Home » excel » excel – Error when trying to find & replace the qoute sign " with Range.Replace

excel – Error when trying to find & replace the qoute sign " with Range.Replace

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a macro file that split files and names them by specific list The names of the files in this list that contain the quote sign " is not getting created and I want to find and replace all of them with regular space in that range only.

But when I run the macro it returns me

Argument not optional.

Can someone find where is my problem?

'Loop for creating files
For i = 2 To FilesCounter
    NewWBName = EmailWS.Cells(i, 1).Value
    Set NewWB = Workbooks.Add

    With SplitWS
        .Range(.Cells(1, 1), .Cells(LastRow, LastColumn)).AutoFilter Field:=1, Criteria1:=NewWBName
        .Range(.Cells(1, 2), .Cells(LastRow, LastColumn)).SpecialCells(xlCellTypeVisible).Copy  'Copy cells starting from column B
    End With

    With NewWB.Worksheets(1)
        .Cells(1, 1).PasteSpecial xlPasteFormats
        .Cells(1, 1).PasteSpecial xlPasteValues
        .Cells.EntireColumn.AutoFit
    End With

    'find and replace all th " in the WB names list
    With EmailWS
        .Range("$A:$A").Replace What:=""", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False"
        .Cells(i, 1).Value = NameForFile & "" & NewWBName
    End With

    NewWB.SaveAs fileName:=DesPath & "\" & NameForFile & "" & NewWBName & ".xlsx", Password:=PassFile
    NewWB.Close

Next i
How to&Answers:

" in VBA can be written as """" or Chr(34)

""" is not the same as """"

In the immediate window type this

?Chr(34)
"    '<~~ This is what you will get

and then this

?"""" = Chr(34)
True '<~~ This is what you will get

Now try

?""" = Chr(34)

See what you get 🙂

In your code, replace """ by """" or Chr(34) so it becomes What:=""""