保存工作簿Excel VBA时删除非法字符

Alb*_*own 3 excel vba excel-vba save-as illegal-characters

此代码基本上重新格式化了xls文件并将其保存为xlsx。但是,它使用G2H2来获取新格式文件的文件名。因此,这意味着某些字符不能出现在文件名中。我添加了一段代码来替换这些字符(

' Remove/Replace Invalid File Name Characters
 WkbName = Range("H2")
    MyArray = Array("<", ">", "|", "/", "*", "\", ".", "?", """")
    For X = LBound(MyArray) To UBound(MyArray)
        WkbName = Replace(WkbName, MyArray(X), "_", 1)
            Next X
                'MsgBox WkbName     'dispaly file name with illegal characters removed

    ActiveWorkbook.SaveAs Filename:= _
       WBPath & "\BOM_" & Range("G2") & "_" & WkbName & ".xlsx" _
        , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False 
Run Code Online (Sandbox Code Playgroud)

)activeworkbook.save始终是调试器带我的地方

我收到一条错误消息,说即使其中的普通文本中总有非法字符h2,我是否丢失了某些内容?

下面的完整代码

Sub FormatBOMExport()
'
' FormatBOMExportPnV Macro
'
Application.ScreenUpdating = False
Application.DisplayAlerts = False

' delete extra sheets
Sheets(Array("Sheet2", "Sheet3")).Select
    ActiveWindow.SelectedSheets.Delete

WBPath = Application.ActiveWorkbook.Path
OrgFile = Application.ActiveWorkbook.FullName

        Range("B1").Select
    With Selection
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlBottom
        .WrapText = True
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With

    Columns("A:M").Select
    Selection.Replace What:="" & Chr(10) & "", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

    Selection.Columns.AutoFit
    Selection.Rows.AutoFit

    Columns("J:J").Select
        With Selection
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlBottom
        .WrapText = True
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With

'    Columns("J:J").Select
'        Columns("J:J").ColumnWidth = 100
'            Selection.Rows.AutoFit

    Columns("G:G").EntireColumn.AutoFit
        Range("G2").Select

' Remove/Replace Invalid File Name Characters
 WkbName = Range("H2")
    MyArray = Array("<", ">", "|", "/", "*", "\", ".", "?", """")
    For X = LBound(MyArray) To UBound(MyArray)
        WkbName = Replace(WkbName, MyArray(X), "_", 1)
            Next X
                'MsgBox WkbName     'dispaly file name with illegal characters removed

    ActiveWorkbook.SaveAs Filename:= _
       WBPath & "\BOM_" & Range("G2") & "_" & WkbName & ".xlsx" _
        , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

    If Len(Dir$(OrgFile)) > 0 Then
        Kill OrgFile
            End If

  Application.DisplayAlerts = True

Application.ScreenUpdating = True

 ' MsgBox OrgFile & " has been deleted and saved as " & "BOM_" & Range("G2") & "_" & Range("H2") & ".xlsx"

End Sub
`
Run Code Online (Sandbox Code Playgroud)

请原谅我的笔记和代码中的废话。我总是把它清理干净再交给别人

在此处输入图片说明

jai*_*ish 8

因为文件名中可能包含更多非法字符。您的方法是正确的,但是在保存文件名之前,它不是从文件名中删除或替换的非法字符的完整列表。例如。您的代码->:&中的数组中缺少这些字符。但是,建议也将文件名除去其他允许的特殊字符。

下面,我提供了一个返回安全字符串的函数,该字符串可用于保存之前生成文件名。

Function ReplaceIllegalCharacters(strIn As String, strChar As String) As String
    Dim strSpecialChars As String
    Dim i As Long
    strSpecialChars = "~""#%&*:<>?{|}/\[]" & Chr(10) & Chr(13)

    For i = 1 To Len(strSpecialChars)
        strIn = Replace(strIn , Mid$(strSpecialChars, i, 1), strChar)
    Next

    ReplaceIllegalCharacters = strIn 
End Function
Run Code Online (Sandbox Code Playgroud)

具体来说,在您的代码中,用以下行替换ActiveWorkbook.SaveAs行:

ActiveWorkbook.SaveAs Filename:= _
   WBPath & "\BOM_" & Range("G2").Value2 & "_" & ReplaceIllegalCharacters(Range("H2").Value2, "_") & ".xlsx" _
    , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Run Code Online (Sandbox Code Playgroud)