Splitting the value of a textbox into 2

R

red6000

Hi,

I have a VBA macro in Word XP that has 3 textboxs

TextBox1 will contain a name, both first and last name

What I want to do is be able to split the value in TextBox1 into 2 so that
TextBox2 contains the first name (ie the text up to the space in TextBox1)
and TextBox3 contains the lastname (ie the text in TextBox1 after the
space).

Any clues on how to achieve this? I assume I will need to use some form of
length function and a function to find the space?

Thanks
 
D

Dave Lett

You can do that any number of ways:

ONE:
Dim sName As String
Dim sFirst As String
Dim sLast As String
Dim iPos As Integer
sName = "Your Name"

iPos = InStr(1, sName, " ") - 1
sFirst = Left(sName, iPos)
sLast = Right(sName, iPos)
MsgBox "First: " & sFirst & vbCrLf & _
"Last: " & sLast

TWO:
Dim sName As String
Dim aName As Variant
sName = "Your Name"
aName = Split(sName, " ")
MsgBox "First: " & aName(0) & vbCrLf & _
"Last: " & aName(1)

HTH,
Dave
 
R

red6000

Thanks, sorted it with:

Dim SearchString, SearchChar, MyPos, First, Last

SearchString = TextBox1.Value
SearchChar = " "

MyPos = InStr(1, SearchString, SearchChar, 1)
MyPos = MyPos - 1

First = Mid(SearchString, 1, MyPos)

MyPos = MyPos + 2

Last = Mid(SearchString, MyPos)

TextBox2.Value = First
TextBox3.Value = Last
 
J

Jezebel

Split() is another possibility that might be better in this case.


1. Add some error-handling in case there is no space at all.

2. Use Trim$() so you don't need to guess how many spaces there are

3. Use the string versions of the sub-string functions (Mid$() rather than
Mid()) -- they are about 1000 times faster.

4. Declare your variables by type. Variants are slow and lead to bugs.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top