多个工作表的Excel宏循环代码

时间:2013-11-01 05:22:13

标签: excel vba

我有一张表的分隔列代码。如何使用循环来创建超过工作表的代码?

Sub Macro1()

    Selection.TextToColumns Destination:=ActiveCell, DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
        :="_", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
    ActiveCell.Offset(0, 1).Columns("A:A").EntireColumn.Select
    Selection.NumberFormat = "dd-mm-yyyy;@"

End Sub

2 个答案:

答案 0 :(得分:1)

Sub t()
    Dim sh As Worksheet
    For Each sh In ActiveWorkbook.Sheets
        'do what you want, for example, 
        Range("A1:B10").TextToColumns Destination:=ActiveCell, DataType:=xlDelimited, _
            TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
            Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
            :="_", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
        ActiveCell.Offset(0, 1).Columns("A:A").EntireColumn.Select
        Selection.NumberFormat = "dd-mm-yyyy;@"
    Next
End Sub

但是,您不应该使用Selection。您应该使用range代替,例如Range("A1:B10")

答案 1 :(得分:0)

尝试这样

Sub forEachWs()
Dim x As Long
Dim ws As Sheets

For x = 1 To 12'<--to as how many is required
ThisWorkbook.Sheets(x).Activate
    Call Macro1  '<---the name of your macro
    Range("A2").Select
End Sub