' Try to format the dates
Range("N:N").Select
Selection.NumberFormat = "dd/MM/yyyy"
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
使用此代码尝试修复一些我无法控制的下载数据的问题。该表在存储为文本的日期前面有一个空格。例如“2013 年 4 月 11 日”
在 Excel 中执行手动查找和替换可以解决问题,但我希望随后对数据进行透视并进行分组,当我尝试使用 VBA 执行此操作时,它会执行两件事...
它不会将所有记录识别为日期。即使单元格格式发生更改,有些仍保留为常规。这意味着用户必须使用 F2+Enter 浏览每一行,然后对数据透视表进行大量的修改。
它颠倒了日/月。即原始数据为 01/10/2013(10 月 1 日),并将其转换为 1 月 10 日。
是否有查找/替换的修复或循环修复单元格格式的方法。
最佳答案
对于非 VBA 解决方案,您可以在此实例中尝试 DATEVALUE
函数。
用法类似于
=DATEVALUE(Trim(A1))
或
=DATEVALUE(RIGHT(A1, LEN(A1)-1)
假设您的日期位于单元格 A1 中
对于 VBA 解决方案,类似于
Public Sub ConvertToDate()
Dim endRow As Long
Dim ws As Worksheet
Dim dateColumn As Long
Dim dateval As String
Set ws = Sheet1
'set date column (in this case we set column A)
dateColumn = 1
endRow = ws.Cells(ws.Rows.Count, dateColumn).End(xlUp).Row
For i = 2 To endRow
Dim length As Long
length = Len(ws.Cells(i, dateColumn)) - 1
'just a quick and dirty check to see if there is value data
'it isn't set to check for numeric data, so if there is some dodgy
'string data in the cell then it will fail on the CDate line.
If length > 3 Then
'store date string (may use Trim() or Mid() etc...)
dateval = Right(ws.Cells(i, dateColumn).Value, length)
'convert to date and change cell value
ws.Cells(i, dateColumn).Value = CDate(dateval)
End If
Next i
End Sub
关于vba - Excel-VBA : Find and Replace and Date Formatting from String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19772933/