Sub LoopingAccr()
Dim i As Integer
Dim fPath As String
Dim fName As String
For i = 6 To 1000
fPath = "*path address"
fName = Worksheets("sheet2").Cells(i, 3).Value
Workbooks.Open Filename:=fPath & fName
Workbooks(fName).Worksheets("Gross Profit Margin").Activate
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
Range("C31:I31").Copy
Workbooks("Macro Test").Worksheets("sheet2").Activate
Worksheets("sheet2").Cells(i, 5).Select
Selection.PasteSpecial xlPasteValues
Workbooks(fName).Close SaveChanges:=False
Next i
End Sub
当我尝试运行上面的代码时,四行之后会出现一条错误消息,但是目前我有81行数据。我在这里做什么错了?
答案 0 :(得分:0)
尝试与此类似的代码:
Sub LoopingAccr()
Dim i As Integer
Dim fPath As String
Dim fName As String
dim sh as worksheet
' no need to set in every cicle
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
For i = 6 To 1000
fPath = "*path address"
' I hope that path address is ended with application.pathseparator
fName = Worksheets("sheet2").Cells(i, 3).Value
Workbooks.Open Filename:=fPath & fName
' nono: Workbooks(fName).Worksheets("Gross Profit Margin").Activate
for each sh in Workbooks(fName).Worksheets
if sh.name="Gross Profit Margin" then
Workbooks(fName).sh.Activate
Range("C31:I31").Copy
Workbooks("Macro Test").Worksheets("sheet2").Activate
Worksheets("sheet2").Cells(i, 5).Select
Selection.PasteSpecial xlPasteValues
end if: next sh
Workbooks(fName).Close SaveChanges:=False
Next i
End Sub