如何替换字符串中的第一个字符

时间:2017-03-02 03:20:56

标签: excel excel-vba vba

我在VBA中有一个字符串- Hello how are you

我想替换' - '用别的东西。我怎样才能做到这一点。我开始在VBA。需要帮助

2 个答案:

答案 0 :(得分:3)

最简单的方法是使用替换功能。

例如:

 Dim yourString As String
 Dim newString As String
 yourString = "- Hello how are you"
 newString = Replace(yourString, "-", "something else")
 MsgBox newString 'returns "something else Hello how are you"

如果它始终是第一个字符,并且每个字符串的字符不同,您可以执行以下操作:

 Dim yourString, subString, replacementString, newString As String
 yourString = "- Hello how are you"
 subString = Right(yourString, Len(yourString) - 1)
 replacementString = "something else"
 newString = replacementString + subString
 MsgBox newString 'returns "something else Hello how are you"

答案 1 :(得分:2)

如果要替换单个字符而不是使用Mid$,那么LHS要比附加RIGHT$操作快得多:

发布此信息,因为您的问题中没有明显的详细信息 - 可能对其他人有用

Dim strNew As String
strNew = "- Hello how are you"
Mid$(strNew, 1, 1) = "x"
Debug.Print strNew