Hakon
Hakon

Reputation: 99

Replace all characters in a string after/including a space

I want to replace all of the characters in a string that come after a space, and then I would like to get rid of the space as well. Lets say the word was "Throw Baseball", I want my program to return me "Throw" and that's it. I'm using some code that I found online but It does not seem to work and keeps calling Example String an invalid Variable. ANy help would be greatly appreciated

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

It should give me Throw for the StringReplace string, however it does not.

Upvotes: 0

Views: 354

Answers (2)

Cyril
Cyril

Reputation: 6829

Try using InStr() to determine the position of the first space, then just keep Left() to one position short of the space, such that:

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

Thanks @CLR for the correction. Typed it up off head and started my InStr number of arguements in the Left

Upvotes: 1

user11509084
user11509084

Reputation:

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

or

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

Upvotes: 0

Related Questions