Ema*_*nez -1 excel vba excel-vba
我是VBA的新手。我想为将在工作簿中的所有工作表中循环的宏创建此循环。基本上,我想做的是将“ G”列中的所有日期更改为从8/15/2018到201808(yyyymm)。这是录制的宏:
Sheets("Sheet1").Select
Columns("G:G").Select
Selection.NumberFormat = "yyyymm"
Application.ScreenUpdating = False
Run Code Online (Sandbox Code Playgroud)
我将如何去做呢?
您可以循环工作表集合以将每一列的格式应用于该表。使用工作表集合的优点是可以避免工作簿中包含任何图表表。
Option Explicit
Public Sub ApplyFormatting()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Columns("G:G").NumberFormat = "yyyymm"
Next
End Sub
Run Code Online (Sandbox Code Playgroud)
如果您使用字符串而不是日期,则可以尝试将字符串转换为日期格式,例如
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
Run Code Online (Sandbox Code Playgroud)