[Blog]  [Microsoft Office VBA: Access    Excel    Outlook    Word    VB6/Genl VBA]
[Other: .NET   VBScript/ASP   Javascript   Favorite Links] [Education: Information Technology Degrees]

Word VBA Snippets Return to Top

Excel VBA Snippets

VB/VBA Generic Code Snippets
Activate Next Window Accessing Particular Cells in Worksheet Adding Doc to Windows Recent Docs List
Activates desired Window Activate Worksheet by Name Appending Data to a Text File
Adding & Deleting Code in VBE Programatically Activates First Worksheet Automating Outlook (send email via code)
Adding Document to Recent Files List Activates Last Worksheet Automation of multiple applications (type ext)
Adding Hyperlink to a Document Adding & Positioning Charts Bubblesort routine (simplest form)
Adding VBA Code programatically Adding VBA Code Programatically Building Recordset of Contacts from Outlook
Adding a Bookmark Adding a Graphic Hyperlink to Sheet Case Control Structure (similar to If/Then)
Aligning selected paragraph to the right Adding a Custom Menu Case Conversion (upper, proper, lowercase)
Array Converted to Delimited Text String Adding a Worksheet Check for Previous Instance of Program
Ascii Character Code Alignment of Cell Contents Check for Read-Only File Attribute
Attaching a Template Application-wide Events in Excel Check whether Drive is Present
Automation of Word (getting or starting Word) Autofit Columns Checking for Existence of a Directory (VBA)
Autosize Height of Rows in a Table Automatic and Manual Recalculation Clearing ALL Controls on a Form
Build an Array of Filenames and perform operation on each file in the array Automating Access (Reports) Clearing Documents List (under Start menu)
Building an Array of Filenames (after browse) Automating Internet Explorer from Excel Close/Termination another Application
Built-In Word Dialogs List Built-In Dialogs and Argument Lists Code (via Automation) to Import Tab-Delimited File into Excel
Built-in Document Properties Comments field Built-In File Search Code to open an Output File in Notepad
Changing Directory for File Open operations Button Faces (to list all of them) Compacting Access database using VB
Character position in a document Closing a Workbook (with options) Concatenating/Merging Output lines using the Print command
Character right (moving 1 char to the right) Color Constants for Excel Converting Numbers to Words
Clear Find Formatting Column Number & Letter of Active Cell Copying a File using the CopyFile API cmd
Closing Word Document (with various options) Column Number or Letter of selected cell Creating a Global Hotkey
Color constants for Word Conditionally formatting col & row when cursor moves Creating a Shortcut on the Desktop
Column Fill (fills values from above) Content & Format of Cells Creating a Timer using System ticks
Comparing Addresses of Bookmarks Convert Column Letter to Number function Creating a Unique Temporary File (w/API)
Comparing Location of Bookmarks Convert Column Number to Letter function Creating and Reading Cookies
Converting a Table to Text (tabbed columns) Converting Formulas to Values Creating and Using Collections
Copying selection to clipboard Copying one worksheet to another Current Directory (finding with API)
Counting and selecting objects within a Word Document (available collections) Counting and Selecting Worksheets Cycling through a character string (in memory)
Creating backup copy of active doc with .old ext Counting functions within Excel Date Validation Function using a passed Object (textbox)
Cursor Types (normal & hourglass) Counting workdays between two dates Dates -- Locating Earliest and Latest
Cursor Types in Word (hourglass vs. normal) Create Array of Worksheet Names Delete File using DeleteFile API cmd
Cutting Selected Text Create Valid Worksheet Name function Deleting Occurrences of Substring in String
Cycling thru Document Pages Create new Workbook from Worksheet Deleting a File to the Recycle Bin
Cycling thru Document Revisions (track changes) Creating Text File from a Worksheet Delimited Text to an Array (similar to Split())
Cycling thru Footnotes and Endnotes Creating and Sizing Cell Comments Detecting the Screen Settings
Cycling thru Paragraphs and other collections Cursor shape (hourglass display) in Excel Detects Keyboard Key Pressed
Cycling thru macros in the Normal template and replacing earlier with later versions (powerful!) Date Calculation (variations) Determines if Task is Running
Cycling thru the Paragraphs of a Word doc Date Formats and Comparisons Determining File Association (uses API)
Date Information (various formats -- insert cmd) Date & Time calculations using Now() Determining Upper & Lower Array Bounds
Default Directory Locations (Tools|File Locations) Delete All Hidden Rows in Worksheet Determining User selection in combobox
Delete one or more Hyperlinks from Document Delete Cell Contents without deleting cell Determining the Datatype
Delete paragraphs containing particular term Delete Toolbar when closing Workbook Determining the Size of a File
Deleting ALL Bookmarks in Document Deletes Active Worksheet (no save) Directory File Count (number of files in directory)
Deleting Duplicate Paragraphs (without sorting) Deleting Custom Menu Directory File List (returns array of filenames)
Deleting a named Bookmark Deleting Particular Columns Disabling the Form Close "X" button
Determine if Template Modules are Password Protected Deleting Selected Rows Display Run Dialog
Directories and subdirectories (from starting point) Deleting a Workbook (i.e., File) Download file from Internet using API
Directory information and management Detecting Menus that are present Dynamic DLL/OCX Registration
Displaying Userform Determining Last Cells (column & row) with Data Email using CDO.sys from VB6 (useful!)
Document (i.e., File) Save with variations Determining if hyperlink exists in active cell Email using MAPI
Document Format Types (e.g., Text, RTF) Determining selection areas of worksheet Enumeration methods and objects
Document Open, Read, and Close Display Alerts (turning them on and off) Erasing an Array (removing all the elements)
Events Listing for various form objects Displaying information about all Hyperlinks Excel chart creation through Automation
Executing a Menu Option using VBA Drop-Down Cell Values (restricting User) Fast File Search (using Scripting Runtime)
Extending Selection 1 character to the right Excel Chart from VB6 DisplayImage Control File Creation using Common Dialog ctrl
Extending Selection 1 word to the right Excel Startup Switches File Input / Output Example
Extending Selection Down 1 Line Feeds Listbox Items to Word Doc (using Automation) File Operations using Scripting Runtime
Extending Selection to the End of the Line File Open Dialog (for browsing and selecting files) Filename Array from Active Directory
Extending Selection to the End of the Paragraph File SaveAs Dialog (for saving files) Finding a File using Scripting Runtime
Extending Selection to the Start of the Line Filename of the active Workbook (full path/name) Folder selection API routine (displays treeview list of dirs for selection)
Feed an Array into a New Document (del dupes) Fill Empty Cells of Selected Area with Data Above Cell Format() function with variations
File Open (opening a known document) Following Hyperlink in the selected Cell Free Space on a Disk Drive
File Open dialogs (to browse & select file) Following and Executing Hyperlink Function for Opening & Closing CD Tray
Find text (simple form) Font Colors (index to the Font.ColorIndex numbers) Function to Convert Binary to Decimal
Find formatted text Formatting the first Row (as with a Heading) Function to Convert Binary to Octal
Finding text formatted in a particular Style Formatting worksheet cells (many properties) Function to Convert Column Number to Letter(s)
Fonts Listing (examples of all fonts in Word) Freeze window panes (above & left of current cell) Function to Convert Decimal to Hexadecimal
Footnote info (best approach for working with footnotes) Height of cell row (setting height of selected cell row) Function to Count Substring within a String
Footnote numbering option (setting with VBA) Hyperlinking Cells among Worksheets (same wkbk) Function to Escape (\) Regex characters
Format determination (such as a bullet) Hyperlinks Collection (and using it) Function to create Legal Filename from String
Going to a particular table (tables Goto command) Inserting a Formula into the Active Cell Function to determine if number is odd or even
Hyperlink extraction to 2nd doc (very useful) Inserting a row into the active worksheet Function to find the first Word in a String
Inserting Text into a Document (various methods) Last Row Containing Data Function to locate first Num & Alpha in String
Jump to a URL on Internet (w/ default browser) Linking a Pivot Table to a Database Get Cursor Position using API
Learn active toolbar when a button is clicked Logical functions in Excel Get entire Command Line (using API)
List macros within one or more templates Menu & Toolbar Added/Deleted on Workbook Open & Close Getting Clipboard Data using API Call
List Directories & Subdirs from Given Dir Moving to different worksheet cell (relative to present position in the worksheet) Getting User's name regular way or with API
Moving macros between templates (Organizer) Moving down one cell (changing active cell) Getting Windows & System Directories
Moving style between templates Moving one cell to the right Getting the MSDOS Prompt/DOS Window
Moving Cursor to Named Bookmark Moving worksheet to particular location (i.e., order) Getting/Retrieving Registry Settings
Moving Cursor to the End of the Document Naming the active worksheet Go to URL with Default Browser (API used)
Moving cursor down 1 line Object Reference for Excel Automation Graphical Measurement Conversions
Moving cursor down 1 paragraph Opening a Workbook (known filename) HTML page for VB program documentation
Moving cursor to end of paragraph Outlook Automation from within Excel Handle of Window Cursor is Floating Over
Moving cursor to end of selection (variations) Pasting (previously copied) Cells Hex Value of Colors (for object properties)
Moving cursor to start of selection (variations) Powerpoint Automation (complex!) from within Excel Hexadecimal to Decimal Conversion
Moving cursor to the end of the line Protecting & Unprotecting Worksheet using VBA Hide all Command Bars
Opening a blank Word document Reading Excel Environment Settings Importing a Macro into the VBE
Overriding Word's Built-In Commands Removing a Module using VBA Inputbox Cancel versus No Input
Paragraph alignment (reading the property) Removing all fill colors from a workbook KeyPress event of a Textbox
Paragraph properties (read when para selected) Restoring Excel Environment Settings (previously read) Keypress for VBA object (not same as VB)
Pasting text from the clipboard Roman Numeral function Last Date Modified of a Web Page (URL)
Pre-defined (Built-in) Bookmarks Row number of Selected Cell Like() function for pattern-matching in code
Pre-defined Bookmarks (good for navigation) Running Excel Macro using VBA Code List of Open Window Names (using API)
Previous window (going to it) Saving a Workbook without Dialogs Listing objects programatically (collections)
QuickSort (Fast!!) (Multidimensional on 2 dims) Selecting ALL the Cells in a Worksheet MessageBox using MessageBox API
QuickSort (Fast!!) (Multidimensional on 3 dims) Selecting Non-Adjacent Cells in Worksheet Minimize all windows (using API)
QuickSort (Fast!!) (Single Dimension) Selecting particular Columns Minimizing a Form (from code within form)
Random number generation (within limits) Selecting particular Rows Moving a Window to the Foreground
Removing whitespace from string of text Selecting Ranges, Rows, and Columns Moving the Cursor to the Top of a Textbox
Repeating last Find command Selecting a Particular Cell (using col & row numbers) Obtaining File Attributes (using API)
Replace Indents with Tab Characters Setting Printer Specifications using VBA Octal to Decimal Conversion
Replaces Multiple Spaces with a Single Space Setting the Column Width of the Active Cell Column Opening and Reading a Known Text File
Repositioning cursor (and text) to middle of screen Setting Current Cell's Value Opening Recycle Bin (using API)
Saving and Restoring Find Dialog settings Shading Alternate Rows in a Worksheet Opening Start Menu (using API)
Selecting text in Word doc using locations Shading of Selected Cells Outlook Automation
Selecting the entire Word document Slanting Text at an Angle (within cell) Passing Arguments to Functions and Procedures (rules & guidelines)
Selecting a row in a Word table Sorting Excel Worksheet by Particular Columns Positioning form on the Screen
Selection information avail in Word (large list!) Split or UnSplit Windows Progress Bar showing percentage complete
Setting Word Tools Options (with VBA) Subtotal (built-in) Function (with explanation) QuickSort (multidimensional) on 2 Dimensions (i.e., columns) -- Fast!!
Setting width of Pictures contained in Document Summation Function (many examples!) QuickSort (multidimensional) on 3 Dimensions -- Fast!!
Sort HTML Table Area (created for this page!) Turning Row/Column Headings & Grid Lines on/off QuickSort (multidimensional) on 4 Dimensions -- Fast!!
Sorting by paragraphs (once text block selected) Un-hiding Columns QuickSort (multidimensional) on a single dimension -- Fast!!
Special characters in Word (as in Find/Replace) Using Built-In Excel Dialogs QuickSort routine
Start of Document (relocating cursor to top) Word Automation from Excel Remove Directory (using API)
Start of Line (relocates cursor) Workbook Built-In Document Properties Removing Duplicates from an Array
Starting a New Document (i.e., New File) Working with Workbooks Removing an Item from a Listbox
Status Bar Messages (shows progress thru doc)

Outlook Code Snippets Return to Top
Replacing one or more substrings in string
Style Validation and/or Creation ("DeleteStyle") Adding Appointment in Outlook using Automation Returning Multiple Filenames from Common Dialog control
Subdirectories of current directory Adding Contact in Outlook using Automation Running one macro from another macro
Toggle Field Codes in a Document (visible or not) Adding an Address Book entry Saving Text using the Common Dialog
Toggle Toolbar routine (visible vs. not visible) Adding an information store (*.pst) Savings Settings in the Registry
Turn screen updating on/off (improves speed!!) Address Book Entry (Properties Sheet) Screen Metrics (height & width) using API
Turning Track Changes On/Off in Word Attaching Files in a Directory to an Email Sending command to Run dialog (under Start)
Underlining selection in Word (with various styles) Attachment Item Methods Set Environment Variables
Unhiding all hidden text in a Word document Attachment Item Properties Set File Attributes
Window name (can be activated as needed) Compose and Read Layouts Set Tab Stops in a Listbox
Word Automation (simple example) Creating and Sending Appointment using VBA Setting Screen Resolution (height & width)
Word Document Properties & Statistics Cycling thru Folder viewing Tasks Setting VB Form on Top of All Windows
Word Startup Command Line Switches Delete Address Book entry Setting visible page of multi-tabbed form

Access Code Snippets Return to Top
Delete Outlook Toolbar (function) Shell Execute using API
#1 Secret for Avoiding Access Jet Database Corruption in a Multi-User Environment Deleting completed Outlook tasks Show timed Splash Form on Startup
ADO Connection method (for creating recordset) Determining Outlook folder type Simulate Ctrl-C for Copying to Clipboard
Access Command Line switches Determining default information store (*.pst) Sorting a Listbox (complete example!)
Access_Records_to_Excel Determining selected Contact Specific Time Delays in Programs
Activating a database form Display Properties page using person's name State Postal Abbreviations (in an array)
Adding Project References using VBA Email Items into a Multivariable Array Storing Values in the Registry
Adding Records to Current Database Email Methods Task Manager disable/enable (Ctrl-Alt-Delete control of processes)
Adding, Updating, or Deleting records using SQL Email Properties Time delays and Event timing
Automating Database Compaction (every 5 times) Email with Attachments Treeview ... Adding Nodes
Calculated controls (ControlSource expressions) Folder Iteration (moving through folder tree) Treeview ... Adding Root Node
Capitalizes all characters of a database field Form validation formulas and error messages Treeview ... ChildNode Info of Selected Node
Changing database password via Code Listing of Appointment Item Methods Treeview ... Collapsing Nodes to Root Level
Closing a database form Listing of Appointment Item Properties Treeview ... Complete Subprocedure for Collapsing Nodes
Closing a Database Listing the entries in Outlook Address book Treeview ... Counting Number of Nodes
Compaction of Database using JRO (ADO) Looping through Outlook toolbars collection Treeview ... Determing selected Node and Highlighting it
ControlSource data from Another Form Obtaining address of email recipients Treeview ... Expanding All Nodes
Convert an ADO Recordset to HTML Obtaining address of the email sender Treeview ... Node Click Event
Creating & Running a Query Definition using VBA Obtaining names of information stores (*.pst) Treeview ... Number of Children (in parens) appended to Text of Selected Node
Creating a Recordset from the Current Database Outlook Object Classes & Constants (can use either) Treeview ... Reacting to Drag and Drop
Creating a Recordset from within Database Outlook Object Collections (various available items) Treeview ... Reacting to DragOver in a Treeview
Creating a New Database Outlook Object Model Constants Treeview ... Repositioning Cursor to the Top of the Tree
Creating a Recordset Clone Outlook Programming Tips Treeview ... Text of Selected Node
Cursor shapes for hourglass and normal Outlook datatypes (differs significantly from others) Trim function (homegrown)
DSN-less Connection to Access for ASP Outlook form creation steps Using Split() function to create Array
Database ControlSource calculations Retrieving Contact information using VBA Using a Control to Capture Clipboard Data
Database DLookup() function Search Outlook Folders Recursively Using Common Dialog to browse for filename
Database Error Table creation Show Address Book entries Using SendKeys() to send keystrokes
Database Me object Show Distribution List members VB Naming Conventions
Database Recordset Open Options (Access) Show Outlook Address lists VB Data Conversion Functions
Database Security -- Adding User to Group Startup Switches for Outlook VBE Shortcuts available
Database Security -- Adding a Group Account Unusual Aspects of Programming in Outlook Variables & Procedures (declarations, scope, passing)
Database Security -- Adding a New User

VB Script/ASP Snippets Return to Top
Visual Basic Operator (<, >, >=, etc.)
Database SysCmd Function (3 functions in one!) ASP Objects and Properties Volume Info of Specified Disk Drive
Database Transaction processing (to avoid partial records) Adding Database Records using VBScript Ways of Referencing a Collection
Database bookmarks (marking & returning to records) Arrays in VBScript Web Page/URL Source Code Retrieval
Database combobox update and list item selection Checkbox group (reading multiple checked values) Word Wrap toggle for RichTextbox
Database connection example Combobox (drop-down list) change event Working with Objects as Variables
Database containers Copy file method (using File Scripting Object -- FSO) Writing Text to a known Filename and Opening in Notepad
Database filename and path information Creating a temp file using FSO Writing a Text File (Basic Example)
Database Form Open? (subroutine to check) Creating a text file using FSO

VB.NET Snippets Return to Top
Database Table creation using VBA Creating an HTML table from a recordset Add, Cycle Through, & Remove Elements from ArrayList (VB.NET)
Database record locking types and method Cycling through the Request form items collection Adding a Row of Data to a Dataset table (ADO.NET)
Dealing with Null Strings in Access DSN-Less Connection string for an Access database Adding a control to a form dynamically (VB.NET)
Declaring a database Recordset object Date validation function Adding fields and primary key to a dataset (ADO.NET)
Determing Properties of Database DateDiff() function in VBScript Application path in VB.NET
Differences between two dates in Access Delete file method using FSO Assigning property values to objects in .NET (VB.NET)
Disabling Shift-Key Bypass of Startup Form Deleting record from database using VBScript Check for previous instance of application (already running) in VB.NET
Disabling the "X" (upper-right) Exit in Userforms Determining combobox / listbox selection Convert bitmap (BMP) to another image format (VB.NET)
DoCmd Object to perform macro actions Displaying file information using FSO Create an Access database at runtime (VB.NET)
Domain Aggregate functions Displaying folder information using FSO Create an Excel workbook from an XML file (Excel, XML)
Eliminate Leading Zeros from Access field Do-Loop using VBScript Create/Delete Directories and Subdirectories in VB.NET
Exporting Query Results to Another Format Error handling on an ASP page Creating context menu on right-click of mouse (VB.NET) (example of Treeview control)
Forward-Only Recordset access (fastest!!) Excel output from Form elements Cursors -- How to Set Shape of Cursor (.NET)
List the values of a particular database column Form Reset button with Confirmation dialog Deleting a row (at cursor location) from the dataset (ADO.NET)
Listing Users and Groups in a Workspace Form button properties and methods Deleting record(s) in the Dataset (ADO.NET)
Listing field names and field descriptions from Access Table (using VBA) Function tied to button click event Determine if File or Folder Exists in VB.NET / ASP.NET
Moving focus to particular control in Access form HTML combobox selection handled by separate ASP page Determining if Microsoft Office applications are installed
Opening a Recordset (options explained) HTML form elements Display an icon in a picture-box control (VB.NET)
Opening and Closing a Database Connection HTML Color Constants (#... values) Enter Key being pressed while in Textbox (VB.NET)
Printing Recordset to a Text File HTML components File attributes (obtaining them) (VB.NET)
Pulling Records from Access to Word Handling ADO errors on ASP page Filename without the path or extension (VB.NET)
QueryDef Creation (using VBA) In-stream VBScript command tied to a form button Form on top of all other windows (VB.NET)
QueryDef Modification (using VBA) Initializing the DSN-Less connection to Access database Hashtable class (VB.NET)
Recordset Methods (working with recordsets) Loading a URL into the active window (i.e., going to a different web page) How to Remove recent Projects from Startup Page in Visual Studio.NET
Recordset creation & connection for Current Database (ADO Method) Passing info from client to server using VBScript (*** Important ***) Managing the clipboard in VB.NET
SQL Query Results placed in an Array Radio button option group (creating and reading) Obtaining the name of a field in a Dataset (ADO.NET)
Security -- List Groups & Users belonging to same Reading an Excel file using ADO Positioning cursor at top of treeview (VB.NET)
Security -- Listing Permissions granted Reading form values from client-side VBScript Reading text data from clipboard using VB.NET
Security -- Table Read Permission for User Resetting a form Referencing a particular column of a dataset row (ADO.NET)
Synchronization of Replica Databases Retrieving database records -- simple example Removing/Deleting a field from a Dataset (ADO.NET)
Table creation Running a function when the page loads Routines needed for Drag & Drop of treeview nodes (VB.NET)
Turning Off Alerts Sending an Email from an ASP page Screen resolution using VB.NET
Using SQL Query to load values to a combobox Server object and methods Searching/Finding text forward in RichTextBox (VB.NET)

Javascript Snippets Return to Top
Session variables Searching/Finding text in reverse in RichTextBox (VB.NET)
Alert message dialog Setting page expiration in the User's cache Selecting records from dataset matching certain criteria (ADO.NET)
Array Creation and Output Updating database records using ADO Selecting the Treeview node at the Cursor/Mouse position (VB.NET)
Array from String Using a button to jump to a particular URL (web page) Setting the transparency/opacity of a control or form (VB.NET)
Array Handling VBScript client-side & server-side subroutine and function structure (*** Important ***) Show all files in a directory (VB.NET)
Browser History Navigation VBScript function responding to combobox / listbox change Show all subfolders (VB.NET)
Button Click Function VBScript subroutine creating an HTML table Specifying which Page to display in a TabControl (VB.NET)
Calendar Creation VBScript/ASP routine to list server variables Storing & Retrieving Font properties (VB.NET)
Checkbox disabling   Storing and retrieving color for a control using color dialog (VB.NET)
Checkbox display and detection   To cycle through all the fields in a Dataset Table (ADO.NET)
Checkbox state validation   To determine if text in a rich textbox has changed (VB.NET)
Clock set function    
Confirmation dialog    
Cookie (retrieving named value)    
Cookie (storing named value)    
Current date/time    
Current hours & minutes    
Datatype conversion to integer    
Datatype validation    
Date difference calculation    
Date output to screen    
Days until specified date    
Dialog boxes (alert, confirm, and prompt)    
Enter key event handling    
File browse dialog    
Hiding and displaying elements via code    
Link navigation with confirmation    
Reset button with confirmation    
Save button with confirmation    
Try/Catch runtime error handling    
Various date formats    
Weekday and date    
Weekday from passed date    
     
     
     
     
     

Send comments and suggestions to: webmaster@vba-programmer.com
setstats