簡體   English   中英

遍歷不同的工作表

[英]Looping through different sheets

感謝您對我要創建的宏的幫助。

我有一個帶有一堆工作表的xls文件,其中一些工作表名為“ 1”,“ 2”,“ 3”,依此類推。 我想創建一個僅在那些“以數字命名”的工作表中循環的宏,因此不按照下面的代碼中的索引進行循環。 (表“ 1”不是工作簿中的第一頁)。 在循環之前,我需要定義單元格范圍和工作表。

以下是我的(錯誤的)嘗試。

Sub Refresh ()

Dim i As Integer
Dim rng As Range
Set rng = Range("A10:TZ180")

 For i = 1 To 30

  Sheets(i).Activate
  rng.Select       
  rng.ClearContents
  Application.Run macro:="xxx"

 Next i

End Sub
dim w as worksheet
for each w in activeworkbook.worksheets
  if isnumeric(w.name) then
    w.range("A10:TZ180").clearcontents
    xxx()
  end if
next

如果宏“ xxx()”需要選定的范圍,則只需添加一條選擇語句。 (從格塞爾借來的)

Dim w As Worksheet
For Each w In ActiveWorkbook.Worksheets
  If IsNumeric(w.Name) Then
    w.Range("A10:TZ180").ClearContents
    w.Range("A10:TZ180").Select
    Application.Run macro:="xxx"
  End If
Next

為了消除您對分配范圍的誤解,請參見以下內容:

Sub Refresh()
    Dim ws As Worksheet
    Dim rng As Range
    Dim i As Integer

    For Each ws In ActiveWorkbook.Worksheets
        If IsNumeric(ws.Name) Then

            'you must activate the worksheet before selecting a range on it
            ws.Activate

            'note the qualifier: ws.range()
            Set rng = ws.Range("A10:TZ180")

            'since the range is on the active sheet, we can select it
            rng.Select
            rng.ClearContents
            Application.Run macro:="xxx"
        End If
    Next

End Sub

Sub test2()
    Dim ws As Worksheet
    Dim rg As Range

    Dim arrSheets As Variant
    arrSheets = Array("Sheet1", "Sheet2", "Sheet3")

    Dim x As Long
    For x = LBound(arrSheets) To UBound(arrSheets)
        Set ws = Worksheets(arrSheets(x))
        ws.Activate

        '...

    Next
End Sub

Sub test3()
    Dim ws As Worksheet

    Dim x As Long
    For x = 1 To 20
        Set ws = Worksheets(CStr(x))
        ws.Activate

        '...

    Next
End Sub

嘗試這個

Sub main()
Dim shtNames As Variant, shtName As Variant

shtNames = Array(1, 2, 3, 4) '<== put your actual sheets "number name"

For Each shtName In shtNames
    With Worksheets(CStr(shtName))
        .Range("A10:TZ180").ClearContents
        .Range("A10:TZ180").Select
        Application.Run macro:="MacroToRun"
    End With
Next shtName

End Sub


Sub MacroToRun()

MsgBox "hello from cells '" & Selection.Address & "' in sheet '" & ActiveCell.Parent.Name & "'"
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM