我是VBA的初学者,我一整天都在试着弄清楚我的代码有什么问题:
Sub DataTransfer():
Dim position As Integer, location (1 To 9) As String
location(1) = "BC"
location(2) = "Calgary"
location(3) = "Edmonton"
location(4) = "Major Projects"
location(5) = "Minneapolis"
location(6) = "Saskatchewan"
location(7) = "Seattle"
location(8) = "Toronto"
location(9) = "Winnipeg"
For position = 1 To 9
Worksheets(location(position)).Select
Cells(1, 2).Value = location(position)
Next position
End Sub
编辑:抱歉我的问题含糊不清。我最终想要做的是实际上能够将第三行(将城市名称写入工作表)更改为我想要的任何功能,以便按我认为合适的方式修改工作表。这实际上是我打破解决问题的一个更大的子程序的一部分。这些工作表散布在其他工作表之间,不幸的是,@ nutsch的解决方案并没有真正达到我想要的目标(但无论如何都要感谢)。
我遇到的最大问题是这个确切的代码有时会按预期工作,而其他时候会使"下标退出范围"第四行的错误。
答案 0 :(得分:0)
可能是工作表名称问题。你有多少工作表不需要更新?你能做到吗
dim sht as worksheet
for each sht in activeworkbook.sheets
sht.cells(1,2)=sht.name
next
答案 1 :(得分:0)
我假设您正在尝试将工作表名称放入它对应的工作表中?如果是这样,问题是您使用Select
而不是Activate
来提供Worksheet
焦点。
由于您使用Cells
而没有限定符,因此它会引起问题,因此它引用了代码中未更改的ActiveSheet
。
两种解决方案:
Activate
,Cells
可以按您的方式工作。Cells
前面使用工作表对象来限定对Sub DataTransfer():
Dim position As Integer, location(1 To 9) As String
location(1) = "BC"
location(2) = "Calgary"
location(3) = "Edmonton"
location(4) = "Major Projects"
location(5) = "Minneapolis"
location(6) = "Saskatchewan"
location(7) = "Seattle"
location(8) = "Toronto"
location(9) = "Winnipeg"
For position = 1 To 9
Worksheets(location(position)).Activate
Cells(1, 2).Value = location(position)
Next position
End Sub
的调用。选项1
Sub DataTransfer():
Dim position As Integer, location(1 To 9) As String
location(1) = "BC"
location(2) = "Calgary"
location(3) = "Edmonton"
location(4) = "Major Projects"
location(5) = "Minneapolis"
location(6) = "Saskatchewan"
location(7) = "Seattle"
location(8) = "Toronto"
location(9) = "Winnipeg"
For position = 1 To 9
'this line really does nothign now
Worksheets(location(position)).Select
Worksheets(location(position)).Cells(1, 2).Value = location(position)
Next position
End Sub
选项2
Worksheet
我更喜欢选项2,因为它不需要先激活{{1}}。在可能的情况下,应始终避免激活和选择。它们减慢了速度,使代码与强大的代码相反。
最后,正如@nutsch指出的那样,有更简单的方法来做同样的事情,但是值得知道为什么你的代码不起作用。