带有一些工作表的 VBA 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9881824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA-Loop with some worksheets
提问by user1115535
I am a beginner and I would like to do a loop in all the worksheets of my excel file, except the first one. However the code below only works on the second one. Could you please explain me what is wrong in this code?
我是一个初学者,我想在我的 excel 文件的所有工作表中做一个循环,除了第一个。但是,下面的代码仅适用于第二个。你能解释一下这段代码有什么问题吗?
Many thanks
非常感谢
Sub MobileTCalculation()
'MobileTCalculation Macro
Dim i As Integer
For i = 1 To 40
Worksheets(1 + 1).Select
Range("A20").Select
On Error Resume Next
Next i
End Sub
采纳答案by Siddharth Rout
If you want to skip the first sheet then change the loop as shown below. Worksheets(i + 1)
will give you errors if there are only 40 sheets in your workbook ;)
如果您想跳过第一张纸,请按如下所示更改循环。Worksheets(i + 1)
如果您的工作簿中只有 40 张,则会出现错误;)
Use this
用这个
Sub MobileTCalculation()
Dim i As Integer
For i = 2 To 40
Worksheets(i).Range("A20").Select
Next i
End Sub
Also two things.
还有两件事。
1)Use of On Error Resume Next
is evil ;) Use it only when necessary.
1)使用On Error Resume Next
是邪恶的 ;) 仅在必要时使用它。
2)Don't use .SELECT
It slows down your code. Instead directly perform the action. For example
2)不要使用.SELECT
它会减慢您的代码速度。而是直接执行操作。例如
Sub MobileTCalculation()
Dim i As Integer
For i = 2 To 40
With Worksheets(i).Range("A20")
Debug.Print .Value
End With
Next i
End Sub
HTH
HTH
Sid
锡德
回答by joshuahealy
You should change:
你应该改变:
Worksheets(1 + 1).Select
so it uses your i
variable... you've just put 1 + 1
so it always evaluates to 2
所以它使用你的i
变量......你刚刚把1 + 1
它总是评估为2
A classic mistake :)
一个经典的错误:)