Click here to Skip to main content
15,860,972 members
Articles / Productivity Apps and Services / Microsoft Office

Office Programming Helper Indent VB Code

Rate me:
Please Sign up or sign in to vote.
4.89/5 (39 votes)
4 Sep 2023CPOL5 min read 224.4K   6.1K   128   43
Indent code, add line numbers, err handling, add number to words and more, expose a .NET library to Microsoft Word, Excel, Power Point macros writers and Access VBA code
In this article, you will see how to indent code, add line numbers, do error handling, expose a .NET library and number to words to Microsoft Word, Excel, Power Point macros writers and Access VBA code This application is not just an add-in. It offers many other helpful resources. It provides to you the simplest way to build your add-on.

Image 1

System Requirements

What's New

  • Windows 11 is supported now

For Whom This Application is Written

If you are one or more of the following, then I hope that you will find this application helpful:

  • Microsoft Word, Excel and PowerPoint macros writers
  • MS Access forms designer
  • VBA (Visual Basic for application) Developers
  • Add in builder

How This Application Differs

  • This application is not just an add-in. It offers many other helpful resources.
  • It provides you with the simplest way to build your add-on

Background

Although VB6 went out, VBA is still needed to develop Office macros or Microsoft Access modules so VBA add-in is important.

Using This Application to Indent Your VBA Code and Add Error Handler

  • Install the app.
  • Open an Office document that contains a macro and edit the macro in the VBA window it or open the Microsoft Access Module.
  • Write your VBA code.
  • From the Add-Ins menu, choose to Add an error handler to this file.
  • This will change the format of your code as follows...

Sample of code before applying this add-in:

VB
Public Sub Macro1()
    MsgBox("This is Macro1")
End Sub

Sample of code after applying this add-in:

VB
Public Sub Macro1()
    On Error GoTo EorrorHandler
1:  MsgBox("This is Macro1")
    Exit Sub
EorrorHandler:
    Debug.Print "Error in: Module1.Macro1." & Erl & vbNewLine & Err.Description
    'This will print the error Module name and the Error Sub Name and 
    'line number in the immediate window and this is useful in debugging
    Debug.Assert False
    'This will stop the execution of the code if you are in debug mode and 
    'has no effect in run mode
    MsgBox "Error in: Module1.Macro1." & Erl & vbNewLine & Err.Description
    'This will show a message box about the error in run time
End Sub 

Using This Application to Expose Some .NET to Your VBA Code

Declaring NP and Number to Words Objects

  • Open an Office document that contains a macro and edit the macro in the VBA window it or open the Microsoft Access Module
  • In the VBE Window, Select Tools, References, Browse, then select the file
    C:\Program Files\OfficeProgrammingHelper\Bin\OfficeProgrammingHelper.tlb
  • Repeat this for the file
    C:\Program Files\OfficeProgrammingHelper\Bin\NumberToText.tlb
  • Insert the following code in any VBA Module:
    Public NP As New OfficeProgrammingHelper.NP
  • Now you could use the NP object in any code in your project.

Using NP Object

You could call the NP object in your code to use the functions:

  • NP.Clipboard: It is used to access the computer clipboard. Example: Put or get a text from the clipboard with a specific format, clear the clipboard or convert the text in its form or to Unicode.

  • You could put or get text with the following formats: Text, Unicode text, RTF, and HTML.
    VB
    Sub Test()
        NP.Clipboard.Clear
        NP.Clipboard.SetText "Some Text"
        NP.Clipboard.Ascii2Unicode
        NP.Clipboard.Unicode2Ascii
        Debug.Print NP.Clipboard.GetText
    End Sub
  • NP.Directory: Create, Delete, Exists, Move
    VB
    Sub Test()
        If Not NP.Directory.Exists("C:\Temp") Then NP.Directory.CreateDirectory "C:\Temp"
        NP.Directory.Move "C:\Temp", "C:\Temp2"
        NP.Directory.Delete "C:\Temp2"
    End Sub
  • NP.File: Copy, Create, Delete, Exists, Move, Shell
    VB
    Sub Test()
        If Not NP.File.Exists("C:\Temp.txt") Then NP.File.Create "C:\Temp.txt"
        NP.File.Move "C:\Temp.txt", "C:\Temp2.txt"
        NP.File.Copy "C:\Temp2.txt", "C:\Temp.txt"
        NP.File.Delete "C:\Temp2.txt"
        NP.Shell "C:\Temp.txt"
    End Sub
  • NP.Screen: CM, Height, Width, TwipsPerPixelX, TwipsPerPixelY
  • NP.Text: EncodingConvert, EncodingConvertByCodePage, GetTextHeight, Md5Hash, TrimAny
  • NP.SQL

NumbersToText

This library will convert numbers to words in English or Arabic and could be used in your Office applications:

VB.NET
Dim c As New NumberToArabicWords
Debug.Print(c.ConvertToWords(10002015)) 

Switch Off the Debug Mode When Executing Office Macro

  • Open an Office document that contains a macro and edit the macro in the VBA window or open the Microsoft Access Module
  • From the Tools menu, choose your project properties, then choose Protection
  • Check the Lock project for viewing
  • Type a password and click OK
  • Close your document and reopen it

Useful Ready to Import VBA Code

You will find in the bin directory of the application some useful VBA code ready to use:

  • Molecular Weight Calculation code that enables calculating Molecular Weight from the line formula
  • Useful MS Access database function to help refresh linked tables and get the next empty integer value for the field in a query and get LastValue in a table

Expose .NET Controls as ActiveX

This library also exposes some .NET controls to be used in Office VBA forms and in ActiveX containers.

Other Useful VBA Add-ins

Here are some useful add-ins you may be interested in:

Points of Interest

How to Write a VBA Addin

  • Create a new class library project that uses  V 4.8 .NET Framework and ComVisible.
  • Add the following references:
    • System
    • System.Windows.Forms
    • Extensibility = Microsoft Add-In Designer
    • Microsoft.Vbe.Interop
    • Microsoft.Office.Core
  • Add a class that Implements IDTExtensibility2
  • Write your code in C# or VB:
    C#
    private const string AddErrorHandlerCaption = "Add error handler to this file";
    
    private CommandBarControl AddErrorHandlerMenuItem;
    private CommandBarEvents AddErrorHandlerEvent;
    void IDTExtensibility2.OnConnection(object Application, 
    ext_ConnectMode ConnectMode, object AddInInst, ref System.Array custom)
    {
    	this.OnConnection(Application, ConnectMode, AddInInst, ref custom);
    }
    private void OnConnection(object Application, 
    ext_ConnectMode ConnectMode, object AddInInst, ref System.Array custom)
    {
    	try
    	{
    		//save the VB instance
    		VBInstance = (VBE)Application;
    		AddErrorHandlerMenuItem = AddToAddInCommandBar(AddErrorHandlerCaption);
    		AddErrorHandlerToProjectMenuItem = 
                    AddToAddInCommandBar(AddErrorHandlerToProjectCaption);
    		//sink the event
    		this.AddErrorHandlerEvent = 
                 VBInstance.Events.CommandBarEvents(AddErrorHandlerMenuItem);
    		//.....More Code
    	}
    	catch (Exception ex)
    	{
    		ErrMsg(ex);
    	}
    }
    
    void IDTExtensibility2.OnDisconnection
         (ext_DisconnectMode RemoveMode, ref System.Array custom)
    {
    	this.OnDisconnection(RemoveMode, ref custom);
    }
    private void OnDisconnection
            (ext_DisconnectMode RemoveMode, ref System.Array custom)
    {
    //INSTANT C# TODO TASK: The 'On Error Resume Next' 
    //statement is not converted by Instant C#:
    	On Error Resume Next
    	//delete the command bar entry 
    
    	AddErrorHandlerMenuItem.Delete();
    	//.....More Code
    	//shut down the Add-In
    }
    
    private void OnAddErrorClick
    (object CommandBarControl, ref bool handled, ref bool CancelDefault)
    {
       //.....Your click event code here
    }
    
    //INSTANT C# NOTE: Converted event handler wireups:
    	private bool EventsSubscribed = false;
    	private void SubscribeToEvents()
    	{
    		if (EventsSubscribed)
    			return;
    		else
    			EventsSubscribed = true;
    
    		AddErrorHandlerEvent.Click += OnAddErrorClick;
    	}
    VB.NET
    Private Const AddErrorHandlerCaption As String = "Add error handler to this file" 
      
    Private AddErrorHandlerMenuItem As CommandBarControl
    Private WithEvents AddErrorHandlerEvent As CommandBarEvents
    Private Sub OnConnection(ByVal Application As Object _
    , ByVal ConnectMode As ext_ConnectMode, ByVal AddInInst As Object _
    , ByRef custom As System.Array) Implements IDTExtensibility2.OnConnection
        Try
            'save the vb instance
            VBInstance = CType(Application, VBE)
            AddErrorHandlerMenuItem = AddToAddInCommandBar(AddErrorHandlerCaption)
            AddErrorHandlerToProjectMenuItem = _
            AddToAddInCommandBar(AddErrorHandlerToProjectCaption)
            'sink the event
            With VBInstance.Events
                Me.AddErrorHandlerEvent = .CommandBarEvents(AddErrorHandlerMenuItem)
                '.....More Code
            End With
        Catch ex As Exception
            ErrMsg(ex)
        End Try
    End Sub 
      
    Private Sub OnDisconnection(ByVal RemoveMode As ext_DisconnectMode _
    , ByRef custom As System.Array) _
    Implements IDTExtensibility2.OnDisconnection
        On Error Resume Next
        'delete the command bar entry 
      
        AddErrorHandlerMenuItem.Delete()
        '.....More Code
        'shut down the Add-In
    End Sub 
      
    Private Sub OnAddErrorClick(ByVal CommandBarControl As Object, _
        ByRef handled As Boolean, _
                ByRef CancelDefault As Boolean) Handles AddErrorHandlerEvent.Click
       '.....Your click event code here
    End Sub
  • Generate a reg file to register your add-in for VBA like this:
    reg
    REGEDIT4 
      
    [HKEY_CURRENT_USER\Software\Microsoft\VBA\VBE\6.0\Addins\{ClassProgId}]
    "CommandLineSafe"=dword:00000000
    "Description"="{ClassDescription}"
    "FriendlyName"="{ClassDisplayName}"
    "LoadBehavior"=dword:00000003 
    
    [HKEY_CURRENT_USER\Software\Microsoft\VBA\VBE\6.0\Addins64\{ClassProgId}]
    "CommandLineSafe"=dword:00000000
    "Description"="{ClassDescription}"
    "FriendlyName"="{ClassDisplayName}"
    "LoadBehavior"=dword:00000003 
              
    [HKEY_CURRENT_USER\Software\Microsoft\VBA\6.0\Common] 
      
    "FontFace"="Courier New"
    "FontHeight"="10"

    {ClassProgId}, {ClassDescription} and {ClassDisplayName} will be replaced with their values for this addin'. {ClassProgId} is the full class name example: VBAErrorHandler.Connect

    Both Addins and Addins64 keys are required for 64-bit addin.

  • Create a setup project that installs and registers the class for com and adds the above reg file to the registry.

How to Analyze the VBA Module

Although we could move from one procedure to another using CodeModule an object, the application will be more quick execution than if we get all the Module code, then analyze it using Regular Expressions and use it to analyze each procedure.

Regular Expressions Learning

Many applications may help you learn Regular Expressions:

  1. Expresso form http://www.ultrapico.com
  2. csharpregexdemo

About Office Addins

Microsoft Office supports add-ins written in VBA itself as word add-in (*.dotm) and access add-in (*.mda) files. Here are some useful application titles for devolving add-ins:

Related Article

History

  • 20th July 2011: Initial version
  • 4th February 2011: Adding expose .NET library to VBA
  • 21st September 2012: Adding expose .NET controls and adding installation
  • 7th August 2013: Some useful additions
  • July 2015: Color class added
  • January 2018: Fit with Windows 10
  • 2nd January 2019
  • 1st March 2020
  • 2023/08/12 Version 4

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Lebanon Lebanon
ASP.Net Hosting on Linux server
---------------------------
There is a developer behind every piece of code!
DNA is too complex what about it!
No junk DNA; There is a functional role for noncoding DNA

Comments and Discussions

 
BugAn application full of bugs and no solution is produced Pin
serkan7935423728-Aug-23 21:57
serkan7935423728-Aug-23 21:57 
GeneralRe: An application full of bugs and no solution is produced Pin
NewPast3-Sep-23 6:49
NewPast3-Sep-23 6:49 
GeneralRe: An application full of bugs and no solution is produced Pin
serkan793542374-Sep-23 0:26
serkan793542374-Sep-23 0:26 
GeneralRe: An application full of bugs and no solution is produced Pin
NewPast4-Sep-23 5:44
NewPast4-Sep-23 5:44 
GeneralRe: An application full of bugs and no solution is produced Pin
serkan793542374-Sep-23 8:51
serkan793542374-Sep-23 8:51 
QuestionA lot of work but not applicable for Business users Pin
jpvvroye17-Aug-23 2:52
jpvvroye17-Aug-23 2:52 
QuestionHelp for error Pin
serkan793542378-Aug-23 23:15
serkan793542378-Aug-23 23:15 
AnswerRe: Help for error Pin
NewPast12-Aug-23 6:21
NewPast12-Aug-23 6:21 
GeneralRe: Help for error Pin
serkan7935423713-Aug-23 0:08
serkan7935423713-Aug-23 0:08 
QuestionLibreOffice Pin
Jalapeno Bob30-Jun-23 9:54
professionalJalapeno Bob30-Jun-23 9:54 
AnswerRe: LibreOffice Pin
NewPast30-Jun-23 22:19
NewPast30-Jun-23 22:19 
QuestionInstallation of OfficeProgrammingHelper - no add-in available Pin
Member 1592882819-Feb-23 21:47
Member 1592882819-Feb-23 21:47 
AnswerRe: Installation of OfficeProgrammingHelper - no add-in available Pin
NewPast22-Feb-23 8:00
NewPast22-Feb-23 8:00 
GeneralRe: Installation of OfficeProgrammingHelper - no add-in available Pin
Member 1592882822-Feb-23 8:49
Member 1592882822-Feb-23 8:49 
GeneralRe: Installation of OfficeProgrammingHelper - no add-in available Pin
NewPast24-Feb-23 8:51
NewPast24-Feb-23 8:51 
GeneralRe: Installation of OfficeProgrammingHelper - no add-in available Pin
Member 1592882826-Feb-23 6:07
Member 1592882826-Feb-23 6:07 
AnswerRe: Installation of OfficeProgrammingHelper - no add-in available Pin
NewPast30-Jun-23 2:23
NewPast30-Jun-23 2:23 
QuestionSource Code Availability Pin
commsjockey2-Mar-20 15:52
commsjockey2-Mar-20 15:52 
AnswerRe: Source Code Availability Pin
NewPast8-Mar-20 6:16
NewPast8-Mar-20 6:16 
Generalms access Pin
Member 145739992-Sep-19 6:31
Member 145739992-Sep-19 6:31 
QuestionWindows 10 Pin
morse10027-Mar-17 9:50
morse10027-Mar-17 9:50 
AnswerRe: Windows 10 Pin
NewPast28-Mar-17 21:49
NewPast28-Mar-17 21:49 
AnswerRe: Windows 10 Pin
NewPast24-Jan-18 0:25
NewPast24-Jan-18 0:25 
GeneralMy vote of 5 Pin
MathildePichard26-Mar-17 1:39
MathildePichard26-Mar-17 1:39 
QuestionMissing Office Applications Pin
cmarcotte1-Mar-15 8:32
cmarcotte1-Mar-15 8:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.