Search code examples
vbaexceldebuggingexcel-2007

VBA : find strings in the textbox and change them into a certain string


I want to make a macro that changes every month in the textbox into a certain month entered in dialog box.
Here's what I wrote. There's no error, but it didn't do the work either. Could you help find the problem? Thank you.

Sub ChangeMonth()
Dim xWs As Worksheet
Dim shp As Shape
Dim xFindStr As String
Dim xReplace As String
Dim z As Integer
Set xWs = Application.Sheets("Mail")
xReplace = Application.InputBox("Replace to :", "Replacement", "", Type:=2)
'On Error Resume Next
For Each shp In xWs.Shapes
    xValue = shp.TextFrame.Characters.Text
    For x = 1 To 12
        shp.TextFrame.Characters.Text = VBA.Replace(xValue, MonthName(x), "xxxx")
    Next x
    shp.TextFrame.Characters.Text = VBA.Replace(xValue, "xxxx", xReplace)
Next
End Sub

Solution

  • This main issue was that you were replacing all the MonthName by "xxxx", but you put that value in the shape's text directly, and yet you used xValue :

    Sub ChangeMonth()
        Dim xwS As Worksheet
        Dim ShP As Shape
        Dim xFindStr As String
        Dim xReplace As String
        Dim z As Integer
    
        Set xwS = ThisWorkbook.Sheets("Mail")
        xReplace = InputBox("Replace to :", "Replacement", "", Type:=2)
    
        'On Error Resume Next
        For Each ShP In xwS.Shapes
            xValue = ShP.TextFrame.Characters.Text
            For x = 1 To 12
                xValue = VBA.Replace(xValue, MonthName(x), xReplace)
            Next x
            ShP.TextFrame.Characters.Text = xValue
        Next ShP
    End Sub