CleanName不清洗“在Excel VBA中?

我正在更新的问题,以显示我已经,在从这里添加行之前…

Function CleanName(strName As String) As String 'will clean part # name so it can be made into valid folder name 'may need to add more lines to get rid of other characters CleanName = Replace(strName, "/", "") CleanName = Replace(CleanName, "*", "") CleanName = Replace(CleanName, ".", "") CleanName = Replace(strName, "\", "") End Function 

而不是多个stringreplace,你可以使用正则expression式

 Function KillChars(strIn As String) As String Dim objRegex As Object Set objRegex = CreateObject("vbscript.regexp") With objRegex .Global = True .Pattern = "[\/\*\.\\""""]+" KillChars = .Replace(strIn, vbNullString) End With End Function 

更新

马特,你的更新后,更改代码为:

 Function CleanName(strName As String) As String 'will clean part # name so it can be made into valid folder name 'may need to add more lines to get rid of other characters CleanName = Replace(strName, "/", "") '-> only use strName the first time, since you are passing that string to the Function CleanName = Replace(CleanName, "*", "") CleanName = Replace(CleanName, ".", "") CleanName = Replace(CleanName, "\", "") '-> if you use strName here, you lose your first 3 replacments CleanName = Replace(CleanName, """", "") '-> this is the correct syntax to remove the " '-> to Sid's point, this should work too 'CleanName = Replace(CleanName, Chr(34), "") End Function 

由于其他人正在回答,我会改变我的意见,以join党的答案!

尝试

CleanName = Replace(CleanName, """", "")

您需要用双引号括住引号,以告诉VBA您想要查找实际的实际报价,而不是自动识别的特殊字符。 (丹尼尔·库克的下面的评论也涉及到这一点。)

为了他人的利益,CleanName是一个自定义函数,用于清除不需要的string。 请参阅此链接了解更多信息: CleanName

将其粘贴到模块中

 Public Function CleanName(rng As Range) As Variant CleanName = Replace(rng.Value, Chr(34), "") End Function 

跟进

 Option Explicit Public Function CleanName(rng As Range) As Variant On Error GoTo Whoa Dim vVal As Variant vVal = rng.Value vVal = Replace(vVal, Chr(34), "") ' " vVal = Replace(vVal, Chr(42), "") ' * vVal = Replace(vVal, Chr(46), "") ' . vVal = Replace(vVal, Chr(47), "") ' / vVal = Replace(vVal, Chr(92), "") ' \ CleanName = vVal Whoa: End Function 

这是一个替代:)

 Option Explicit Function CleanName(ByRef str As String) As String Dim removeChars As String Dim i As Long removeChars = "/*.""" For i = 1 To Len(removeChars) str = Replace(str, Mid(removeChars, i, 1), vbNullString) Next i CleanName = str End Function 

并进行testing

 Sub Test() Dim messyString As String messyString = "/*It Works!""." Debug.Print CleanName(messyString) End Sub