Excel vba is keyword

Keywords we use in MS Office Excel VBA (Visual Basic for Applications) programming language. These keywords are high light in blue color in visual basic editor window. We can’t use these keywords as function name or procedure name or variable name. Keywords in VBA plays an important role in VBA Programming language. Keywords are always starts with capital letter and followed by small letters. Always start writing in small letters, automatically the first letter converts to capital letter.

Table of Contents:

  • Overview
  • List of Keywords in VBA
  • Usage & Examples on VBA Keywords
    • Use of As VBA Keyword
    • Use of an Option VBA Keyword
    • Use of Nothing VBA Keyword
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Here are the following list of keywords in VBA.

Keyword Description
As As keyword is used with Dim to specify the data type of a variable or argument.
ByRef ByRef keyword is used to pass variables or arguments into procedures and functions.
ByVal ByVal keyword is used to pass variables or arguments into procedures and functions.
Case Case keyword is used with Select when we check conditions.
Date Date keyword is used to define the current date.
Else Else keyword is used in conditional statements.It is an optional part of it.
Empty Empty keyword is used to explicitly set a variant data type variable to Empty.
Error Error keyword is used to generate an error message.
FALSE FALSE keyword is used to represent the value zero(0) to Boolean variable.
For For keyword is used with the Next keyword to repeating statements.
Friend Friend keyword is used to in class modules.
Get Get keyword is used with the Property keyword while creating objects.
Is Is keyword is used to compare two object variables which we used as reference.
Let Let keyword is used with the Property keyword while creating objects.
Me Me keyword is used in class module or userform.
New New keyword is used while creating new instance of an object.
Next Next keyword is used in for …Next loop
Nothing Nothing keyword is used to an object variable to disassociate the variable from an object.
Null Null keyword is used to represent that a variable contains no valid data.
On On keyword is used with the Error keyword for error handling.
Option Option keyword is used for module level settings.
Optional Optional keyword indicates that an argument in a function is not required.
ParamArray ParamArray keyword is used to allow a dynamic number of arguments for a function.
Private Private keyword is used to declare a procedure which is visible in that code module.
Property Property keyword is used with the Class keyword while creating objects.
Public Public keyword is used to declare a procedure which is visible to entire modules.
Resume Resume keyword is used with the On Error keyword for error handling.
Set Set keyword is used with the Property keyword while creating objects.
Static Static keyword is used to represent a static variable or argument
Step Step keyword is used with the For keyword for additional increments and decrements.
String String keyword is used to consist string variables.
Then Then keyword is used with the If keyword in conditional statements.
To To keyword is used with the For keyword while repeating statements.
TRUE TRUE keyword is used to represent the value one(1) to Boolean variable.
WithEvents WithEvents keyword is used in class modules.

Usage & Example on VBA Keywords

Let us see few sample examples and usage on VBA keywords.

Usage and Example on As VBA Keyword:

Here is usage and example on ‘As’ VBA Keyword.

Usage: The As keyword is used in the following statements.

  • Dim Statement
  • Function Statement
  • ReDim Statement
  • Sub Statement and many more statements

Example: Here is simple example on As keyword. You can notice As keyword is high lighted in blue color.
VBA As Keyword

Sub As_Keyword_Example()

    'Variable Declaration
    Dim iCnt As Integer
    Dim sName As String
    Dim dDate As Date

End Sub

Use of Option VBA Keyword

Here is usage and example on ‘Option’ VBA Keyword.

Usage: The Option keyword is used in the following statements.

  • Option Base Statement
  • Option Explicit Statement
  • Option Compare Statement and many more statements

Example: Here is simple example on Option keyword. You can notice Option keyword is high lighted in blue color.
VBA Option Keyword

'Set default array index to 1
Option Base 1

Note: The specified above code added at module level.

Use of Nothing VBA Keyword

Here is usage and example on ‘Nothing’ VBA Keyword.

Usage: The Nothing keyword is used in the following scenarios.

  • To initialize an object variable
  • To release an object variable
  • Used with Set statement

Example: Here is simple example on Nothing keyword. You can notice Nothing keyword is high lighted in blue color.
VBA Nothing Keyword

Sub Nothing_Keyword_Example()

    'Variable Declaration
    Dim oWb As Object
    'Returns TRUE, because oWb varaibale not assigned to an object variable
    MsgBox oWb Is Nothing
    
    'Returns FALSE, because oWb varaibale assigned to an object variable
    Set oWb = Workbooks.Add
    MsgBox oWb Is Nothing
    
    'Returns TRUE, because oWb varaibale released from an object variable
    Set oWb = Nothing
    MsgBox oWb Is Nothing
    
End Sub

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

Select Case Statement of Excel VBA

The Select Case VBA statement compares an expression with multiple Case statements containing conditions. If a match is found in any of the Case statements, the condition is said to be true. Further, if a condition is true, its corresponding code is executed and no more Case statements are tested. However, if a match is not found in any of the Case statements, the conditions are said to be false. In this case, the code of the Case Else statement is executed.

For example, an employee is asked to rate the work-life balance of his organization on a scale of 10. Further, his input will be compared with the following three conditions (or possible outcomes):

  • If the input is between 1 and 3 (both inclusive), display the message “the work-life balance is poor.”
  • If the input is between 4 and 6 (both inclusive), display the message “the work-life balance is reasonable.”
  • If the input is between 7 and 10 (both inclusive), display the message “the work-life balance is healthy.”

The message of only that condition will display, which matches the input entered by the employee. Note that the expression can either be entered directly in a Select Case structure or collected from the user as an input.

The purpose of using the Select Case statement in VBA is to execute different codes based on the fulfillment or non-fulfillment of different conditions. The Select Case statement is used to evaluate (or test) three or more conditions. It is a substitute for the If Then Else statement of VBA and the nested IF statement of Excel.

Table of contents
  • Select Case Statement of Excel VBA
    • Syntax of the Select Case Statement of Excel VBA
    • How to use the Select Case Statement of Excel VBA?
    • VBA Select Case Examples
      • Example #1–“Expression for Testing” is Entered Directly
      • Example #2–“Expression for Testing” is Compared with a Range of Values Using the “To” Keyword
      • Example #3–“Expression for Testing” is Compared with Numbers Using the “Is” Keyword
      • Example #4–“Expression for Testing” is Entered in a Cell and Evaluated by the Command Button
      • Example #5–“Expression for Testing” is Divided by 2 with the MOD Operator of VBA
      • Example #6–Nested Select Case Statements Where “Expression for Testing” is the Current Date
    • The Key Points Related to the Select Case Statement of Excel VBA
    • Frequently Asked Questions
    • Recommended Articles

Syntax of the Select Case Statement of Excel VBA

The Select Case statement in VBA is similar to the Switch Case statement used in programming languages like Java, C#, PHP, etc. The syntax of the Select Case statement of Excel VBA is given as follows:

Select [Case]  Expression for testing
  
[Case] List of Expression Statements (Case 1, Case 2, Case 3 and so on...)

Case Else (Else Statements)

End Select
End Sub

The Select Case statement of Excel VBA accepts the following arguments:

  • Expression for testing: This is a single expression that is to be compared with the different Cases. It can either be a numeric or textual expression. So, it can evaluate to a character, integer, Boolean, object, string, etc.
  • List of expressions: This is the list of expressions (called Case statements) against which the “expression for testing” is compared. Excel VBA looks for an exact match within these Case statements. These Case statements consist of one or more possible outcomes (values or conditions) that may or may not match the “expression for testing.” If there are multiple expressions (or values) within a single Case, they must be separated by commas. The following keywords can be used in Case statements:
    • The To keyword should be used when a range of values needs to be specified in a Case statement. The value preceding the To keyword should be less than or equal to the value succeeding this keyword.
    • The Is keyword should be used when a logical operatorLogical operators in excel are also known as the comparison operators and they are used to compare two or more values, the return output given by these operators are either true or false, we get true value when the conditions match the criteria and false as a result when the conditions do not match the criteria.read more (=, <>, <, >, <= or >=) needs to be entered in a Case statement. This keyword should be inserted before the logical operator.
  • Statements: This is one or more codes succeeding the “list of expressions.” Only that code is executed for which the “expression for testing” matches the “list of expressions.”
  • Case Else statement: This consists of one or more codes (or statements), which are executed when all the Case statements (or list of expressions) are false.
  • End Select: It closes the Select Case structure. Every Select Case statement must necessarily have an End Select statement.

The “expression for testing,” “list of expressions,” and End Select clauses are required in a Select Case construction. However, the “statements” and Case Else statements are optional in the given syntax.

Note 1: In a Select Case statement in VBA, each Case statement is compared with the “expression for testing.” Once a condition is met (or the Case statement is matched), no further Case statements are tested. However, if a condition is false (or the Case statement does not match), the next Case statement is tested.

The testing of Case statements (or conditions) continues till one of the specified conditions is met or till the Case Else or the End Select statement. If none of the tested conditions is true and there is no Case Else statement, control passes to the End Select statement.

Note 2: If the “expression for testing” matches more than one Case statement, only the code of the first such match is executed.

How to use the Select Case Statement of Excel VBA?

The Select Case statement is a feature of Excel VBA. One can access VBA from the “visual basic” option of the Developer tab of ExcelEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more. In this tab, the user-defined functions (UDF) and their codes can be created.

The Select Case statement of VBA should be used in place of the nested IF statementIn Excel, multiple IF conditions are IF statements that are contained within another IF statement. They are used to test multiple conditions at the same time and return distinct values. Additional IF statements can be included in the ‘value if true’ and ‘value if false’ arguments of a standard IF formula.read more of Excel. This is because the former is easier to understand and execute than the latter.

The steps to use the Select Case statement of VBA are listed as follows:

  1. Create a command button and place it in the Excel worksheet. When the command button is clicked, a macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
    read more
    runs. The running of the macro performs an action.
  2. Right-click the command button and choose the option “view code.” The Visual Basic Editor opens.
  3. Enter the code between the CommandButton function and End Sub.
  4. Debug and compile the code to identify the syntax errors.
  5. Change the input values to observe the different outputs.

Note 1: The user-defined functions (UDF) are customized functions that cater to the specific needs of the user.

Note 2: Every time the input is changed (in point e), the “expression for testing” changes. As a result, the conditions that match this expression change. Hence, different codes are executed each time the input values change.

VBA Select Case Examples

You can download this VBA Select Case Excel Template here – VBA Select Case Excel Template

Example #1–“Expression for Testing” is Entered Directly

In the following code, the “expression for testing” is A=20 and the Case statements are 10, 20, 30, and 40. There is also a Case Else statement in this code.

Private Sub Selcaseexmample ()
Dim A As Integer
A = 20
 
Select Case A
  
Case 10
 MsgBox "First Case is matched!"

Case 20
 MsgBox "The Second Case is matched!"

Case 30
 MsgBox "Third Case is matched in Select Case!"

Case 40
 MsgBox "Fourth Case is matched in Select Case!"

Case Else
 MsgBox "None of the Cases match!"

End Select
End Sub

On running the preceding code, the following output is obtained.

VBA Select Case

Explanation: The expression A=20 is compared with the four Case statements 10, 20, 30, and 40. A match is found in the second Case statement (Case 20). Consequently, the message of the second Case statement is displayed, which is “the second Case is matched.”

Had the expression not matched with any of the Case statements, the message of the Case Else statement would have been displayed.

Note: The MsgBox function of VBA displays a dialog box containing a customized message.

Example #2–“Expression for Testing” is Compared with a Range of Values Using the “To” Keyword

In the following code, the “expression for testing” is collected from the user with the help of the InputBox function of VBA. There are four Case statements, namely Case 1 To 36, Case 37 To 55, Case 56 To 80, and Case 81 To 100. There is also a Case Else statement in the code.

Private Sub Selcasetoexample ()
Dim studentmarks As Integer
studentmarks = InputBox("Enter marks between 1 to 100.")
  
Select Case studentmarks
    
  Case 1 To 36
   MsgBox "Fail!"
   
  Case 37 To 55
   MsgBox "C Grade"
 
  Case 56 To 80
   MsgBox "B Grade"
  
  Case 81 To 100
   MsgBox "A Grade"
  
  Case Else
   MsgBox "Out of range"

End Select
End Sub

On running the preceding code, the user is asked for input. Assume that the user enters 90. So, the following output is obtained.

VBA Select Case 1

Explanation: The Case statements of the preceding code contain a range of values. Notice that in the code, each number preceding the To keyword is smaller than the number succeeding this keyword.

The “expression for testing” is entered as 90 by the user. This expression matches the fourth Case statement (Case 81 to 100). So, the code in this Case statement is executed. Hence, the message “A grade” is returned by VBA. This output is displayed in a dialog box due to the usage of the MsgBox function in the code.

Both numbers (preceding and succeeding the To keyword) of the range are inclusive. So, had the user entered 81, it would have again matched with the fourth Case statement. However, had a number greater than 100 been entered, the output would have been “out of range.” This message is defined in the Case Else statement of the code.

Note: The InputBox function collects the input from the user through a dialog box. The message shown in this dialog box is the same as that entered in the InputBox function of the code.

Example #3–“Expression for Testing” is Compared with Numbers Using the “Is” Keyword

In the following code, the “expression for testing” is collected from the user. There are two Case statements, namely Case Is < 200 and Case Is >= 200. There is no Case Else statement in the code.

Sub CheckNumber()
  Dim NumInput As Integer
  NumInput = InputBox("Please enter a number.")
  
Select Case NumInput
  
Case Is < 200
 MsgBox "You entered a number less than 200"
    
Case Is >= 200
 MsgBox "You entered a number greater than or equal to 200"

End Select
End Sub

On running the preceding code, a dialog box containing the message “please enter a number” is displayed. Assume that the user enters 200. So, the following output is displayed.

vba select case example 3

Explanation: Observe that the two logical operators (< and >=) in the code are preceded by the “Is” keyword. Had this keyword not been supplied, VBA would have automatically inserted it before the logical operators.

The “expression for testing” is entered by the user as 200. This expression is compared with the two Case statements of the preceding code. A match is found in the second Case statement. This is because 200 is not greater than but is equal to 200.

Notice that there is no Case Else statement in the preceding code. This is because whatever number the user enters, it falls within either of the two Case statements. So, one of the two Case statements will always be true. Hence, the Case Else statement is not required as it runs only when all Case statements evaluate to false.

Example #4–“Expression for Testing” is Entered in a Cell and Evaluated by the Command Button

In the following code, the “expression for testing” is taken from cell A1 of the Excel worksheet. There are three Case statements and one Case Else statement.

Sub color()
Dim color As String
color = Range("A1").Value
  
Select Case color

Case "Red", "Green", "Yellow"
 Range("B1").Value = 1
    
Case "White", "Black", "Brown"
 Range("B1").Value = 2
    
Case "Blue", "Sky Blue"
 Range("B1").Value = 3
    
Case Else
 Range("B1").Value = 4

End Select
End Sub

Further, a command button has been created in the worksheet with the help of ActiveX controls. The input entered in cell A1, the command button, and the output obtained in cell B1 are shown in the following image.

vba select case example 4

Explanation: The preceding code is executed by clicking the command button of the Excel worksheet. Notice that multiple expressions of each Case statement are separated by commas (like “Red”, “Green”, “Yellow”).

The “expression for testing” is entered as “pink” in cell A1. This expression matches none of the three Case statements specified in the code. Consequently, the code of the Case Else statement is executed. So, the output in cell B1 is 4.

Had the user entered a color (in cell A1) specified in any of the three Case statements, the corresponding code would have run. For instance, had the user entered “White” in cell A1 (without the double quotes and with “W” capital), the output in cell B1 would have been 2.

Hence, a change in the input of cell A1 causes the output of cell B1 to change.

Example #5–“Expression for Testing” is Divided by 2 with the MOD Operator of VBA

In the following code, the “expression for testing” is collected from the user. There are two Case statements, namely Case True and Case False. The Case Else statement is not there in the code.

Sub CheckOddEven()
CheckValue = InputBox("Enter a number.")

Select Case (CheckValue Mod 2) = 0
 
Case True
 MsgBox "The number is even"
  
Case False
 MsgBox "The number is odd"

End Select
End Sub

On running the preceding code, a dialog box with the message “enter the number” is displayed. Assume that the user enters 10. The output obtained is shown in the following image.

example 5

Explanation: The “expression for testing” entered by the user is 10. This expression is divided by 2 with the help of the MOD operatorVBA MOD is the same as the application in mathematics. When a number is divided by its divisor, this function gives us the remainder from the division. However, it is not a function in VBA; rather it is an operator.read more. If the remainder is equal to zero, the number is divisible by 2. Such a number is even. If the remainder is not equal to zero, the number is not divisible by 2 and is odd.

Since 10 is divisible by 2, the code of the Case True statement is executed. Hence, the output is the message “the number is even.” Notice that a Case Else statement is not required in the preceding code. This is because either of the two Case statements will be true at all times.

Note: The MOD operator of VBA divides one number by the other and returns the remainder as the output.

Example #6–Nested Select Case Statements Where “Expression for Testing” is the Current Date

In the following code, the “expression for testing” is the current date. There are two Select Case statements [Select Case Weekday (Now) and Case 1,7], one Case Statement (Case 1), and two Case Else statements.

Sub TestWeekday()

Select Case Weekday(Now)

Case 1, 7
 Select Case Weekday(Now)
  
Case 1
 MsgBox "Today is Sunday"
  
Case Else
 MsgBox "Today is Saturday"
  
End Select

Case Else
  MsgBox "Today is a Weekday"

End Select
End Sub

On running the preceding code, the output obtained is shown in the following image.

example 6

Explanation: The inner Select Case statement (Case 1, 7) is the Case statement of the outer Select Case statement [Select Case Weekday (Now)]. The outer Select Case statement checks whether the current date is a weekday, Saturday or Sunday.

When the NOW VBA functionNOW is a date and time function in VBA which is used to get the current system date and time. VBA Now function does not takes any arguments and the return output for this function is date.read more is enclosed within the VBA WEEKDAY functionWeekday in VBA is a date and time function to identify the weekday of a given date provided as an input. This function returns an integer value from 1 to 7 range. There is an optional argument provided to this function which is the first day of the week.read more, the latter returns a day of the week that corresponds with the current date. If the output of the WEEKDAY function is 1, the message to be displayed is “today is Sunday.” If the output of the WEEKDAY function is 7, the message to be displayed is “today is Saturday.” This is because, in the preceding code, VBA considers 1 and 7 as Sunday and Saturday respectively.

The message “today is a weekday” will be returned when the output of the WEEKDAY function is other than 1 and 7. So, the second Case Else statement is executed when Case 1 (today is Sunday) and the first Case Else statements (today is Saturday) are false.

Since this article has been created on a weekday, the output of the Select Case statement is “today is a weekday.”

Note 1: The NOW function of VBA returns the current date and time. This function does not take any arguments. The WEEKDAY function of VBA returns the day of the week corresponding to the specified date.

Note 2: Every nested Select Case statement should necessarily contain a matching End Select statement.

The important points related to the Select Case statement of VBA are listed as follows:

  • The Is keyword used in the Case statement and Case Else statement is different from the Is operator of VBA.
  • The codes of the Select Case statement of VBA can run successfully if macros have been enabled.
  • The “expression for testing” entered in the dialog box should be in accordance with the message of the InputBox function of VBA.

Note: To know more about enabling macrosTo enable macros simply means to run or execute a macro in a particular file in order to save the time spent on repetitive actions. To enable macros, select “enable all macros” from the “trust center” of the File tab (in the “options” button).
read more
, click the given hyperlink.

Frequently Asked Questions

1. Define the Select Case statement of Excel VBA.

The Select Case statement is used to compare an expression with multiple Case statements. If a Case statement matches the expression, the corresponding code is executed. However, if a Case statement does not match the expression, the next Case statement is evaluated.

The evaluation of Case statements continues till a match is found or till the Case Else or End Select statement. Once a match is found in any of the Case statements, no further Case statements are tested. The Case Else statement is optional and its code is executed when none of the Case statements is true.

Note: For details related to the working of the VBA Select Case statement, refer to the examples of this article.

2. How is the Select Case statement of Excel VBA written?

The steps to write the Select Case statement of Excel VBA are listed as follows:

a. Specify a single expression that needs to be compared with multiple Case statements. This expression can be numeric or textual. Note that the expression is evaluated only once and is stated at the beginning of the Select Case structure.
b. Specify the Case statements. Each Case statement should consist of one or more conditions (or possible outcomes) followed by a code. For stating multiple conditions within the same Case statements, use the comma as the separator.
c. Specify the Case Else statement. The code of this statement will be executed if none of the Case statements match the expression. Though it is optional to specify the Case Else statement, it is recommended to be included in the Select Case structure.
d. State the End Select statement. This statement is necessarily required as it terminates the Select Case structure. If no Case statement matches the expression and there is no Case Else statement, control passes to the End Select statement.

Note 1: If the expression (in point a) is to be collected as an input from the user, a customized message must be stated within the InputBox function of VBA.

Note 2: For more details related to the writing of the VBA Select Case statement, refer to the codes of the examples and their explanations given in this article.

3. Differentiate between the Select Case and If Then Else statements of Excel VBA.

The differences between the Select Case and If Then Else statements of Excel VBA are listed as follows:

a. The Select Case statement evaluates a single expression at a time, while the If Then Else statement can evaluate multiple expressions simultaneously.
b. The Select Case statement checks one expression for multiple possible outcomes, while the If Then Else statement checks multiple expressions for multiple possible outcomes.
c. In a Select Case statement, any number of Case statements can be included without impacting the readability of the code. In contrast, a lot of conditions tend to make the If Then Else statement unreadable.
d. It is easy to write, edit, and make changes to the Select Case statement. On the other hand, it is difficult to write, identify errors, and make changes to the If Then Else statement.

In both, Select Case and If Then Else statements, a code is executed depending on whether a condition is met or not. So, based on the requirement and convenience, one can choose either of the two statements.

Recommended Articles

This has been a guide to the Excel VBA Select Case statement. Here we discuss how to use the Excel VBA Select Case statements with certain keywords (like Is, To) along with examples and a downloadable Excel template. Take a look at the following Excel VBA articles–

  • VBA LCase
  • Excel VBA InputBox
  • FIND VBA Function
  • What is VBA Range?

Using Excel VBA to create Microsoft Word documents

In these examples, we generate Microsoft Word Documents with various formatting features using
the Microsoft Excel VBA scripting language. These techniques can have many useful applications.
For instance if you have a list of data like a price or product list in Excel that you want to present
in a formatted Word Document, these techniques can prove useful.

In these examples, we assume the reader has at least basic knowledge of VBA, so we will not
go over basics of creating and running scripts. This code has been tested on Microsoft Word and Excel
2007. Some changes may be required for other versions of Word and Excel.

Writing to Word
Inserting a Table of Contents
Inserting Tabs
Inserting Tables
Inserting Bullet List
more on Inserting Tables
Multiple Features

Function that demonstrates VBA writing to a Microsoft Word document

The following code illustrates the use of VBA Word.Application object and related properties.
In this example, we create a new Word Document add some text.

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
	
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
            .Font.Bold = True
            .Font.Name = "arial"
            .Font.Size = 14
            .TypeText ("My Heading")
            .TypeParagraph            
        End With
    End With 

Some VBA Vocabulary

ParagraphFormat
Represents all the formatting for a paragraph.

output in MS Word:

Inserting a Table of Contents into Word Document using Excel VBA

In this example, we generate a Table of Contents into a Word Document using Excel VBA

Sub sAddTableOfContents()
    
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
	
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
    
    Dim wdDoc As Word.Document
    Set wdDoc = wdApp.Documents.Add
    
    ' Note we define a Word.range, as the default range wouled be an Excel range!
    Dim myWordRange As Word.range
    Dim Counter As Integer
    
    wdApp.Visible = True
    wdApp.Activate
    
    'Insert Some Headers
    With wdApp
        For Counter = 1 To 5
            .Selection.TypeParagraph
            .Selection.Style = "Heading 1"
            .Selection.TypeText "A Heading Level 1"
            .Selection.TypeParagraph
            .Selection.TypeText "Some details"
        Next
    End With

    ' We want to put table of contents at the top of the page
	Set myWordRange = wdApp.ActiveDocument.range(0, 0)
    
    wdApp.ActiveDocument.TablesOfContents.Add _
     range:=myWordRange, _
     UseFields:=False, _
     UseHeadingStyles:=True, _
     LowerHeadingLevel:=3, _
     UpperHeadingLevel:=1

End Sub

Some VBA Vocabulary

ActiveDocument.TablesOfContents.Add
The TablesOfContents property to return the TablesOfContents collection.
Use the Add method to add a table of contents to a document.

Some TablesOfContents Parameters

Range The range where you want the table of contents to appear. The table of contents replaces the range, if the range isn’t collapsed.

UseHeadingStyles True to use built-in heading styles to create the table of contents. The default value is True.

UpperHeadingLevel The starting heading level for the table of contents. Corresponds to the starting value used with the o switch for a Table of Contents (TOC) field. The default value is 1.

LowerHeadingLevel The ending heading level for the table of contents. Corresponds to the ending value used with the o switch for a Table of Contents (TOC) field. The default value is 9.

output Word Table in MS Word:

Write Microsoft Word Tabs

A function that writes tabbed content to a Microsoft Word Document. Note in each iteration, we change the
value of the leader character (characters that are inserted in the otherwise blank area created by the tab).

Public Sub sWriteMicrosoftTabs()

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
    
        For Counter = 1 To 3
            .Selection.TypeText Text:=Counter & " - Tab 1 "
            
            ' position to 2.5 inches
            .Selection.Paragraphs.TabStops.Add Position:=Application.InchesToPoints(2.5), _
                Leader:=Counter, Alignment:=wdAlignTabLeft
            
            .Selection.TypeText Text:=vbTab & " - Tab 2 "
            
            ' position to 5 inches
            .Selection.Paragraphs.TabStops.Add Position:=Application.InchesToPoints(5), _
                Leader:=Counter, Alignment:=wdAlignTabLeft
            
            .Selection.TypeText Text:=vbTab & " - Tab 3 "
                    
            .Selection.TypeParagraph
        Next Counter
        
    End With
End Sub

Some VBA Vocabulary

.TabStops.Add Use the TabStops property to return the TabStops collection. In the example above,
nprogram adds a tab stop positioned at 0, 2.5 and 5 inches.

output in MS Word:

Write Microsoft Word Tables

In this example, we generate a Microsoft Table using Excel VBA

Sub sWriteMSWordTable ()
 
    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        
        With .Selection
        
            .Tables.Add _
                    Range:=wdApp.Selection.Range, _
                    NumRows:=1, NumColumns:=3, _
                    DefaultTableBehavior:=wdWord9TableBehavior, _
                    AutoFitBehavior:=wdAutoFitContent
            
            For counter = 1 To 12
                .TypeText Text:="Cell " & counter
                If counter <> 12 Then
                    .MoveRight Unit:=wdCell
                End If
            Next
        
        End With
        
    End With

End Sub

Some VBA vocabulary

Table.AddTable object that represents a new, blank table added to a document.

Table.Add properties

Range The range where you want the table to appear. The table replaces the range, if the range isn’t collapsed.

NumRows The number of rows you want to include in the table.

NumColumns The number of columns you want to include in the table.

DefaultTableBehavior Sets a value that specifies whether Microsoft Word automatically resizes cells in tables to fit the cells� contents (AutoFit). Can be either of the following constants: wdWord8TableBehavior (AutoFit disabled) or wdWord9TableBehavior (AutoFit enabled). The default constant is wdWord8TableBehavior.

AutoFitBehavior Sets the AutoFit rules for how Word sizes tables. Can be one of the WdAutoFitBehavior constants.

output in MS Word:

Write Microsoft Word bullet list

In this example, we write with bullet list and outline numbers with Excel VBA

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
    
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        ' turn on bullets
        .ListGalleries(wdBulletGallery).ListTemplates(1).Name = ""
        .Selection.Range.ListFormat.ApplyListTemplate ListTemplate:=.ListGalleries(wdBulletGallery).ListTemplates(1), _
            continuepreviouslist:=False, applyto:=wdListApplyToWholeList, defaultlistbehavior:=wdWord9ListBehavior
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .Font.Bold = False
            .Font.Name = "Century Gothic"
            .Font.Size = 12
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            .TypeParagraph
        End With
        
        ' turn off bullets
        .Selection.Range.ListFormat.RemoveNumbers wdBulletGallery
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            .TypeParagraph
            
        End With
        
        ' turn on outline numbers
        .ListGalleries(wdOutlineNumberGallery).ListTemplates(1).Name = ""
        .Selection.Range.ListFormat.ApplyListTemplate ListTemplate:=.ListGalleries(wdOutlineNumberGallery).ListTemplates(1), _
            continuepreviouslist:=False, applyto:=wdListApplyToWholeList, defaultlistbehavior:=wdWord9ListBehavior
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            
        End With
        
    End With

output in MS Word:

Another example of Writing Tables to Microsoft Word

In this example we will create a word document with 20 paragraphs. Each paragraph will have a header with a header style element

    
   'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    Dim wdApp As Word.Application
    Dim wdDoc As Word.Document

    Set wdApp = New Word.Application
    wdApp.Visible = True
    
    
    Dim x As Integer
    Dim y As Integer
    
    wdApp.Visible = True
    wdApp.Activate
    wdApp.Documents.Add
            
    wdApp.ActiveDocument.Tables.Add Range:=wdApp.Selection.Range, NumRows:=2, NumColumns:= _
        2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
                
    With wdApp.Selection.Tables(1)
        If .Style <> "Table Grid" Then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        .ApplyStyleRowBands = True
        .ApplyStyleColumnBands = False
    End With
            
    With wdApp.Selection
        
        For x = 1 To 2
            ' set style name
            .Style = "Heading 1"
            .TypeText "Subject" & x
            .TypeParagraph
            .Style = "No Spacing"
            For y = 1 To 20
                .TypeText "paragraph text "
            Next y
            .TypeParagraph
        Next x
    
        ' new paragraph
        .TypeParagraph
        
        ' toggle bold on
        .Font.Bold = wdToggle
        .TypeText Text:="show some text in bold"
        .TypeParagraph
        
        'toggle bold off
        .Font.Bold = wdToggle
        .TypeText "show some text in regular front weight"
        .TypeParagraph
        
        
    End With
        
    

Some VBA vocabulary

TypeText

Inserts specified text at the beginning of the current selection. The selection is turned into an insertion point at the end of the inserted text.
If Options.ReplaceSelection = True then the original selection will be replaced. This behaves exactly the same as typing some text at the keyboard.

TypeParagraph

Insert a new blank paragraph. The selection is turned into an insertion point after the inserted paragraph mark. If Options.ReplaceSelection = True then the original selection will be replaced. This behaves exactly the same as pressing the Enter key.

output in MS Word:

Generating a Word table with VBA
	'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.

	Dim wdApp As Word.Application
	Dim wdDoc As Word.Document
	Dim r As Integer

	Set wdApp = CreateObject("Word.Application")
	wdApp.Visible = True

	Set wdDoc = wdApp.Documents.Add
	wdApp.Activate

	Dim wdTbl As Word.Table
	Set wdTbl = wdDoc.Tables.Add(Range:=wdDoc.Range, NumRows:=5, NumColumns:=1)

	With wdTbl

		.Borders(wdBorderTop).LineStyle = wdLineStyleSingle
		.Borders(wdBorderLeft).LineStyle = wdLineStyleSingle
		.Borders(wdBorderBottom).LineStyle = wdLineStyleSingle
		.Borders(wdBorderRight).LineStyle = wdLineStyleSingle
		.Borders(wdBorderHorizontal).LineStyle = wdLineStyleSingle
		.Borders(wdBorderVertical).LineStyle = wdLineStyleSingle
		
		For r = 1 To 5
			.Cell(r, 1).Range.Text = ActiveSheet.Cells(r, 1).Value
		Next r
	End With

	

output in MS Word:

Option Explicit
Dim wdApp As Word.Application
 
Sub extractToWord()

   'In Tools > References, add reference to "Microsoft Word 12 Object Library" before running.
   
    Dim lastCell
    Dim rng As Range
    Dim row As Range
    Dim cell As Range
    Dim arrayOfColumns
    arrayOfColumns = Array("", "", "", "", "", "", "", "", "", "", "", "", "", "", "")
    Dim thisRow As Range
    Dim thisCell As Range
    Dim myStyle As String
    
    ' get last cell in column B
    lastCell = getLastCell()
    
    Set rng = Range("B2:H" & lastCell)
    
    'iterate through rows
    For Each thisRow In rng.Rows
            
        'iterate through cells in row row
        For Each thisCell In thisRow.Cells

            If thisCell.Value = arrayOfColumns(thisCell.Column) Or thisCell.Value = "" Then
            ' do nothing
                ''frWriteLine thisCell.Value, "Normal"
                ''frWriteLine arrayOfColumns(thisCell.Column), "Normal"
                  If thisCell.Value = arrayOfColumns(thisCell.Column) Or thisCell.Value = "" Then
                  End If
                  
            Else
                myStyle = "Normal"
                Select Case thisCell.Column
                    Case 2
                        myStyle = "Heading 1"
                    Case 3
                        myStyle = "Heading 2"
                    Case 4
                        myStyle = "Heading 3"
                    Case Is > 5
                        myStyle = "Normal"
                    
                End Select
                    
                frWriteLine thisCell.Value, myStyle
            End If
        
        arrayOfColumns(thisCell.Column) = thisCell.Value
    
      Next thisCell
    Next thisRow
    
End Sub

Public Function getLastCell() As Integer

    Dim lastRowNumber As Long
    Dim lastRowString As String
    Dim lastRowAddress As String
         
    With ActiveSheet
        getLastCell = .Cells(.Rows.Count, 2).End(xlUp).row
    End With
    
End Function

Public Function frWriteLine(someData As Variant, myStyle As String)
    
    If wdApp Is Nothing Then
        
        Set wdApp = New Word.Application
        With wdApp
            .Visible = True
            .Activate
            .Documents.Add
        End With
            
    End If
    
    With wdApp
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
            .Style = myStyle
            .TypeText (someData)
            .TypeParagraph
        End With
    End With
    
End Function

output in MS Word:

Excel VBA Online Tutorial — learn VBA Programming, enhance your Excel skills!

Learn Excel VBA programming with our easy to understand Excel VBA Online Tutorial — access examples & illustrations, live codes and downloadable files which will make learning VBA simple and quick for you. The VBA course starts with Excel VBA Basics, teaches how to create your own VBA Procedures & Macros, explains how to use Automation with VBA (Send Email from Excel, Automate PowerPoint, …) and then illustrates how to Connect with Databases (Access).

VBA for Excel

VBA is a programming language used to work with Microsoft Excel, and also with other Microsoft Office applications like Microsoft Word, Microsoft Access, PowerPoint, … and with many third-party applications. VBA stands for Visual Basic for Applications and reference to Excel VBA indicates that the Application is Excel. It is a language which Excel understands and is used to give instructions to Excel to program and automate tasks.

Benefits of VBA

VBA programming is used to get enhanced functionality which might be beyond an Excel spreadsheet;

VBA is used to automate repetitive tasks in Excel;

VBA is used to integrate Excel with other Office applications such as Microsoft Access.

Our Excel VBA Online Tutorial

Learn Excel VBA programming with our easy to understand Excel VBA Online Tutorial — access examples & illustrations, live codes and downloadable files which will make learning VBA simple and quick for you. If you are finding VBA difficult to learn, or if you find it too complicated, or if you feel it is beyond your capacity, then you have come to the RIGHT place. We keep it easy! Our tutorial is in plain language, in English, and will enable you to master Excel VBA effortlessly.

Brief Contents: Excel VBA Basics; VBA Objects; Working with Variables; Conditional Statements; VBA Loops; Application Object; Workbooks & Worksheets; Cells & Ranges in VBA; String & Date Functions; VBA Procedures & Functions; VBA Arrays; Error Handling; Events; Custom Classes & Objects; UserForms; Charts, Shapes, ActiveX & Form Controls; PivotTables with VBA; Automation with VBA (Send Email from Excel, Automate PowerPoint, …); Connect with Databases — ADO, ADOX &  DAO;

Methodology: You will create a Free Login Account on our site (‘VBA Tutorial Login’ on the Left Panel), and then Login with your username and password to access our Online Tutorial. You will get complete access to the Excel VBA course, structured in appropriate Sections & Chapters, with Live Codes & Downloadable Excel Files. You can learn VBA from the comfort of your house or office, 24 x 7, without any time limits, explained in a simple and easy manner.

The tutorials are based primarily on Microsoft Excel 2007.

Is the VBA Tutorial for YOU?

The tutorial presumes a basic knowledge of Microsoft Excel for the user, and familiarity with basic Excel concepts and using a Spreadsheet.

We expect the VBA Tutorial to be useful for users who are either beginners in VBA, as well as those already having a reasonable working knowledge of VBA.

Why Us?

Check out what some existing users have to say about our Excel VBA Tutorial (click for all Testimonials):

«Thanks very much. Excellent tutorial … Looked like a nightmare on other sites. This one broke it down and showed it best. Cheers!

«I find your site very informative and written in understandable language.»

«Thank you for sharing your excellent, clear VBA explanations. It saves my time.»

«I have been teaching myself VBA over the past 5 months by incorporating it into many useful projects. I have purchased several well-known books and searched the internet extensively as I’ve encountered problems. I don’t know what took me so long to come across your site, but it is without a doubt, the best site on the web for getting a good handle on VBA. The clear examples and descriptive notes are very informative. You provide much depth while keeping it simple.»

«Good Work! One of the best sites i have come across.!! I was stuck up in a problem fr 3 days….n i got it solved here..!! Many Many thanks :)»

«I was completely taken back by the amount of information and examples that were offered. I stopped writing my code, and I spent over two hours exploring the MANY facets of this site. The whole time, I was saying, » Wow!…. Wow!… Wow!» . Your explanations and examples have helped me a great deal! «

«I’ve been to all kinds of excel schools, addin, books, excel program like … Finding ways to make me understanding excel in shortcut mode. Wanted to know the code and just copy with simple reason about the code. Done. period. I’m thankful for your work … and give me more information if there’s more.»

Get the VBA Advantage Today — learn Excel VBA & Macros, take your Excel skills to the next level!

We want you to come join us, in the marvelous world of vba programming, to discover the magic of vba!

Detailed Contents of Excel VBA Online Tutorial

Sections           
Chapters Topics
     

Excel VBA Basics

Excel VBA — Introduction

Programming Languages & Visual Basic;

Visual Basic for Applications (VBA), VBA is GUI-based; Visual Basic is not truly an Object-Orientated Programming (OOP) Language;

VBA is an Event-driven programming language; Enable VBA / Macros in Excel 2007 & 2003;

VBE — the VBA Code Editor

Launch the Visual Basic Editor;

Visual Basic Editor components — Code Window, Project Explorer, Properties Window, The Programming Workspace;

Record & Run Macros

Record and Run Macros using the Excel Macro Recorder — the Record Macro dialog box, Naming a Macro, Assign a Keyboard Shortcut, Store a Macro, Add a Description, Recording a Macro, View, Edit & Run a Recorded Macro, Use Relative References, Limitations of Recording a Macro, Storing a  Macro in Personal Macro Workbook;

Starting with VBA, Writing Code

Basic concepts in brief:

Excel VBA Objects, Properties & Methods;

Event Procedures in VBA;

Visual Basic Editor (VBE);

Modules in Excel VBE;

VBA Procedures;

Creating a sub-procedure;

Run or Execute a Procedure;

Line Continuation within VBA code;

Auto Syntax Check;Comment Text within VBA code;

Indenting your VBA code;

Using Variables in VBA;

Keywords in VBA;

Arithmetic Operators;

String Operators;

Using Message Box in your code;

Examples of writing vba code;

Message Box & Input Box

Using Message Box in vba code — MsgBox Function;

Using Input Box in vba code — InputBox Function, Application.InputBox Method, Accepting formulas in InputBox, Accepting a cell reference as a Range object in InputBox;

Excel VBA Objects

Working with Objects

VBA Objects;

The Excel Object Model;

Access an Object / Access a Single Object from its Collection; Properties and Methods of Objects;

Working with Objects in Excel VBA — Excel VBA IntelliSense, Using With…End With Statement to refer to Objects, Using Variables in VBA, Keywords in VBA, Assign an Object to a Variable, using the Set Keyword;

Working with Variables

Declare Variables in VBA

Declaring Variables — variables are initialized to a default value, assign a value to a variable, assign an object reference, using Option Explicit;

Valid and Invalid Declaration of Variables; Dim statements declared at 3 basic levels — Procedure Level, Module Level, Project Level;

Initialize variables;

Static Statement;

ReDim Statement to Resize Dynamic Array;

Variable Names — Naming Conventions for Variables; Variable Data Types;

Conditional Statements

If…Then…Else Statements

If…Then…Else Statements — Multiple line statements, Nesting, using NOT Operator with IF statement, Single line If…Then…Else Statements, Select…Case, compared to If…Then…Else Statements;

Select…Case Statement

Select…Case Statement (VBA) — using the To keyword to specify the upper and lower range of values, using the Is keyword (with a comparison operator) to compare values, using a comma to separate multiple expressions or ranges in each Case clause, Option Compare Setting, Nesting, GoTo statement, compared to If…Then…Else Statements;

Excel VBA Loops

Excel VBA For & Do Loops

The For Loop — the For … Next Statements, the For Each … Next Statements, Nesting Loops, the Exit For Statement;

The Do While Loop — the Do While … Loop Statements, the Do … Loop While Statements, the Exit Do Statement;

The Do Until Loop — the Do Until … Loop Statements, the Do … Loop Until Statements, the Exit Do Statement;

Excel Application Object

Application Object, Properties & Methods

Excel VBA Application Object;

Instances where using the Application qualifier is required — Height, Width and WindowState Properties, DisplayFullScreen Property, DisplayFormulaBar Property, Calculation Property, EditDirectlyInCell Property, ScreenUpdating Property, DisplayAlerts Property, DefaultFilePath Property, Quit Method, Application.OnTime Method, ActivateMicrosoftApp Method, Application.GetOpenFilename Method;

When it is not required to specify the Application qualifier — ActiveCell Property, ActiveWindow Property, ActiveWorkbook Property, ThisWorkbook Property, ActiveSheet Property, ActiveChart Property, ActivePrinter Property, Selection Property, Sheets Property, Range Property, Calculate Method;

Application.OnTime VBA, Schedule Macros

Excel Application.OnTime Method — Scheduling OnTime Events;

Stop or Cancel a Running Procedure (using the OnTime method);

Excel VBA Workbooks

Workbook Object, Properties & Methods 

Reference a Workbook object — Workbooks.Item Property, ActiveWorkbook Property, ThisWorkbook Property;

Open, Add, Copy & Close Workbooks — Workbooks.Open Method, Workbooks.Add Method, Close Method, OpenDatabase Method, SaveCopyAs Method;

Saving Workbooks — Workbook.Save Method, Workbook.Saved Property;

Often used Methods & Properties of the Workbook Object — Workbook.Activate Method, PrintPreview Method, Workbook.SendMail Method, Workbook.ActiveSheet Property, ActiveChart Property, FileFormat Property, Name Property, Password Property, Path Property; 

Excel VBA Worksheets

Worksheet object, Properties & Methods 

The Worksheet Object, Sheets Object, Chart Object, 4 types of sheets — worksheet, chart sheet, macro sheet,dialog sheet;

Reference a Worksheet object — Item Property, The Active Object, Code Name and Sheet Name;

Activate or Select a Worksheet — ActiveSheet Property, Activate Method, Select Method;

Adding & Naming Worksheets — Add Method, Default worksheet names on creating a new workbook, Name property;

Copy a Worksheet, Move or Change Worksheet Sequence, Hide or Display Worksheets, Remove or Delete a Worksheet — Copy Method, Move Method, Visible Property, Delete Method; Worksheet Page Layout & Views — PageSetup Property, PrintPreview Method, DisplayPageBreaks Property, View Property;

Calculating Worksheets — Calculation Property, Calculate Method; Speed up your VBA Code by Turning off Screen Updates and Automatic

Calculations — Screen Updates and Automatic Calculations, CalculateBeforeSave Property, EnableCalculation Property

Run Macros on Protected Worksheet 

Run VBA Macros on Protected Worksheet;

Unprotect & Protect;

Error Handler;

UserInterfaceOnly argument in the Protect method;

Run macro on protected worksheet, code remaining visible & editable, but protection password hidden;

Using the UserInterfaceOnly argument to Enable Auto Filter;

Using UserInterfaceOnly argument to Allow Grouping; Worksheet.Protect Method; 

Excel VBA Cells & Ranges 

Referencing Cells & Ranges — 1 

Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address — Range Object, Range property, Shortcut Range Reference, Cells Property, Item property, Columns Property, Rows Property, Accessing a worksheet range with vba code (Referencing a single cell, Referencing a range of cells, Referencing Rows or Columns, Relative Referencing), Range.Row Property, Range.Column Property, Range.Address Property;

Activate & Select Cells;

The ActiveCell & Selection — Select method, ActiveCell Property, Selection property, Activate Method;

Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method — EntireRow Property, EntireColumn Property, Insert Method

Referencing Cells & Ranges — 2 

Ranges, Union & Intersect — Union Method, Intersect Method, using Intersect method with worksheet change or selection change events;

Resize a Range — Offset & Resize properties of the Range object;

Contiguous Block of Cells, Collection of non-contiguous ranges, Cells Meeting a Specified Criteria, Used Range, Cell at the End of a Block / Region — Using the Areas Property, CurrentRegion Property, SpecialCells Method, UsedRange property, End Property, find Last Used Row in a worksheet

Find Method in Excel VBA 

Find Method in Excel VBA;

Find multiple occurrences of an item or value in a range;

Using Find Method to do VLookUp;

Using Find Method to Search for a Date;  

VBA — Last Used Row & Column 

Use End(xlUp) to determine Last Row with Data, in one column;

Use End(xlToLeft) to determine Last Column with Data, in one row;

UsedRange property to find the last used row number in a worksheet;

UsedRange property to find the last used column number in a worksheet;

UsedRange property to find number of used rows in a worksheet;

UsedRange property to find number of used columns in a worksheet;

UsedRange property to find the first used row number in a worksheet;

UsedRange property to find the first used column number in a worksheet;

Use End(xlDown) to determine Last Row with Data, at the End of a Block in a column;

Use End(xlToRight) to determine Last Column with Data, at the End of a Block in a row;

FIND method to determine Last Row with Data, in a worksheet;

FIND method to determine Last column with Data, in a worksheet;

SpecialCells method to find Last Used Row in worksheet;

SpecialCells method to find Last Used Column in worksheet; 

Text, String & Date Functions 

Excel Text & String Functions — 1 

Excel VBA String Functions for Finding and Replacing Text, with Examples: LEFT, RIGHT, MID, LEN, REPLACE;

InStr & InStrRev Functions (VBA);  

Excel Text & String Functions — 2 

Excel VBA String Functions: SPLIT, JOIN, CONCATENATE — Excel VBA Functions to Split a String into Substrings, and Join an Array of Substrings to form a String, with Examples

Functions — CODE & CHAR / Asc & Chr 

Excel Text and String Functions: Excel CODE & CHAR Functions, VBA Asc & Chr Functions, with examples — Changing case (uppercase / lowercase) of alphabets in a string, format or manipulate data with ANSI codes

ASCII & ANSI Code, Extended ASCII characters 

ASCII Code;

ASCII to Extended ASCII characters (8-bit system) and ANSI Code;

Extended ASCII characters (8-bit) and UNICODE;

The Windows SDK provides function prototypes in generic, Windows code page (ANSI) and Unicode versions;

Excel uses ANSI code system for Windows computers; ASCII Non-Printing Control Codes Chart;

ASCII Printing Characters Chart;

Extended ASCII Printing Characters Chart; 

Column No. to Letter, Column Letter to No. 

VBA Codes to Convert Excel Column Number to corresponding Column Letter;

VBA Codes to Convert Excel Column Letter to corresponding Column Number; 

VBA Convert to UpperCase / LowerCase 

Worksheet vba codes for: Convert Text and Cells with Formulas to UpperCase;

Convert Text and Cells with Formulas to UpperCase;

Convert Text and Cells with Formulas to UpperCase;

Convert Text to UpperCase; 

Excel VBA Dates & Time, Format Function 

Excel VBA Dates & Time — Excel Dates Equate to Serial Numbers, Date Data Type in VBA, System’s Locale settings vs. Code Locale, Format specified in your computer’s regional settings;

Format Function in VBA — Predefined Named Date/Time Formats, System-defined Format, Predefined Named Numeric Formats, User-Defined Number Formats, User-Defined Date & Time Formats, User-Defined String Formats, Multiple Sections for User-defined Formats

Excel VBA Date & Time Functions 

VBA DateSerial Function;

DateValue Function;

TimeSerial Function;

TimeValue Function;

IsDate Function;

CDate Function;

DateAdd Function;

DateDiff Function;

DatePart Function;

Date Function;

Now Function;

MonthName Function;

Day Function;

Month Function;

Year Function;

Hour Function;

Minute Function;

Second Function;

WeekDay Function;

WeekdayName Function;

Find Method to Search for a Date; 

Custom Number Formats, Date Formats 

Excel Home Tab, Format Cells dialog box;

VBA, NumberFormat property;

Number Codes; Specify Font Color;

Four Sections of Code;

Specify Conditions;

Custom Date & Time Formats;  

Excel VBA Procedures 

Subs & Functions, Placement in Modules 

Sub procedures (Event Procedures & User Created), Function Procedures (Built-in & User-defined) & Property Procedures;

Naming Rules & Conventions for Procedures;

VBA Procedures Scope — Public vs Private; Placement of Macros / Sub procedures in appropriate Modules — Standard Code Modules, Workbook module, Sheet Modules, UserForm Modules, Class Modules;

Calling Procedures — Calling Sub procedures in the Same Module, Calling Functions in the Same Module, Calling Procedures in Outside Modules;

Executing Procedures — Executing Function Procedures, Executing Event Procedures, Executing Sub Procedures

Pass Arguments to Procedures, ParamArray  

Argument Data Types;

Passing Arguments By Value;

Passing Arguments By Reference;

Optional Arguments;

Pass an Arbitrary or Indefinite Number of Arguments — Parameter Arrays (ParamArray);  

VBA — Empty, ZLS, Null, Nothing, Missing 

Empty, Blank, ZLS (zero-length string), Null String & vbNullString;

IsEmpty Function;

VarType Function;

Null;

IsNull Function;

Nothing;

Missing;

IsMissing function;  

Excel VBA Arrays 

Excel VBA Arrays 

VBA Arrays;

Declare Arrays, Sizing an Array, Determining the Upper and Lower Bounds;

One-Dimensional and Multi-Dimensional Arrays;

Fixed-size and Dynamic Arrays;

ReDim Statement to Resize Dynamic Array;

use the ‘Preserve’ Keyword with the ReDim statement;

Excel VBA Functions — SPLIT a String and return an Array of Substrings, JOIN an Array of Substrings to form a String;

Create a 200-Year Calendar in VBA, using Arrays with Loops;

ParamArray (Parameter Array); 

Error Handling & Debugging

Error Handling in VBA

VBA Erros & Error Handling, Error Handling Setting in VBE, Error Handler, On Error Statements, Using an Exit Statement, Error Handling in Nested Procedures & The Resume Statement, Get Information from the Error Object, Raise Method of the Err Object — Generate a Run-time error.

Debugging Tools in VBE

Debug Code by using a Message Box, Use Breakpoints to Debug Code, Using Break Mode to Debug Code, Stepping Through Code, Debugging Views — Immediate Window, Locals Window, Watch Window, Call Stack.

Excel VBA Events  

Excel VBA Built-in Events 

Excel VBA Events; Event Procedures;

Built-in Event procedures & Custom events;

Excel events broadly classified — Workbook events, Worksheet events, Chart events, UserForm events, Application events, Events not associated with objects

Worksheet Change Event 

Worksheet_Change Event;

Target parameter;

Preventing Event Loops with Application.EnableEvents = False;  

Worksheet Selection Change Event 

Worksheet_SelectionChange Event;

Preventing Event Loops with Application.EnableEvents = False; 

Custom Classes & Objects 

Custom Classes & Objects, Custom Events 

Excel VBA Custom Classes & Objects — Insert a Class Module, Name a Class Module, Instancing Property of a Class Module, Instantiate a Class Object, Create Class Properties, Using Property Procedures to Create Properties (Property Get, Property Let, Property Set);

Custom Class Events — Define a Custom Event, Raise an Event, External Code to Raise the Event, Create an Event Procedure

ActiveX & Form Controls, AutoShapes

ActiveX & Form Controls, AutoShapes

Built-in Excel Data Form;

Using ActiveX controls, Form controls & AutoShapes in Excel Worksheet;

Shape object & OLEObject object;

ActiveX Controls in VBA;

Add an ActiveX Control, a Form Control or an AutoShape, in Worksheet;

Illustrating Form Controls, ActiveX Controls & AutoShapes — Button (Form Control) & Command Button (ActiveX Control), Check Box (Form Control or ActiveX Control), List Box & Combo Box (Form Control / ActiveX Control), Option Button (Form Control or ActiveX Control), Toggle Button (ActiveX Control), ScrollBar & SpinButton Controls(Form Control or ActiveX Control), TextBox (ActiveX Control), Label (Form Control or ActiveX Control), Illustrating Auto Shapes & Add a connector;

UserForms in Excel VBA 

UserForm Basics, Add Controls 

UserForms in Excel VBA;

Create a UserForm; UserForm ToolBox Controls — A Snapshot;

UserForm Basics; Trapping UserForm Events;

Add Controls to a UserForm — using the Add Method; 

UserForm and Controls — Properties 

Design-Time, Run-time and Break-time;

Setting control properties with vba;

Basic Properties common to the UserForm and most Controls — Name Property, Caption Property, Height & Width Properties, Left & Top Properties, Value Property;

Other Properties common to the UserForm and most Controls — Accelerator Property, Alignment Property, AutoSize Property, BackColor Property, BackStyle Property, BorderColor Property, BorderStyle Property, ControlSource Property, ControlTipText Property, Enabled Property, Locked Property, Font Object, ForeColor Property, MouseIcon Property, MousePointer Property, Picture Property, PicturePosition Property, SpecialEffect Property, TabIndex Property, TabStop Property, Visible Property, WordWrap Property;

Specifying Color in Properties Window;

Applicability of Properties to UserForm and its Controls — A SnapShot; 

Label, TextBox & CommandButton 

Label Control; CommandButton — Click event;

TextBox — AutoTab Property, EnterKeyBehavior Property, MaxLength Property, MultiLine Property, PasswordChar Property, ScrollBars Property, Text Property

ComboBox & ListBox 

Difference between ListBox and ComboBox;

Key Properties of ComboBox and ListBox — AddItem Method, BoundColumn Property, Clear Method, Column Property, ColumnCount Property, ColumnHeads Property, List Property, ListCount Property, ListIndex Property, ListRows Property, MultiSelect Property, RemoveItem Method, RowSource Property, Selected Property, Style Property, TextColumn Property;

Add Items/Data to (Populate) a ListBox or ComboBox — Setting the RowSource property of a ListBox or ComboBox in a UserForm, Populate a ComboBox or ListBox from an Array, Populate a ComboBox or ListBox with AddItem method, Populate a multi-column ComboBox or ListBox using AddItem method and List & Column properties, Populate a multi-column ListBox from a worskheet range, using AddItem method and List property, Add a new item/row to the list if ComboBox is bound to data in a worksheet;

Extract ListBox & ComboBox Items, with VBA — Display selected ComboBox item in TextBox, Copy selected ComboBox item to a worksheet range, Copy ComboBox item determined by its position, to a worksheet range;

Delete ListBox rows using the RemoveItem Method; 

CheckBox, OptionButton, ToggleButton 

CheckBox — Value property, TripleState property;

OptionButton — GroupName property, using a Frame Control, Value property;

Difference between CheckBox and OptionButton;

ToggleButton;  

Frame, MultiPage & TabStrip 

Frame Control;

MultiPage Control — Dynamically Add/Remove a Page, Dynamically Access an individual Page, Create a wizard using a Single UserForm and MultiPage control;

TabStrip Control — Dynamically Add/Remove a Tab, Difference between a MultiPage control and TabStrip control, Selecting a Tab

ScrollBar & SpinButton 

ScrollBar Control — SmallChange & LargeChange Properties, Min and Max Properties, Orientation Property;

SpinButton Control — SmallChange & Min & Max & Orientation Properties, Difference between ScrollBar & SpinButton controls

Image & RefEdit 

Image Control — LoadPicture function, PictureSizeMode Property, PictureSizeMode Property, PictureAlignment Property, Use LoadPicture property with GetOpenFilename Method;

RefEdit control; 

Charts in Excel VBA

Add a Chart, Chart & ChartObject objects

Charts in Excel VBA;

Worksheet & Chart Sheet in Excel — Chart objects in VBA;

Add a Chart — Charts.Add Method, ChartObjects.Add Method;

ChartObject object — Commonly used Properties & Methods;

Chart object — Commonly used Properties & Methods;

Chart Elements: Chart Title, Chart & Plot Area, Axes

Chart Title — Commonly used Properties & Methods of the ChartTitle object, Child Objects for the ChartTitle Object;

Chart Area —  Commonly used Properties & Methods of the ChartArea object, Child Objects for the ChartArea Object;

Plot Area —  Commonly used Properties & Methods of the PlotArea object, Child Objects for the PlotArea Object, PlotArea Alignment , ChartTitle Alignment, AxisTitle Alignment, Legend Alignment;

Chart Axis — Axes object & Axis object, Tick Marks & Gridlines, Commonly used Properties & Methods of the Axis object, Properties & Methods of the AxisTitle object, Properties & Methods of the TickLabels object, Child Objects for the Axis Object;

Chart Elements: Chart Series, Data Labels, Legend

Chart Series — SeriesCollection object & Series object, Commonly used Properties & Methods of the Series object, Child Objects for the Series Object, ErrorBars & LeaderLines, Combination Chart;

DataLabels Object & DataLabel Object — Commonly used Properties & Methods of the DataLabels Object / DataLabel Object, Child Objects for DataLabels Object / DataLabel Object;

Chart Legend — LegendKey & LegendEntry, Commonly used Properties & Methods of the Legend object, Child Objects for the Legend Object.

Border / ChartFillFormat / Interior / Font Objects

Child Objects commonly used with Chart Elements — Border Object, ChartFillFormat Object, Interior Object & Font Object with Properties & Methods.

ChartFormat object, Formatting, 3D Charts

Line, fill & effect formatting for chart elements:

FillFormat object — Setting ForeColor & BackColor, Setting a Solid Fill, Setting Gradient Type, Gradient Stops, Setting Pattern, Setting Texture, Setting Picture for the Fill;

LineFormat object — Setting ForeColor & BackColor, Setting Style or Dash Style, Setting Pattern, Line Arrowheads, Transparency & Weight Properties;

ShadowFormat object;

GlowFormat object;

SoftEdgeFormat object;

ThreeDFormat object — Manipulating 3-D Charts;

Create Line, Column, Pie, Scatter, Bubble charts

Create an Embedded Chart — Line with Markers;

Creating a Clustered Stacked Column Chart;

Create a Clustered Stacked Bar Chart displaying Variance between Series;

Pie Chart;

XY Scatter Chart & Bubble Chart — Single series with X & Y values, Multiple series where all series share the same Y values with distinct X values, Manipulate both X & Y error bars;

Excel Pivot Tables with VBA 

Create Pivot Table using VBA 

Use VBA to Create and Customize PivotTable & PivotChart reports;

The PivotTableWizard method;  

Referencing Pivot Table Range 

TableRange1 Property and TableRange2 Property;

PivotField.LabelRange Property and PivotItem.

LabelRange Property;

RowRange Property and ColumnRange Property;

PivotTable.DataBodyRange Property;

DataLabelRange Property;

PageRange Property;

PivotField.DataRange Property and PivotItem.

DataRange Property;

PivotTable.PivotSelect Method;

Intersect Method;  

Reference Pivot Fields & Items 

Using the PivotTable.PivotFields Method to access a Pivot Field;

PivotTable.ColumnFields Property to access a column field;

PivotTable.RowFields Property to access a row field;

PivotTable.DataFields Property to access a data field;

PivotTable.PageFields Property to access a page field;

Reference PivotItem in a PivotField;

PivotTable.HiddenFields Property to return hidden fields;

PivotTable.PivotSelect Method to Select a part of the PivotTable;  

Pivot Table Move & Copy 

Address of Pivot Table;

Move PivotTable to a new location;

Copy a PivotTable and paste as data or values or paste as a PivotTable;  

Pivot Table Layout & Design 

Layout Forms for PivotTable report, column header and row header;

Hide or Display Subtotals;

Subtotal Location, Inserting blank lines, Show/hide GrandTotals & Grand Total Name, Set Number Format;

Pivot Table Styles — Style Gallery;

PivotTable Style Options — Row Headers, Column Headers, Banded Rows &

Banded Columns; 

Pivot Table Properties & Settings 

Get data from a PivotTable using VBA — PivotTable.GetPivotData Method;

Disable or Enable DrillDown of PivotTable Fields; Display the PivotTable FieldList;

Sort Fields in Ascending order in the PivotTable FieldList; Return the Parent object of a PivotTable object;

Allow PivotTable Update only Manually;

PivotTable.Name Property returns the name of a PivotTable object;

PivotTable Print Settings — PivotTable.PrintTitles Property, PivotTable.

RepeatItemsOnEachPrintedPage Property, Repeat specific rows at the top or columns on the left while printing a PivotTable report, PivotTable.PrintDrillIndicators Property;

Save the PivotCache data while saving the workbook;

Create a new PivotTable, each on a new worksheet, for each item of a Page field;

Return the data source of a PivotTable report;

Include hidden page field items in subtotals and totals;

Pivot Table versions & Excel version;  

Refresh Pivot Table & Cache 

PivotCache.Refresh Method to Refresh the Cache of the Pivot Table;

PivotTable.RefreshTable Method to update the PivotTable report;

Automatically refresh Pivot Tables in all worksheets on opening a workbook;

Return the Date when PivotTable was last refreshed, and Name of the user who refreshed; 

Group Items, Data & Date Values 

Group Date Values in a PivotTable report, using the Group method;

Group Date Values by Weeks;

Group Numeric Items; Group Specific Text Field Items;  

Sort Fields, Values & Dates, Custom Lists 

PivotField.AutoSort method — set sort order of a PivotTable field;

Range.Sort Method — to sort a range of values in a PivotTable report; Set the sort order manually;

Sort a PivotTable report using Custom Lists — Application.AddCustomList Method, Application.DeleteCustomList Method, Application.GetCustomListContents Method, Application.GetCustomListNum Method, SortUsingCustomLists Property;  

Filter Data, Items, Values & Dates 

PivotField.AutoShow method — to display the Top or Bottom items in a PivotTable Field;

PivotFilters.Add Method — to add new filters to a PivotTable report;

Manual Filter;

Clear Filters;

PivotTable.AllowMultipleFilters Property — apply multiple filters to a single PivotField

Summary Functions, Custom Calculations 

Pivot Table Summary Functions — xlAverage, xlCount, xlCountNums, xlMax, xlMin, xlProduct, xlStDev, xlStDevP, xlSum, xlVar and xlVarP;

Pivot Table Custom Calculations — xlNoAdditionalCalculation, xlDifferenceFrom, xlPercentOf, xlPercentDifferenceFrom, xlRunningTotal, xlPercentOfRow, xlPercentOfColumn, xlPercentOfTotal and xlIndex;  

Insert Calculated Fields, Create Formulas 

Pivot Table Calculated Fields — CalculatedFields.Add Method;

Pivot Table Calculated Items — CalculatedItems.Add Method, PivotTable.ListFormulas Method;  

Create Pivot Table Charts 

Create a PivotChart based on an existing PivotTable report;

Add embedded chart based on an Excel Database;

Create a Chart (add a new chart sheet) based on an Excel Database;

Create an embedded PivotChart based on an existing PivotTable report;  

Automation with VBA 

Automate Microsoft Word from Excel 

Automating an Office Application — Automation Process, Early Binding & Late Binding in Automation, Adding a reference to the Object Library, Built-in Constants and their Numerical Values, The Getobject function and CreateObject function;

Automating Word from Excel; 

Automate Microsoft Outlook from Excel 

Create a new instance of the Outlook application;

Using the Application.GetNamespace Method;

Reference Existing Outlook Folders and Create New Folders in Automation;

Create New Outlook Items and Reference Outlook Items;

NameSpace.GetDefaultFolder Method; Folders.Add Method;

Items.Add Method and the Application.CreateItem Method;

Using the Find and FindNext methods to search a folder;

Using the Restrict Method; 

Export contacts from Outlook to Excel 

Export contacts from Outlook to Excel — automate in vba using Early Binding and Late Binding;

Export contacts from a specific Contact Items Folder or from the default Contact Items Folder to an Excel Worksheet;  

Import Contacts from Excel to Outlook 

Import Contacts from Excel to Outlook — automate in vba using Early Binding and Late Binding;

Import data from an Excel Worksheet to the specified Contacts folder or to the default Contacts folder; 

Automate Outlook, Send Email from Excel 

Sending Email from Excel using Outlook — automate in vba using Early Binding and Late Binding;

Send text, Send contents from the host workbook’s worksheet range as Mail Body, Send an attachment with the mail;

Send multiple mails to ids sourced from the Host Workbook’s sheet;

Copy the Host Workbook or Create a New Workbook, Add a New Sheet and Copy-Paste a Range to the Workbook, then send as an attachment with

the mail;

Find a mail item in the Inbox folder meeting a specified criteria, delete or add attachment, forward it to a specific email id, and move the mail item to a newly created mail folder; 

 

Automate PowerPoint from Excel 

Automate Microsoft PowerPoint from Excel using vba & Run a Slide Show;

Create a new PowerPoint ppt of 4 sli

des with sound clips and chart, run & view the slide show, automatically close & quit the PowerPoint application;  

Connect with Databases (ADO)

Microsoft Access: ADO Library

Connect with Databases using DAO, RDO and ADO Objects;

ADO Objects & Programming model; Connecting to a Data Source (viz. Microsoft Access) using the ADO Connection Open Method;

The Connection Object; Establish Connection to a Data Source; Access records from a database table;

The ADO Recordset Open Method, to open an ADO Recordset object;

Create a new record using the Recordset Object’s AddNew method;

Update Method (ADO Recordset);

Close & Delete Methods;

Moving between Records in a Recordset;

Count the number of Records in a Recordset;

Access fields in a Recordset;

Execute SQL statements — ADO

Microsoft Access — Use ADO to Execute SQL statements to Manage your Database;

SQL Commands explained;

Using the ADO connection Execute method to execute the specified query and SQL statements;

Use the OpenSchema Method to access information about database tables and columns;

Create a database table using ADO with SQL statements;

ADO Find Method to Find or Locate a specific Record; ADO Filter Property to FilterRecords;

Import / Export Data, Access to Excel

Using ADO to Import data from an Access Database Table to an Excel worksheet (your host application);

Using ADO to Export data from Excel worksheet (your host application) to Access Database Table;

Connect to Access from Excel — ADOX

Create an Access Database using ADOX;

ADOX Table Object & Tables Collection — Properties & Methods; ADOX Column Object & Columns Collection — Properties & Methods;

Reference & Delete Database Tables and Columns and Reference & Edit Field Properties using ADOX;

Create an Index using ADOX;

Create Relationship between Tables using ADOX;

ADO Command Object, ADOX View Object, Parameter Queries, Create & Execute Stored Queries / Action Queries with ADOX;

Connect with Databases (DAO)

Connect to Access from Excel — DAO

DAO Objects & Programming model;

The DBEngine object; Workspace Object & Workspaces Collection;

DAO Databases;

Tables of a DAO Database; Fields / Columns of a Table;

Recordset & Records of a DAO Database Table;

Create Index & Relationships, Exceute Query

Create an Index using DAO;

Create Relationship between Fields of Database Tables using DAO;

Create and Exceute a Query, including Action & Parameter Query, using DAO;

Import / Export Data from Access to Excel

Import data from an Access Database Table to an Excel worksheet (your host application);

Export data from Excel worksheet (your host application) to an Access Database Table;

This post is the second in a series about controlling other applications from Excel using VBA. In the first part we looked at the basics of how to reference other applications using Early Binding or Late Binding. In this post, we will look at how we can automate Word from Excel even though we don’t know any VBA code for Word… yet. The process we will use for this is as follows:

  1. Enable the Word Developer menu
  2. Record a Word macro
  3. Add the code to Excel VBA and amend
  4. Record macros in Excel if necessary
  5. Repeat the previous steps until macro complete

I am not an Excel VBA expert (I’m more of an Excel VBA tinkerer), and I am certainly not a Word VBA expert. The process I am about to show you may not create the most efficient code, but I know this process works, because I have used it myself to automate lots tasks using Microsoft Word.

Enable the Word Developer menu

If you have enabled the Excel Developer menu it is the same process in Word.

In Word: File -> Options -> Customize Ribbon

Then tick the Developer Ribbon option, OK.

Enable Word Developer Tab

Record a Word Macro

The key to the success of this method is taking small sections of code and building up a complex macro bit by bit. Using the Word Macro Recorder is again, similar to the Excel Macro recorder.

Click on: Developer -> Record Macro

Word VBA Record Macro

For the example in this post, we will create a macro which will open a new Word document, then copy a chart from Excel and paste it into that Word document. We will tackle this one stage at a time. Firstly, lets create the macro to open a new word document.

Click – Developer -> Record Macro. The Record Macro window will open.

Word Record Macro Window

Make a note of the “Store macro in” option, as we will need to know where to find the recorded code later. Normal.dotm is fine for now. Click OK – the Macro Recorder is now running.

Open a new Word Document – File -> New -> Blank Document

Stop the Macro from recording – Developer -> Stop Recording

Word VBA Stop Recording

We can now view the code for opening a new Word Document in the Visual Basic Editor. Click: Developer -> Visual Basic.

Word Visual Basic Editor

Find the location of your recorded code in the Visual Basic Editor. In this example: Normal -> Modules -> NewMacros.

Automate Word from Excel

Your code should look like the following. It may be slightly different, but not significantly.

Sub Macro1()
'
' Macro1 Macro
'
'
    Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
    Windows("Document1").Activate
    Windows("Document2").Activate
End Sub

Add the code to Excel VBA and amend

Let’s head back to the Excel VBA Editor and use the Early Binding method to control to Microsoft Word. In the Visual Basic Editor click Tools -> References select Microsoft Word x.xx Object Library. Then click OK.

VBA Word Object Library

As we are using Early Binding we need to declare the Application as a variable as follows:

Dim WordApp As Word.Application
Set WordApp = New Word.Application

Now copy and paste the code from the Word VBA Editor into the Excel VBA Editor.

The Word VBA code started with Documents.Add, all we have to do is add our application variable to the front of that line of code. Now becomes WordApp.Documents.Add . . .

Often, Selecting and Activating Objects is not required in VBA code, so I have not copied those statements into the code below.

Sub CreateWordDocument()

'Connect using Early Binding.
'Remember to set the reference to the Word Object Library
'In VBE Editor Tools -> References -> Microsoft Word x.xx Object Library
Dim WordApp As Word.Application
Set WordApp = New Word.Application

WordApp.Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
WordApp.Visible = True 'New Apps will be hidden by default, so make visible

Set WordApp = Nothing 'release the memory

End Sub

A point to note, when an application is opened with VBA, it is normally opened in the background. To make the Word document visible I have added the following code:

WordApp.Visible = True

Record macros in Excel (if necessary)

If we want to copy Excel content into a Word document, we will need to copy that content using Excel VBA. We can use the Macro Recorder in Excel to obtain the VBA code for copying, then we can use the Word Macro Recorder to obtain the VBA code for pasting.

Macro Recording from Excel – selecting a worksheet and copying chart

Sheets("Sheet1").Select
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.ChartArea.Copy

Macro Recording from Word – pasting a chart into a document

Selection.PasteSpecial Link:=False, DataType:=wdPasteEnhancedMetafile, _
        Placement:=wdInLine, DisplayAsIcon:=False

We can add both Macro recordings into our Excel macro. Remember to add WordApp. at the start of each statement of Word VBA code.

Sub CreateWordDocument()

'Connect using Early Binding.
'Remember to set the reference to the Word Object Library
'In VBE Editor Tools -> References -> Microsoft Word x.xx Object Library
Dim WordApp As Word.Application
Set WordApp = New Word.Application

WordApp.Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
WordApp.Visible = True 'New Apps will be hidden by default, so make visible

'code copied from Excel Macro recorder
Sheets("Sheet1").Select
Selection.ChartObjects("Chart 1").ChartArea.Copy

'code copied from Word Macro recorder with WordApp. added to the front.
WordApp.Selection.PasteSpecial Link:=False, DataType:=wdPasteEnhancedMetafile, _
        Placement:=wdInLine, DisplayAsIcon:=False

Set WordApp = Nothing 'release the memory 

End Sub

This code is not particularly efficient; it contains a few unnecessary sections code. However… it works!

Repeat the previous steps until macro complete

By repeating the same steps above; recording short actions, then transferring the code into Excel, we can slowly build up much more complex Macros. The key is to keep the actions short, if you do too many actions with the Macro Recorder, code starts to look long and scary.

If you’ve you tried to use the Macro Recorder before you will know that this is not as easy as it seems. And this simple tutorial may make you think it is easy, when it’s not. Sometimes, it can be quite frustrating trying to find out where the issues and errors are. The key to success is recording very short actions, such as those below and copying them into the Visual Basic Editor.

'Pressing the Enter Key to move to a new line in Word
WordApp.Selection.TypeParagraph

'Turn on/off Bold Text
WordApp.Selection.Font.Bold = wdToggle

'Change Font Size
WordApp.Selection.Font.Size = 16

'Type some text
WordApp.Selection.TypeText Text:="Here is some text"

You will soon build up a standard library of code that you can use to control Word for most basic tasks.

In recorded VBA code from Word, the word “Selection” in the code often refers to the document itself. It is possible to make the code a little bit more efficient by declaring the document as a variable. If we were opening a specific document, we could include this at the start, just below the declaration of the application.

'Declare a specific document as a variable
Dim WordDocument As Object
Set WordDocument = WordApp.Documents.Open(sourceFileName)

Or, if we created a new document we could include the following below the declaration of the application variable.

'Delcare a new document as a variable
Dim WordDocument As Object
Set WordDocument = WordApp.Documents.Add Template:="Normal", _
NewTemplate:=False, DocumentType:=0

If we have created the document as a variable we can then reference the specific document. This code:

WordApp.Selection.TypeParagraph

Would become this code:

WordDocument.TypeParagraph

Or this code:

WordApp.Selection.TypeText Text:="Here is some text"

Would become this code:

WordDocument.TypeText Text:="Here is some text"

This method is much better, as it doesn’t rely on the Selection of the user being in the right place.

Conclusion

We have seen in this post that it is possible to create complex Macros to automate Word from Excel using VBA. By understanding how to declare variables for the application and documents we can create much more robust macros, even without knowing a lot of VBA code.

Related Posts:

  • 5 quick ways to embed a Word document in Excel
  • Controlling Powerpoint from Excel using VBA
  • Edit links in Word using VBA
  • How to link Excel to Word

Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

Понравилась статья? Поделить с друзьями:
  • Excel vba is broken
  • Excel vba not contain
  • Excel vba is application running
  • Excel vba no update screen
  • Excel vba intersect target