带有一些工作表的 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 15:39:25  来源:igfitidea点击:

VBA-Loop with some worksheets

excelvbaloopsexcel-vba

提问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 Nextis evil ;) Use it only when necessary.

1)使用On Error Resume Next是邪恶的 ;) 仅在必要时使用它。

2)Don't use .SELECTIt 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 ivariable... you've just put 1 + 1so it always evaluates to 2

所以它使用你的i变量......你刚刚把1 + 1它总是评估为2

A classic mistake :)

一个经典的错误:)