Replace code

Bomba
3StarLounger
Posts: 281
Joined: 20 Jan 2019, 19:43

Replace code

Post by Bomba »

In a code, I have the text "2. February 2019" which I want to replace it to "3. March 2019". This code is in Module1 in 31 workbooks which are in the same folder named "3. March 2019". I tried a code (below) which replace text but a message appeared saying "You didn't select a folder!". If the code to replace text is good, where I will select or write the name of the folder.

Code: Select all

Sub ReplaceText()
    Const OldText = "2. February 2019"
    Const NewText = "3. March  2019"
    Dim Folder As String
    Dim File As String
    Dim Wbk As Workbook
    Dim NumLines As Long
    Dim Lines As String
    With Application.FileDialog(4) ' msoFileDialogFolderPicker
        If .Show Then
            Folder = .SelectedItems(1)
        Else
            MsgBox "You didn't select a folder!", vbExclamation
            Exit Sub
        End If
    End With
    Application.ScreenUpdating = False
    Folder = Folder & "\"
    File = Dir(Folder & "*.xlsm")
    Do While File <> ""
        If UCase(File) <> UCase(ThisWorkbook.Name) Then
            Set Wbk = Workbooks.Open(Folder & File)
            With Wbk.VBProject.VBComponents("Module1").CodeModule
                NumLines = .CountOfLines
                Lines = .Lines(1, NumLines)
                Lines = Replace(Lines, OldText, NewText)
                .DeleteLines 1, NumLines
                .AddFromString Lines
            End With
            Wbk.Close SaveChanges:=True
        End If
        File = Dir
    Loop
    Application.ScreenUpdating = True
End Sub
Thanks

User avatar
HansV
Administrator
Posts: 78457
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Replace code

Post by HansV »

The error message indicates that you canceled the Browse dialog...
Best wishes,
Hans

Bomba
3StarLounger
Posts: 281
Joined: 20 Jan 2019, 19:43

Re: Replace code

Post by Bomba »

Is there a way that I fix it?
Thanks

User avatar
HansV
Administrator
Posts: 78457
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Replace code

Post by HansV »

Select a folder in the Browse dialog so that you see a name in the 'Folder name' box and make sure that you click OK instead of Cancel
Best wishes,
Hans

Bomba
3StarLounger
Posts: 281
Joined: 20 Jan 2019, 19:43

Re: Replace code

Post by Bomba »

Hi
After I selected the folder and run the code, the line "With Wbk.VBProject.VBComponents("Module1").CodeModule" became highlighted.
Thanks

User avatar
HansV
Administrator
Posts: 78457
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Replace code

Post by HansV »

That probably means that the workbook doesn't have a module named Module1. You can check this in the Project Explorer pane on the left hand side of the Visual Basic Editor.
Best wishes,
Hans