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 - 宏来计数过滤器不同的唯一值

c# - 仅使用 VSTA 在 Corel Draw X6 中创建自定义控件

Excel VBA 用户定义函数,计算具有条件格式的单元格

excel - 使用 github 存储 Excel 文件

python - 将 -inf 值替换为 pandas.series 特征中的 np.nan

java Replace - 替换由空格和换行符分隔的两个标签之间的字符串中的文本

javascript - 替换从外部for循环加载的html字符串中的字符

excel - 如何以编程方式将工具栏按钮(和 OnClick 处理程序)添加到 Excel

excel - 如何在 For Each 循环之外创建一个 vbYesNo MsgBox?

vba - Excel VBA 类型不匹配 #N/A