Joining strings in VB6

Level:
Level1

Written By TheVBProgramer.

Prior to VB4, the plus sign (+) was used not only to add numbers, but also to concatenate strings together. The plus sign can still be used for concatenation in later versions of VB (4 thru 6) to maintain backward compatibility:

 

strName = "John"

strGreeting = "Hello, " + strName + ". How are you?"

'strGreeting now contains the string "Hello, John. How are you?"

 

In VB4, the ampersand (&) was introduced as the new concatenation operator, and it is the preferred operator to use for concatenation in the later versions of VB:

 

strGreeting = "Hello, " & strName & ". How are you?"

When you have many items to string together (such as when composing a long in-line SQL query), you'll find it useful to break up a logical line of code into several physical lines. To do so, each line to be continued must end with the line continuation character (an underscore preceded by a space):

 

strSQL = "SELECT Field1, Field2, " _

& "Field3, Field4, Fileld5 " _

& "FROM MyTable " _

& "WHERE Field1 = '" _

& strMyValue _

& "' AND Field4 <> '" _

& strSomeOtherValue _

& "' ORDER BY 1, 2, 3"

 

Although a line of code can be over 1,000 characters long, it is strongly recommended that you break up long lines of code with line continuation character. A good rule of thumb is to keep the length of a line of code no longer than what can be seen on the screen without scrolling (approximately 70 to 80 characters long). In VB6, up to 25 lines can be continued with the line continuation character (in versions 4 and 5, the limit was 10 lines; prior to version 4, line continuation was not available).

 

As an alternative to using a series of continued lines to concatenate the pieces of a long string together, you can have several individual lines of code that concatenate the target string variable to itself, as in the following example:

 

strSQL = "SELECT Field1, Field2, "

strSQL = strSQL & "Field3, Field4, Fileld5 "

strSQL = strSQL & "FROM MyTable "

strSQL = strSQL & "WHERE Field1 = '"

strSQL = strSQL & strMyValue

strSQL = strSQL & "' AND Field4 <> '"

strSQL = strSQL & strSomeOtherValue

strSQL = strSQL & "' ORDER BY 1, 2, 3"

 

 

More on the & and + Operators

 

("Everything you wanted to know about the '&' and '+' operators, but were afraid to ask", taken from the MSDN help.)

 

& Operator

 

Used to force string concatenation of two expressions.

Syntax:

result = expression1 & expression2

 

Part Description

result Required; any String or Variant variable.

expression1 Required; any expression.

expression2 Required; any expression.

 
Remarks

If an expression is not a string, it is converted to a String variant. The data type of result is String if both expressions are string expressions; otherwise, result is a String variant. If both expressions are Null, result is Null. However, if only one expression is Null, that expression is treated as a zero-length string ("") when concatenated with the other expression. Any expression that is Empty is also treated as a zero-length string.

 

 

+ Operator

 

Remarks

When you use the + operator, you may not be able to determine whether addition or string concatenation will occur. Use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.

 

If at least one expression is not a Variant, the following rules apply:

 

If

Then

Both expressions are numeric data types (Byte, Boolean, Integer, Long, Single,

Double, Date, Currency, or Decimal)

Add.

 

Both expressions are String

Concatenate.

One expression is a numeric data type and the other is any Variant except Null

Add.

One expression is a String and the other is any Variant except Null

Concatenate.

One expression is a numeric data type and the other is a String

A Type mismatch error occurs.

Either expression is Null

result is Null.

 

 

If both expressions are Variant expressions, the following rules apply:

If

Then

Both Variant expressions are numeric

Add.

Both Variant expressions are strings

Concatenate.

One Variant expression is numeric and the other is a string

Add.

 

For simple arithmetic addition involving only expressions of numeric data types, the data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Integer, Long, Single, Double, Currency, and Decimal. The following are exceptions to this order:

 

If

Then result is

A Single and a Long are added

a Double.

The data type of result is a Long, Single, or Date variant that overflows its legal range,

converted to a Double variant.

The data type of result is an Integer variant that overflows its legal range,

converted to a Long variant.

 

A Date is added to any data type,

a Date.

 

If one or both expressions are Null expressions, result is Null. If both expressions are Empty, result is an Integer. However, if only one expression is Empty, the other expression is returned unchanged as result.

 

Note The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication.

 

This example uses the + operator to sum numbers. The + operator can also be used to concatenate strings. However, to eliminate ambiguity, you should use the & operator instead. If the components of an expression created with the + operator include both strings and numerics, the arithmetic result is assigned. If the components are exclusively strings, the strings are concatenated.

 

Dim MyNumber, Var1, Var2

MyNumber = 2 + 2 ' Returns 4.

MyNumber = 4257.04 + 98112 ' Returns 102369.04.

 

Var1 = "34": Var2 = 6 ' Initialize mixed variables.

MyNumber = Var1 + Var2 ' Returns 40.

 

Var1 = "34": Var2 = "6" ' Initialize variables with strings.

MyNumber = Var1 + Var2 ' Returns "346" (string concatenation).

If you enjoyed this post, subscribe for updates (it's free)

Interesting

I never used the line continuation character(_) in my sql statements. This was helpful.

hjm

hjm

Interesting, thanks!

Interesting, thanks!

Great tutorial, Very helpful

Great tutorial, Very helpful helps me to do alot of things:)

Help with parsing project - vb.net

Hi there,
Hopefully, someone can steer me in the right direction with a project. I'm at a block with what to do. Here are the instructions I was given:

In this case, you will create a Visual Basic 2005 solution that manipulates strings. It will parse a string containing a list of items within a text box and put the individual items into the list box. It will build the textbox string by putting the list box items together into a single string. Parsing is based on the selected delimiter.

Step 1: Create the Project:
Create a Visual Basic Project using the project name “StringParser”.

Step 2 – Design the Form:
Design the form as shown in Figure 1. You will need three group boxes, three radio buttons, four button controls, one text box, one list box, and two label controls.

Step 3 – Add code in the Form’s Load event to select the first radio button:
In the Form’s Load event, write code to select the Comma choice in the radio buttons group box.

Step 4 – Add code in the Parse Text to List button’s Click event to parse and load the list box:
You will need the variables shown in Table 1:

Variable name Type Use
delimiter String Holds the String character representing the chosen delimiter
oldIndex Integer Holds the starting position in the string for the search
newIndex Integer Holds the position where the delimiter was found in the string
length Integer Holds the length of the input string
tempString String Holds the input string from the text box
tempWord String Holds the extracted word from the string
advanceSize Integer Holds the number of characters to advance the pointer, to skip over the delimiter
Table 1

Initialize:
First, clear the list box in case there are items from a previous use.

Validate and set the delimiter:
Use an If/ElseIf/Else statement to validate that a delimiter has been selected. CR-LF means “carriage return – line feed”, which causes a new line to be started. You will use a built-in constant to represent this, called vbCRLF. Note that vbCRLF is two characters long, while the other delimiters are only 1 character long.

For the selected delimiter radio button, set the delimiter variable to the actual character and set the advanceSize for that delimiter, using the values in Table 2:

Selected delimiter Delimiter character Advance size
Comma , 1
CR-FL vbCRLF 2
Space “ “ 1
Table 2
Use the Exit Sub statement to leave the Click event if no radio button was selected.

Parse the text box contents:
Parsing a string to break out the words involves a loop and two pointer variables (oldIndex and newIndex). Both start at the beginning position, which is 0. oldIndex will always point to the current starting position for the scan (and extraction). newIndex should be set to the position of the next delimiter. Inside the loop, do these steps:
1. Scan the string from the starting position (oldIndex) until you find a delimiter. Set newIndex to the position of the delimiter.
2. Extract the word from the starting position (oldIndex) up to but not including the delimiter position (newIndex). Use tempWord to hold the extracted word.
3. Trim off spaces, and load the extracted word into the list box.
4. Move the starting position (oldIndex) forward past the extracted word and past the delimiter.

Hints:
1. Use a While loop. The condition to use will be whether oldIndex has reached the end of the input string. You can determine this by getting the length of the input string.
2. Use the IndexOf method to scan for the selected delimiter, and assign the results of the IndexOf method to newIndex. newIndex therefore points to the location of the next delimiter.
3. Use the Mid function to extract the word.
4. Remember that the delimiter size has been assigned to advanceSize.
5. Remember that there probably is no delimiter at the very end. So when the scan no longer finds a delimiter, you must check to see if oldIndex is at the end of the string. If not, you should extract the remaining characters from oldIndex forward.

Step 5 – Add code in the Build Text From List button’s Click event to load the text box:

This part is simpler! You will take the items in the list box, combine them with the delimiter, and put the final string into the text box. You will need the variables shown in Table 3:

Variable name Type Use
delimiter String Holds the String character representing the chosen delimiter
i Integer Loop counter
length Integer Holds the length of the input string
tempString String Holds the input string from the text box
advanceSize Integer Holds the number of characters to advance the pointer, to skip over the delimiter
Table 3

Initialize:
First, clear the text box of items from a previous use.

Validate and set the delimiter:
This code will be identical to the code used in the Parse Text to List button’s click event to validate the delimiter choice.

Load the text box from the list box:
You will need a loop to iterate through all of the items in the list box. For each item in the list, concatenate its value with the tempString variable. If it is not the last item in the list, concatenate the sleeted delimiter also. After all items have been concatenated into tempString, assign it to the text box.

Hints:
1. You can use a For loop here, because you know the number of items in the list (the Items.Count property provides the count of items in the list box).
2. You can test to see if the loop counter has reached the last item by comparing it with the Items.Count property to determine if you need to add a delimiter for this item.

I am very new to vb.net and I am not ashamed to say I'm clueless. The below is my feeble effort so far.

'declare variables
Dim delimiter As String
Dim oldindex As Integer = 0
Dim newindex As Integer = 0
Dim length As Integer
Dim tempString As String
Dim tempWord As String
Dim advanceSize As Integer
delimiterTextBox.Text = contentsListBox.Text

'check to see what radio button is checked
If commaRadioButton.Checked Then
delimiter = ","
advanceSize = 1
ElseIf newlineRadioButton.Checked Then
delimiter = vbCrLf
advanceSize = 2
ElseIf spaceRadioButton.Checked Then
delimiter = " "
advanceSize = 1
End If

In another language....

This is a VB6 site and so you will get very little help with VB.net try looking around for a dedicated VB.net help site.

The tutorial does a great

The tutorial does a great job to explain everything except one thing. I want to make a textbox where the person enters their name and it says "How are you (yourname)".
I know it is not like:

strname = Val(yourname.Text)

Do you use something else like? I apologize it sounds easy but I just cannot figure out the command for it.

textbox

use this
Dim strname As String
Private Sub Command1_Click()
strname = Text1.Text
Text1.Text = ""
Text1.Text = "How are you " & strname & ""
End Sub

Private Sub text1_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
Command1_Click
End If
End Sub

Nevermind! I figured it

Nevermind! I figured it out. Thanks though.

thanks!

it is too simple to understand andimplement .