该行正在抛出错误
ThisWorkbook.Sheets("data").Range("AJ2:AM2").AutoFill Destination:=Range("AJ2:AM" & localLastRow)
以前是合作的,但在我纠正了另一个错误之后,它似乎不再想玩得好了。源包含在目标中。我只是不确定问题的来源。
非常感谢任何帮助。 我在下面发布了整个宏。它最终会被称为主宏。
Sub FormulaUpdate()
'
' FormulaUpdate Macro
' Updates Columns AJ through AS
'
Dim localLastRow As Long
Dim sourceLastRow As Long
Dim wbName As String
Dim wbPath As String
Dim sourceSheet As Worksheet
Dim sourceRange As Range
Dim thisSheet As Worksheet
Application.ScreenUpdating = False
'sets strings from user's selection of Item Branch Report
wbPath = GetFile("Select Item Branch Report to be Used")
wbName = GetFilenameFromPath(wbPath)
Workbooks.Open(wbPath, ReadOnly:=True).Activate
'sets workseets to be referenced
Set sourceSheet = ActiveWorkbook.Sheets(1)
Set thisSheet = ThisWorkbook.Sheets("data")
'counts rows in selected item branch report for use elsewhere in macro
sourceLastRow = sourceSheet.Range("A" & Rows.Count).End(xlUp).Row
'range for use in vlookup formula, for both system leadtime and order min columns
Set sourceRange = sourceSheet.Range("B1:BG" & sourceLastRow)
'Counts rows in this workbook for use elswhere in macro
localLastRow = thisSheet.Range("A" & Rows.Count).End(xlUp).Row
'uses formulas in cells to autofill the data
thisSheet.Range("AJ2:AM2").AutoFill Destination:=thisSheet.Range("AJ2:AM" & localLastRow)
'loops through each row of both the system lead time, and the order min column, and sets the value from item branch report
For i = 2 To localLastRow
thisSheet.Range("AN" & i).Value = Application.WorksheetFunction.VLookup(thisSheet.Range("C" & i), sourceRange, 53, False)
thisSheet.Range("AP" & i).Value = Application.WorksheetFunction.VLookup(thisSheet.Range("C" & i), sourceRange, 58, False)
Application.StatusBar = "Referencing IBR: " & i & " of " & localLastRow & ": " & Format(i / localLastRow, "0%")
Next i
'uses formulas in cells to autofill the data
thisSheet.Range("AO2").AutoFill Destination:=thisSheet.Range("AO2:AO" & localLastRow)
thisSheet.Range("AQ2:AS2").AutoFill Destination:=thisSheet.Range("AQ2:AS" & localLastRow)
Workbooks(wbName).Close (False)
答案 0 :(得分:1)
我在上面提到的是错误的解决方案。请阅读this,了解为什么依赖Select
和Activate
方法通常会出现问题的背景,应始终避免使用。您已经遇到了一个令人沮丧的问题 - 您需要跟踪哪个工作表是"活动"并不断更新代码以获得适当的工作表"活动"。这使得代码难以导航,执行起来更加昂贵。
适当的解决方案是完全限定您的范围,例如:
ThisWorkbook.Sheets("data").Range("AJ2:AM2").AutoFill Destination:=ThisWorkbook.Sheets("data").Range("AJ2:AM" & localLastRow)
<强>为什么吗
因为,正如您所观察到的,不合格的范围总是指的是ActiveSheet
。一个解决方案(错误的解决方案)是连续制作正确的工作表Active
。正确的解决方案是完全限定您的范围,尤其是在处理多个工作簿或工作表时。