通过工作簿中的所有工作表运行我的宏

时间:2016-06-02 19:49:24

标签: excel vba excel-vba

目前我有一个运行的宏并查找标题" DATE"和" DT"在活动工作表中,重新格式化列中的单元格。我希望让它贯穿所有工作表并运行宏。这是当前的VBA代码:

Sub DateFormatting()
    Dim x As Variant
    With ActiveWorksheet
        For Each x In .Range(.Cells(2, 1), .Cells(2, .Columns.Count).End(xlToLeft)).Cells
            If InStr(1, Replace(x.Value, "DATE", "DT", , , vbTextCompare), "DT", vbTextCompare) Then
                Intersect(.UsedRange, .UsedRange.Offset(2), x.EntireColumn).NumberFormat = "m/d/yyyy h:mm"
            End If
        Next
    End With
End Sub

1 个答案:

答案 0 :(得分:1)

总结所有评论:

Option Explicit

Sub DateFormatting2()

Dim x As Variant
Dim ws As Worksheet

For Each ws In ThisWorkbook.Worksheets
    With ws
        For Each x In .Range(.Cells(2, 1), .Cells(2, .Columns.Count).End(xlToLeft)).Cells
            If InStr(1, Replace(x.Value2, "DATE", "DT", , , vbTextCompare), "DT", vbTextCompare) Then
                Intersect(.UsedRange, .UsedRange.Offset(2), x.EntireColumn).NumberFormat = "m/d/yyyy h:mm"
            End If
        Next x
    End With
Next ws

End Sub

评论:

  1. 您错过了s
  2. 末尾的For Each ws In ThisWorkbook.Worksheet
  3. 你在for each ws语句中有with ws循环,而它应该是相反的方式。如果尚未启动,则无法使用ws
  4. 要结束With,您需要End With而不是Next
  5. Option Explicit只是为了做好准备。