通过非活动工作表循环

时间:2019-01-29 15:46:12

标签: excel vba

除非我转到每个选项卡并运行它,否则循环代码不会一次出现在所有工作表上

Dim Sheets As Variant
Dim Sheet As Variant

Sheets = Array("1", "2", "3", "4", "5", "6")

For Each Sheet In ActiveWorkbook.Sheets

If Range("G2").Value = 1 Then Range("h10:h11").Value = 
Range("N10:N11").Value
If Range("G2").Value = 1 Then Range("h14:h22").Value = 
Range("N14:N22").Value
If Range("G2").Value = 1 Then Range("h27:h29").Value = 
Range("N27:N29").Value
Next Sheet

我该如何修复我的代码,以便当我在选项卡1上更改所有其他选项卡

2 个答案:

答案 0 :(得分:1)

如果您未在代码中指定父级工作表,则只会得到活动工作表。使用With块:

Dim Shts As variant
Dim Sheet As Worksheet

Shts = Array("1", "2", "3", "4", "5", "6")

For Each Sheet In ActiveWorkbook.WorkSheets
    With Sheet
        If .Range("G2").Value = 1 Then 
            .Range("h10:h11").Value = .Range("N10:N11").Value
            .Range("h14:h22").Value = .Range("N14:N22").Value
            .Range("h27:h29").Value = .Range("N27:N29").Value
        End If
    End With
Next Sheet

答案 1 :(得分:0)

类似的事情,还检查工作表是否存在,并提供跳过活动工作表的选项

if(isset($_SESSION['user'])){
    $user = $_SESSION['user'];
}else{
    $user = 'Anonymous'; // or guest or whatever you want
}