通过在工作簿中的所有工作表的循环宏

插入新的模块工作表中键入下面的宏代码
  1.  Sub WorksheetLoop()
    Dim WS_Count As Integer Dim I As Integer ' Set WS_Count equal to the number of worksheets in the active ' workbook. WS_Count = ActiveWorkbook.Worksheets.Count ' Begin the loop. For I = 1 To WS_Count ' Insert your code here. ' The following line shows how to reference a sheet within ' the loop by displaying the worksheet name in a dialog box. MsgBox ActiveWorkbook.Worksheets(I).Name Next IEnd Sub
  2. 若要进行该宏将插入点放在行中读取"Sub WorksheetLoop(),然后按 F5。
宏将工作簿中循环,并显示每次通过循环运行相应的不同工作表名称与一个消息框。 注意该宏将只显示工作表的名称 ; 它不会在工作簿中显示的其他类型的工作表的名称。

您还可以使用 For Each 循环循环遍历所有工作簿中工作表中。
  1. 插入新的模块工作表中键入下面的宏代码
    Sub WorksheetLoop2()   ' Declare Current as a worksheet object variable.   Dim Current As Worksheet   ' Loop through all of the worksheets in the active workbook.   For Each Current In Worksheets      ' Insert your code here.      ' This line displays the worksheet name in a message box.      MsgBox Current.Name   NextEnd Sub
  2. 若要进行该宏将插入点放在行中读取"Sub WorksheetLoop2(),然后按 F5。
此宏 WorksheetLoop 宏作为完全相同的方式工作,不同之处在于它处理的所有活动工作簿中工作表中使用不同类型的循环。
posted @ 2010-01-15 10:14  Daniel_Lu  阅读(431)  评论(0编辑  收藏  举报