我想在多张纸上运行代码。工作表名称为:Sheet1,Sheet2,1,2,3,5,5,7,8,9,10,11,12和摘要。我定义我的感兴趣的表=(1,2,3,4和摘要)。代码应仅在这些工作表上运行。如果没有感兴趣的纸张中的任何纸张,它应该针对所有其他感兴趣的纸张运行,即如果1,2不存在则应该运行3,4和摘要。
答案 0 :(得分:1)
您可以loop
将每张工作表放入工作簿
Option Explicit
Dim ws As Worksheet, a As Range
Sub forEachWs()
For Each ws In ActiveWorkbook.Worksheets
Call yourcode
Next
End Sub
答案 1 :(得分:0)
这是一个非常基本的问题,您应该通过谷歌搜索来找到答案。虽然here与this相结合可以为您解答。
Sub WorksheetLoop()
Dim WS_Count As Integer
Dim I As Integer
Dim found As Integer
Dim index As Integer
Dim sheetnames {"1", "2", "Summary"}
' 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
found = 0;
For index = 0 To numbers.GetUpperBound(0)
If sheetnames(index) = ActiveWorkbook.Worksheets(I).Name Then
found = 1
EndIf
Next
If found = 1 Then
' 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
EndIf
Next I
End Sub
答案 2 :(得分:0)
作为For ... Next Loop的替代方案,这将适用于所有编号的工作表:
Sub AllSheets()
Dim wrkSht As Worksheet
For Each wrkSht In ThisWorkbook.Worksheets
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Or any workbook.worksheets reference: '
'For Each wrkSht In ActiveWorkbook.Worksheets '
'For Each wrkSht In Workbooks("Book2.xlsx").Worksheets '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If IsNumeric(wrkSht.Name) Then
'Your code here.
End If
Next wrkSht
End Sub
作为一个完整的替代方法,您可以将所需的工作表名称放在工作簿的某个范围内,为该范围指定一个已定义的名称并使用它:
Sub All()
Dim rCell As Range
Dim wrkSht As Worksheet
For Each rCell In Range("MyDefinedSheetNameRange")
If WorkSheetExists(rCell.Value) Then
Set wrkSht = ThisWorkbook.Worksheets(rCell.Value)
'Do stuff with wrksht
End If
Next rCell
End Sub
Public Function WorkSheetExists(SheetName As String) As Boolean
Dim wrkSht As Worksheet
On Error Resume Next
Set wrkSht = ThisWorkbook.Worksheets(SheetName)
WorkSheetExists = (Err.Number = 0)
Set wrkSht = Nothing
On Error GoTo 0
End Function
答案 3 :(得分:0)
For Each sht In ThisWorkbook.Sheets
If sht.Name <= 12 Then
'
'
'MsgBox sht.Name
End If
Next