vba - Excel-VBA : Find and Replace and Date Formatting from String

标签 vba excel replace find

    ' 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 执行此操作时,它会执行两件事...

  1. 它不会将所有记录识别为日期。即使单元格格式发生更改,有些仍保留为常规。这意味着用户必须使用 F2+Enter 浏览每一行,然后对数据透视表进行大量的修改。

  2. 它颠倒了日/月。即原始数据为 01/10/2013(10 月 1 日),并将其转换为 1 月 10 日。

是否有查找/替换的修复或循环修复单元格格式的方法。

最佳答案

对于非 VBA 解决方案,您可以在此实例中尝试 DATEVALUE 函数。

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/

相关文章:

excel - 我可以在 VBA 中使用 .res(资源)文件吗?这样做有好处吗?

c# - 在 C# 中使用 OLEDB 读取受密码保护的 excel 文件

c# - 尝试使用 epplus 读取 excel 文件并出现 System.NullException 错误?

mysql - phpmyadmin 中的字符串替换,同时保留内部文本

python - 使用正则表达式将韩文文本解析为列表

html - 如何在 HTA 文件中使用 VBScript 单击按钮

vba - 加快 VBA 速度吗?

vba - 错误 440 : Method 'Create' of object 'PivotCaches' failed

forms - 如何创建允许上面插入的 MS-Word-Form-Region?

python - 如何替换元组列表中的某些字符