Generic VBA

VBA Object Models

Comments

A comment in VBA begins with a single quote '. You may also use the word "Rem" (short for remark) to signify a comment, but if used on the same line as a statement, it will often need to be preceded by a ":", whereas the ' does not need to be preceeded by a ":". In addition, the comment can start immediately after the ' character. So it is recommended you avoid using Rem and just use the ' character to signify comments:

' This routine will extract first and last names from the full name
Rem This is the older style of signifying a comment - not recommended.


Sub ParseData()
	Dim r As Integer ' index for rows
	MsgBox "Hello World": Rem Say Hi (note the colon required for this style comment)
	MsgBox "Hello World" 'Say Hi (no colon necessary) 

String Concatenation

The ampersand (&) is used for string concatenation:

Dim myString,myOtherString As String
myString = "Hello "
myOtherString = myString & "World"

Line Continuation

The line continuation character is an underscore (_):

If a = 2 Or _  
   a = 3 Or _  
   a = 4 Then  
   MsgBox("a in range") 
End If

Writing statements to a terminal window - Debug.Print

Premature Loop Continuation

Premature For loop exit - Exit For

Premature Do While loop exit

The "first useful code" below is somewhat in error. The Dim statement does not work as expected. Dim r, position As Integer creates an Integer variable position and a Variant variable r. Similarly, only one String variable was created.

' first useful VBA code ever written:
Sub ParseData()
  Dim r, position As Integer
  Dim userID, lastName, firstName As String
  For r = 2 To 54
    userID = Cells(r, 1).Value
    position = InStr(userID, ",")
    If position = 0 Then
       'MsgBox (userID & " has no comma")
       lastName = userID
    Else
       lastName = Mid(userID, 1, position - 1)
       firstName = Mid(userID, position + 1)
       'MsgBox ("First name is " & firstName)
       Cells(r, 2) = firstName
       Cells(r, 3) = lastName
    End If
  Next r
  
End Sub