2014-06-23 134 views
-1

错误被扔在这之前合作行错误1004自动填充

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

只是确保'localLastRow'是一个有效的数字'> 2' –

+0

它返回5091,所以不应该是错误来源 –

+0

,但你确定它是> 2吗?那很可能会导致问题标题中的1004 ... –

回答

1

我提到上面是错误解决方案。阅读this了解为什么依赖SelectActivate方法的背景通常存在问题,应始终避免。您已经遇到了一个令人沮丧的问题 - 那就是您需要跟踪哪张表处于“活动”状态,并不断更新代码以使相应的表格“处于活动状态”。这使得代码难以浏览,而且执行起来更加昂贵。

适当的解决办法是完全限定的范围,例如:

ThisWorkbook.Sheets("data").Range("AJ2:AM2").AutoFill Destination:=ThisWorkbook.Sheets("data").Range("AJ2:AM" & localLastRow) 

为什么?

因为,如您所见,不合格范围总是指的是ActiveSheet。一种解决方案(错误的)是连续制作正确的纸张Active。正确的解决方案是完全限定您的范围,尤其是在多个工作簿或工作表中工作时。

+0

我发现你发布的帖子相当有帮助。我和问问题的人差不多。谢谢!在我的情况下,这是值得明确提到打开的第二个工作簿,而不是激活它并参考这种方式?或者,既然这里只有两个工作簿,那么使用ActiveWorkbook引用打开的工作簿就等于使用变量来引用? –

+0

IMO最好的做法是始终使用变量来表示工作簿,而不是“ActiveWorkbook”关键字。 –

+1

++ @DavidZemens还值得一提的是,'sourceLastRow = Range(“A”&Rows.Count).End(xlUp)。Row'也应该是完全合格的 –