如何使用 VBA 在 Excel 评论中查找和替换日期格式

How to Find and Replace date format in Excel Comments using VBA

我的单元格带有如下评论:

May 26, 2017: Reduced from 1000 to 900

我想使用 VBA 仅查找和替换以下评论中的日期格式:

MMM DD, YYYY

YYYY/MM/DD

我搜索了几个小时后找到的最好的代码如下,但不幸的是,它只能查找文本并将文本替换为文本。我试图让它与格式一起工作,但我做不到。

Sub ReplaceComments()
Dim cmt As Comment
Dim wks As Worksheet
Dim sFind As String
Dim sReplace As String
Dim sCmt As String
sFind = "2011"
sReplace = "2012"
For Each wks In ActiveWorkbook.Worksheets
For Each cmt In wks.Comments
sCmt = cmt.Text
If InStr(sCmt, sFind) <> 0 Then
sCmt = Application.WorksheetFunction. _
Substitute(sCmt, sFind, sReplace)
cmt.Text Text:=sCmt
End If
Next
Next
Set wks = Nothing
Set cmt = Nothing
End Sub

您可以试试下面的代码。

确保在使用之前复制您的作品。 正如@Kevin 所说,成功将取决于数据输入过程中使用的格式变化。 您提供的代码遍历了您工作簿中的所有工作表,是您想要的吗?

还是试一下,不合适再来

Sub test_comment()

Dim Wsh As Worksheet
Dim Cmt As Comment

For Each Wsh In ActiveWorkbook.Sheets
    For Each Cmt In Wsh.Comments
        If InStr(1, Cmt.Text, ":") > 0 Then
            St1 = Cmt.Text
            St2 = Format(Left(St1, InStr(1, St1, ":") - 1), "YYYY/MM/DD")
            Cmt.Text St2 & Mid(St1, InStr(1, St1, ":"))
        End If
    Next Cmt
Next Wsh

End Sub

多行新尝试:

Sub test_comment()

Dim Wsh As Worksheet
Dim Cmt As Comment

For Each Wsh In ActiveWorkbook.Sheets
    For Each Cmt In Wsh.Comments
        Arr1 = Split(Cmt.Text, Chr(10))
        For i = 0 To UBound(Arr1)
            If InStr(1, Arr1(i), ":") > 0 Then
                St1 = Arr1(i)
                St2 = Format(Left(St1, InStr(1, St1, ":") - 1), "YYYY/MM/DD")
                Arr1(i) = St2 & Mid(St1, InStr(1, St1, ":"))
                Cmt.Text Join(Arr1, Chr(10))
            End If
        Next i
    Next Cmt
Next Wsh

End Sub