多张纸的宏无法正常工作

时间:2014-07-03 20:02:34

标签: excel vba excel-vba

Sub RunMacroOnAllSheetsToRight()
    For i = ActiveSheet.Index To Sheets.Count
        Call MyFunction(i)
    Next i
End Sub

Function MyFunction(i)
    'Code goes here
     Columns("R:R").ColumnWidth = 8.1
     [S1].Resize(, 14).EntireColumn.Insert
    MsgBox "I'm currently on sheet " & ThisWorkbook.Sheets(i).name
End Function

我找到了一个用于运行宏的代码示例,该代码应该在活动窗口右侧的所有工作表上运行,但它不起作用,它一直在一张纸上运行,但msgbox向我显示纸张已更改(每次显示不同的名称)。你能帮助我吗?我是vba-excel的新手。

1 个答案:

答案 0 :(得分:1)

您需要激活每张纸。然后激活原始表格。

  Sub RunMacroOnAllSheetsToRight()
  Dim a As Integer

    a = ActiveSheet.Index 'Save current sheet

    For i = a To Sheets.Count
        Call MyFunction(i)
    Next i
   Sheets(a).Activate 'At the end, activate original sheet
End Sub

Function MyFunction(i)
    'Code goes here
    Sheets(i).Activate 'Activate each sheet
     Columns("R:R").ColumnWidth = 8.1
     [S1].Resize(, 14).EntireColumn.Insert
    MsgBox "I'm currently on sheet " & ActiveSheet.Name 'Trustworthy information
End Function