0

在从此处添加行之前,我正在更新问题以显示我已经拥有的内容...

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
4

4 回答 4

7

您可以使用正则表达式,而不是多个字符串替换

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
于 2012-09-25T00:25:38.987 回答
4

更新

马特,在您更新的帖子中,将代码更改为:

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

既然别人都在回答,那我就把评论改成回答入党了!

尝试

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

您需要将引号括在双引号中,以告诉 VBA 您要查找实际的实际引号,而不是它自动识别的特殊字符。 (丹尼尔库克下面的评论也涉及到它。)

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

于 2012-09-24T18:23:17.920 回答
3

将其粘贴到模块中

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
于 2012-09-24T18:18:05.800 回答
3

这是另一种选择:)

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

并测试

Sub Test()
Dim messyString As String

    messyString = "/*It Works!""."
    Debug.Print CleanName(messyString)

End Sub
于 2012-09-24T19:21:45.977 回答