String 字符串编辑功能

String 字符串编辑功能,string,replace,vbscript,String,Replace,Vbscript,我有一种情况,在这种情况下,我调用了一个带有一个参数(字符串)的函数。由于某种原因,我的代码不会接受我给它的字符串变量,并给我一个错误。我是不是犯了一些愚蠢的语法错误?以下是简化得多的代码框架: Dim input, message, done, testFormatMessage Do good = 0 input = InputBox("Type the name:", "Name prompt-- By JM", "Type name/command here...")

我有一种情况,在这种情况下,我调用了一个带有一个参数(字符串)的函数。由于某种原因,我的代码不会接受我给它的字符串变量,并给我一个错误。我是不是犯了一些愚蠢的语法错误?以下是简化得多的代码框架:

Dim input, message, done, testFormatMessage
Do
    good = 0
    input = InputBox("Type the name:", "Name prompt-- By JM", "Type name/command here...")
    message = UCase(input)
    'if you hit cancel or close the window:
    If message = "" Then
        Exit Do
    End If
    'if the input contains a '%' then format the input to delete that symbol
    If InStr(message, "%") > 0 Then
        testFormatMessage = Format(message)
        MsgBox(testFormatMessage)
    End If
    If input = "Type name/command here..." Then
        MsgBox("You didn't type a name/command")
        done - 1
    End If
    If done = 0 Then
        MsgBox("'" & input & "' is not a recognized name/command.")
    End If
Loop

Function Format(m)
    m = m.Replace("%", "")
    Format = m
End Function
在您的输入包含“%”之前,这将正常工作。如果是这样,程序就会崩溃,导致一个错误

行:构成脚本的函数名的第一行

错误:需要对象“m”

为什么我的函数在运行时不能接受字符串“message”作为参数来替换对象“m”?我承认我在VBScript编程方面处于中级水平,所以如果我犯了愚蠢的语法错误,请不要太苛刻


提前谢谢

没关系,多亏了@KenWhite,我才找到了答案。正如Ken所说,字符串不是VBScript中的对象,因此它没有.Replace方法。下面是一个实际可行的示例替换方法

Function Replace(case, replaceCaseWithThis, str)
    Dim obj

    Set obj = new RegExp
    obj.Pattern = pattern
    obj.IgnoreCase = True

    Replace = obj.Replace(str, replaceCaseWithThis)
End Function
现在,我们来看一个使用示例输出调用方法的示例

Dim startingString, resultingString
startingString = "I am a string for testing purposes"
resultingString = Replace("string", "series of characters", startingString)
MsgBox(resultingString)
这将显示一个包含以下内容的消息框:

我是一系列用于测试的字符

再次感谢@KenWhite看到了我愚蠢的错误,这个答案正在发布,以便作为参考来源

编辑/更新:

多亏了@Tomalak,我还看到我在遵循VBScript方法进行替换,而不是函数。使用该函数,代码简化为:

Replace(m, "%", "")

再次感谢@Tomalak

,因为字符串不是VBScript中的对象,所以它没有
。请替换
方法。改为使用VBScript函数进行字符串操作(就像使用
InStr
UCase
一样)。VBScript有一个内置的
Replace()
函数。为什么不使用它?@Tomalak,这是我最初的困境。我尝试使用内置的Replace()函数来更改字符串,但是在更改字符串时它将不起作用。相反,你必须改变对象。因此,在我作为参考提供的答案中,我创建了对象“obj”,并使用它成功地更改了字符串。您最初的尝试
m.Replace(“%”,“”)
应为
Replace(m,“%”,“”)
。我不明白为什么那样不行。我明白你的意思了。这是我的错,我遵循的是Replace()方法的规则,而你遵循的是Replace()函数。事实证明,它们在VBScript中完全不同。不幸的是,我来自Java(有多年的经验),因此看到“method”这个词以及“object.Replace()”的含义似乎完全正确。所以基本上,你是对的,我可以写一行说明
Replace(m,“%”,“)
。这只是一种我不习惯的命令形式(尽管我应该这么做)。感谢您的帮助,我希望您会注意到,我已经更新了提供的答案,以适应您的输入,以及对您的直接引用。