替换字符串中所有字符(在空格之后/包括空格)

时间:2019-06-06 13:42:54

标签: excel vba

我想替换一个空格后的字符串中的所有字符,然后我也希望摆脱该空格。可以说这个词是“ Throw Baseball”,我希望程序返回“ Throw”,仅此而已。我正在使用一些在网上找到的代码,但似乎无法正常工作,并一直将Example String称为无效变量。任何帮助将不胜感激

Dim ExampleString As String
ExampleString = "Throw Baseball"
Dim StringReplace As String
Dim CharReplaceCounter As String
CharReplaceCounter = 0
Dim I AS Integer
I=0
While (ExampleString.Characters(CharReplaceCounter).Text <> " ")
CharReplaceCounter = CharReplaceCounter + 1
Wend

While(I<CharReplaceCounter)
StringReplace.Characters(CharReplaceCounter).Text = ExampleString.Characters(CharReplaceCounter).Text
I=I+1
Wend

它应该让我抛出StringReplace字符串,但事实并非如此。

2 个答案:

答案 0 :(得分:1)

尝试使用InStr()确定第一个空格的位置,然后将Left()保持在空格的一个位置,例如:

Left(FullString,InStr(FullString," ")-1)

感谢@CLR进行更正。从头开始输入,并在InStr

中开始我的Left争论

答案 1 :(得分:0)

Dim ExampleString As String
ExampleString = "Throw Baseball"
If InStr(ExampleString, " ") Then Debug.Print Left(ExampleString, InStr(ExampleString, " ") - 1)

Dim ExampleString As String
ExampleString = "Throw Baseball"
Debug.Print Split(ExampleString, " ")(0)