Reputation: 346
I have Cells with Comments such as the following:
May 26, 2017: Reduced from 1000 to 900
I want to use VBA to Find and Replace only the date format within the comments from:
MMM DD, YYYY
to
YYYY/MM/DD
The best code I could find after searching for several hours is the following but unfortunately, it does only Find and Replace text with a text. I tried to make it work with formats but I couldn't.
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
Upvotes: 1
Views: 354
Reputation: 596
You could try this code below.
Make sure you make a copy of your work before using it. As @Kevin says, success will depend on the format variation used during data entry. The code you provided is going through all sheets in your workbook, is it what you want ?
Still, make a try and come back if not suitable.
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
New try for multiple lines :
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
Upvotes: 3