【发布时间】:2020-04-23 06:00:08
【问题描述】:
我在 Excel 中使用 VBA 处理应用程序。我正在尝试获取工作簿中特定数据的单元格引用,以基于单元格引用构建一个 do while 循环。我无法弄清楚为什么引用没有加载到我为其配置的变量中。我已经将这种方法用于同一工作簿中存在的数据,所以我认为它与对其他工作簿的引用有关。无论 MsgBox 是在激活合并器电子表格之前还是之后,我都会收到相同的错误(运行时 91)。具体来说,未加载 firstDataCell 和 lastDataCell 变量。我试图操纵这篇文章中的代码,但一无所获:Excel VBA - .Find method between workbooks
这是我的(截断的)代码:
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
请帮我确定我的查找失败的地方。
提前谢谢你
【问题讨论】:
-
不要依赖
Activate。Range("A1", Range("A65536").End(xlUp))中的每个Range调用都应符合工作簿/工作表。 -
还使用 Find 指定所有参数以确保安全。我不明白为什么您的代码会出错,即使 RTE91 建议找不到该值。
-
奇怪...从搜索字符串中删除
.End(xlup)解决了这个问题。该代码在我设计的其他电子表格中运行良好。它以毫秒为单位工作,所以我现在不太担心。我不会在嘴里看礼物马。 BigBen,根据您的建议,我将努力清理代码中的activate调用。还有一些这里没有展示。