保存工作簿 Excel VBA 时删除非法字符
Posted
技术标签:
【中文标题】保存工作簿 Excel VBA 时删除非法字符【英文标题】:Remove illegal characters while saving workbook Excel VBA 【发布时间】:2018-11-23 13:45:42 【问题描述】:此代码基本上重新格式化 xls 文件并将其保存为 xlsx。但是它使用G2
& H2
来获取新格式化文件的文件名。
这意味着某些字符不能出现在文件名中。我添加了一段代码来替换这些字符(
' 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
) activeworkbook.saves 是调试器总是带我去的地方
我收到一条错误消息,说即使 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
`
请原谅我的笔记和代码中的随机废话。我总是在把它给别人之前把它清理干净
【问题讨论】:
可能G2
中有非法字符?如果您发布实际错误消息和一些示例数据,那将是一个好主意
在保存行之前,做一个msgbox行,看看结果是否正确。msgbox WBPath & "\BOM_" & Range("G2") & "_" & WkbName & ".xlsx"
如果不正确,你会知道在哪里编辑你的字符串。
'WkbName = Application.WorksheetFunction.Clean(WkbName)'怎么样
【参考方案1】:
因为文件名中可能有更多非法字符。您的方法是正确的,但它不是在保存之前从文件名中删除或替换的非法字符的完整列表。例如。您的代码中的数组中缺少这些字符 -> : & 。但是,建议文件名也不要包含其他允许的特殊字符。
下面,我提供了一个函数,它返回一个安全的字符串,可用于在保存之前生成文件名。
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
具体来说,在您的代码中,将 ActiveWorkbook.SaveAs 行替换为以下行:
ActiveWorkbook.SaveAs Filename:= _
WBPath & "\BOM_" & Range("G2").Value2 & "_" & ReplaceIllegalCharacters(Range("H2").Value2, "_") & ".xlsx" _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
【讨论】:
strSpecialChars(i)
在 VBA 中不起作用。请改用Mid$(strSpecialChars, i, 1)
谢谢 Chris - 当您使用多种语言时就会发生这种情况。有时我也用 C# 编写代码。更正代码。非常感谢您指出。
已编辑帖子以包含原始错误消息以及使用您的函数和代码编辑@jainashish 之后的错误消息
再次编辑了我的帖子 - 需要添加条款以包括方括号!
访问此链接:***.com/questions/18594223/…以上是关于保存工作簿 Excel VBA 时删除非法字符的主要内容,如果未能解决你的问题,请参考以下文章
每次创建新数据透视表并保存文件时,Excel工作簿的文件大小都会增加