Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the first word from a string in VBA (Excel)?

Tags:

excel

vba

For example, if I had:

Sub TestModule()
    Dim test As String
    test = "Machine Head"
End Sub

How would I extract the word Machine and assign it to a variable? I have tried using the Search and Left functions but have not had much success.

Cheers!

like image 771
Matt Hill Avatar asked Jul 18 '17 18:07

Matt Hill


People also ask

How do I extract first name in Excel VBA?

METHOD 1. Return First name from name. Output Range: Select the output range by changing the cell reference ("D5") in the VBA code. Name: Select the name from which you want to only extract the First name by changing the cell reference ("B5"), in the VBA code, or changing the name in cell ("B5").

How do I extract a substring in Excel VBA?

Step 1: In the same module declare a sub-function to start writing the code for sub-function. Step 2: Declare two Variables A as string and B as String array and take input string from the user and store it in Variable A. Step 3: Use the Split SubString function and store its value in Variable B.

How do I use InStr in Excel VBA?

The syntax of VBA InStr is “InStr([start],string1,string2,[compare]).” In comparison, the syntax of InStrRev is “InStrRev(string1,string2,[start,[compare]]).” If the “start” argument is omitted, the InStr begins to search from the starting (first position) of the string.


1 Answers

Use Split():

Sub TestModule()
    Dim test As String
    dim frstWrd as string
    test = "Machine Head"
    frstWrd = split(test," ")(0)
    Debug.Print frstWrd
End Sub
like image 134
Scott Craner Avatar answered Sep 23 '22 12:09

Scott Craner