我在Excel中使用VBA应用程序。我试图获取一个工作簿中特定数据的单元格引用,以根据单元格引用建立一个do while循环。我不明白为什么引用没有加载到我为它配置的变量中。我已经对存在于同一工作簿中的数据使用了这种方法,所以我认为这与对其他工作簿的引用有关。无论MsgBox是在激活合并器电子表格之前还是之后,我都会得到同样的错误(运行时91)。具体来说,firstDataCell和lastDataCell变量没有加载。我试着操作这个帖子中的代码,但一无所获。Excel VBA - .Find方法在工作簿之间的问题
这是我的(截断的)代码。
Dim wbConsolidator As Workbook 'Variable to store this workbook
Dim wbQ1Actuals As Workbook 'Variable to store workbook with quarter 1 actuals
Dim wsExist As Boolean 'Variable to store if the worksheet exists in the actuals workbook t/f
Dim searchRange As Range 'Variable to store the range to search for budget data
Dim firstDataCell As Range 'Variable to store first data cell
Dim lastDataCell As Range 'Variable to store the last data cell
Dim tabName As String 'Variable to store employee's tab name
Dim notIn414 As String 'Variable to store employees the VB could not find in 414
Set wbConsolidator = Workbooks("Consolidator.xlsm")
'Store consolidation workbook into variable
Set wbQ1Actuals = Workbooks("(the spreadsheet title")
'Store worbook with Q1 actuals into variable
tabName = calculated based on the employee's name. This functions correctly and the correct tab activates
If wsExist = True Then 'Check if wsExist is false after all loops
wbQ1Actuals.Worksheets(tabName).Activate
Set searchRange = Range("A1", Range("A65536").End(xlUp))
Set firstDataCell = searchRange.Find("Pay Date", LookIn:=xlValues, lookat:=xlWhole)
'Find the first row with budget percentages
Set lastDataCell = searchRange.Find("Total:", LookIn:=xlValues, lookat:=xlWhole)
'Find the sum row to track last row with budget percentages
Else
notIn414 = notIn414 & lastName & "," & firstName & ":"
'Write the employee's name to the error log
End If 'End this test
wbConsolidator.Activate 'Activate the main spreadsheet
If lastDataCell Is Nothing Then
MsgBox "The variable is blank."
Else
MsgBox lastDataCell.Row
End If
请帮我找出我的查找失败的地方。
先谢谢你
像这样的东西应该是比较健壮的。
Set wbConsolidator = Workbooks("Consolidator.xlsm")
Set wbQ1Actuals = Workbooks("(the spreadsheet title")
tabName = "someUserName"
If wsExist Then
With wbQ1Actuals.Worksheets(tabName)
'all range references are fully-qualified...
Set searchRange = .Range("A1", .Cells(.Rows.Count, 1).End(xlUp))
End With
Set firstDataCell = searchRange.Find("Pay Date", LookIn:=xlValues, lookat:=xlWhole)
Set lastDataCell = searchRange.Find("Total:", LookIn:=xlValues, lookat:=xlWhole)
Else
notIn414 = notIn414 & lastName & "," & firstName & ":"
End If
If lastDataCell Is Nothing Then
MsgBox "The variable is blank."
Else
MsgBox lastDataCell.Row
End If