在列表VBA中查找动态变量

问题描述 投票:-1回答:1

我试图在不同的工作簿中找到变量(MonthCell)的值。我想要找到的变量在列表中。当我运行下面的代码时,Month变量保持为空,即使应该匹配。我究竟做错了什么?

Sub CreateAList()

Dim ws As Worksheet
Dim wb As Workbook
Dim LastRow As Long
Dim coll As Collection
Dim Hotel As Excel.Range
Dim arr() As String
Dim i As Long
Dim MyFiles As String, ThisMonth As String
Dim startPath As String
Dim WhereCell As Range
Dim Month As Range

Set ws = Application.Workbooks("Booking Pace - Test 
Tool.xlsm").Sheets("Forecast") startPath = 
"C:\Users\gborner\Documents\Projects\"

With ws
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
Set coll = New Collection
For Each Hotel In .Range("A6:A" & LastRow)
    On Error Resume Next
    coll.Add cell.Value, CStr(cell.Value)
    On Error GoTo 0

    Set WhereCell = ThisWorkbook.ActiveSheet.Range("A6:A200").Find(Hotel, 
    LookAt:=xlPart)
    Set MonthCell = ThisWorkbook.ActiveSheet.Range("B3")

    MyFiles = Dir(startPath & "*" & Hotel & "*.*")

    'Do While MyFiles <> ""

        On Error Resume Next
    Application.AskToUpdateLinks = False
    Application.DisplayAlerts = False
    Workbooks.Open startPath & MyFiles

    Set Month = ThisWorkbook.Sheets("Budget").Find(MonthCell, 
    LookIn:=xlValues)
excel vba
1个回答
1
投票

下面的代码循环所有工作表并搜索名为SearchValue的变量。最后填充一个包含所有相关匹配的消息框。

码:

Option Explicit

Sub test()

    Dim ws As Worksheet
    Dim SearchValue As String, FullReport As String
    Dim Position As Range

    SearchValue = "Test"

    For Each ws In ThisWorkbook.Worksheets

        Set Position = ws.UsedRange.Find(SearchValue)

        If Not Position Is Nothing Then
            If FullReport = "" Then
                FullReport = "The word " & SearchValue & " appears in " & ws.Name & ", " & "Column " & Position.Column & " and row " & Position.Row & "."
            Else
                FullReport = FullReport & vbNewLine & "The word " & SearchValue & " appears in " & ws.Name & ", " & "Column " & Position.Column & " and row " & Position.Row & "."
            End If
        End If

    Next ws

    MsgBox FullReport

End Sub

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.