我对VBA比较陌生。我想为将在工作簿中的所有工作表中循环的宏创建此循环。基本上,我想做的是将“ G”列中的所有日期更改为从8/15/2018到201808(yyyymm)。这是录制的宏:
Sheets("Sheet1").Select
Columns("G:G").Select
Selection.NumberFormat = "yyyymm"
Application.ScreenUpdating = False
我该怎么做?
答案 0 :(得分:4)
您可以循环工作表集合以将该列的格式应用于每个表。使用工作表集合的优点是避免了工作簿中的任何图表表。
Option Explicit
Public Sub ApplyFormatting()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Columns("G:G").NumberFormat = "yyyymm"
Next
End Sub
如果您使用的是字符串而不是日期,则可以尝试将字符串转换为日期格式,例如
Option Explicit
Public Sub ApplyFormatting()
Dim ws As Worksheet, inputArray(), lastRow As Long
For Each ws In ThisWorkbook.Worksheets
With ws.Columns("G:G")
lastRow = ws.Cells(.Rows.Count, "G").End(xlUp).Row
inputArray = ws.Range("G1:G" & lastRow).Value
inputArray = ProcessArray(inputArray)
.Cells(1, 1).Resize(UBound(inputArray, 1), UBound(inputArray, 2)) = inputArray
.NumberFormat = "yyyymm"
End With
Next
End Sub
Public Function ProcessArray(ByRef inputArray As Variant) As Variant
Dim i As Long
For i = LBound(inputArray, 1) To UBound(inputArray, 1)
inputArray(i, 1) = GetDate(inputArray(i, 1))
Next
ProcessArray = inputArray
End Function
Public Function GetDate(ByVal dateString As String) As String
Dim arr() As String
If dateString = vbNullString Or Not InStr(dateString, "/") > 0 Then
GetDate = vbNullString
Else
arr = Split(dateString, "/")
GetDate = Format$(DateSerial(arr(2), arr(0), arr(1)), "yyyy-mm-dd")
End If
End Function