我有三本工作簿;所有这些都包含相同政策的信息,但来自不同的文件。我正在尝试从工作簿1和工作表中具有相同工作表名称的每个工作表中复制相同单元格的值。工作簿3.这是我的代码:
Sub foo()
Dim wbk1 As Workbook
Dim wbk2 As Workbook
Dim wkb3 As Workbook
Dim shtName As String
Dim i As Integer
Set wkb1 = Workbooks.Open("C:\Users\lliao\Documents\Trad Reconciliation.xlsx")
Set wkb2 = Workbooks.Open("C:\Users\lliao\Documents\TradReconciliation.xlsx")
Set wkb3 = Workbooks.Open("C:\Users\lliao\Documents\Measure Trad Recon LS.xlsx")
shtName = wkb2.Worksheets(i).Name
For i = 2 To wkb2.Worksheets.Count
wkb2.Sheets(shtName).Range("D3").Value = wkb1.Sheets(shtName).Range("D2")
wkb2.Sheets(shtName).Range("E3").Value = wkb1.Sheets(shtName).Range("E2")
wkb2.Sheets(shtName).Range("F3").Value = wkb1.Sheets(shtName).Range("F2")
wkb2.Sheets(shtName).Range("D4").Value = wkb3.Sheets(shtName).Range("D2")
wkb2.Sheets(shtName).Range("E4").Value = wkb3.Sheets(shtName).Range("E2")
wkb2.Sheets(shtName).Range("F4").Value = wkb3.Sheets(shtName).Range("F2")
Next i
End Sub
我不明白我是如何使用下标错误的。这是我第一次编写VBA(5年来第一次),所以我不熟悉编码错误。
谢谢!
答案 0 :(得分:3)
Dim i As Integer Set wkb1 = Workbooks.Open("C:\Users\lliao\Documents\Trad Reconciliation.xlsx") Set wkb2 = Workbooks.Open("C:\Users\lliao\Documents\TradReconciliation.xlsx") Set wkb3 = Workbooks.Open("C:\Users\lliao\Documents\Measure Trad Recon LS.xlsx") shtName = wkb2.Worksheets(i).Name
变量i
已声明,但在分配之前使用 - 因此其值为隐式0
。
VBA集合从1开始,这使得wkb2.Worksheets(i)
超出范围。
Dim i As Integer
i = 1
'...
shtName = wkb2.Worksheets(i).Name
将修复它。
你可能想把它移到循环中。
答案 1 :(得分:0)
可能是你之后:
For i = 2 To wkb2.Worksheets.Count
wkb2.Sheets(i).Range("D3:F3").Value = wkb1.Sheets(i).Range("D2:F2")
wkb2.Sheets(i).Range("D4:F4").Value = wkb3.Sheets(i).Range("D2:F2")
Next i