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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42546223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 12:13:16  来源:igfitidea点击:

How to replace first character in string

excelvba

提问by raju

I have a string in VBA - Hello how are you.

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

I want to replace -with something else. How can I do that? I am beginning in VBA. Need help.

我想-用别的东西代替。我怎样才能做到这一点?我从 VBA 开始。需要帮忙。

回答by Andrew L

The easiest way would be to use the replace function.

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

For example:

例如:

 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"

If it's always the first character and that character is different for each string you can do something like this:

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

 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"

回答by brettdj

If you are replacing with a single character than using Mid$on the LHS is much quicker than appending to a RIGHT$manipulation:

如果您使用单个字符替换而不是Mid$在 LHS 上使用比附加到RIGHT$操作要快得多:

(posting this as not enough detail evident in your question - may be useful for others)

将此发布为您的问题中不够明显的细节-可能对其他人有用

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