I have created a code where I automate text files, outputting column data from an excel macro, in a specific format. I have created 5 different sub methods where they all contain almost the same lines of code. However, there are two lines of code that change for each sub. I would like to create just ONE sub just to simplify the coding for the user. The end goal is to have just one function that can be called and automatically generate the other output files (from sub test1, sub test2, sub test3, sub test4).
Below is one of the sub function code. The rest are the same except for the following lines:
stream.Write "EQUIPMENT_ID_DEF,02,0x1" & "," & Chr(34) & "ic1080_1" & Chr(34)
For the above line what changes is the 0x1 (it increases) and the "ic1080_1" which changes its name to test1, test2, etc...
If destgroup = "ic1080_1" And ssystem = "A429" And sformat = "BNR" Then
For the above line what changes is the "ic1080_1" name for the other sub names (test1, test2, etc...)
Sub ic1080_1(Path, IDnum As Integer, parmgroup As String)
'Declaring variables
Dim equipID As String, destgroup As String, sourceparmname As String, descript As String
Dim lsb As Integer, msb As Integer, signed As String, sformat As String, units As String
Dim scalefact As Variant, numbits As Integer, decim As Integer
Dim ssystem As String
Dim FName As String, stream As TextStream
Dim fso As Scripting.FileSystemObject
Dim vDB
Set fso = New Scripting.FileSystemObject
'Create txt file
Set stream = fso.CreateTextFile(Path)
'Activate Sheet1
Sheet1.Activate
With Sheet1
vDB = .Range("a1").CurrentRegion 'Get data to array from excel data range
n = UBound(vDB, 1) 'Size of array (row of 2 dimension array)
End With
'Open text file to write data
stream.Write "EQUIPMENT_ID_DEF,02,0x" & IDnum & "," & Chr(34) & parmgroup & Chr(34)
'Create arrays for each row of data
For i = 2 To n
destgroup = vDB(i, 15) '15th columm array(destination group)
ssystem = vDB(i, 7) '7th columm array(source system)
sformat = vDB(i, 32) '32nd columm array(format)
sourceres = vDB(i, 11) '11th column array(source resolution)
If destgroup = parmgroup And ssystem = "A429" And sformat = "BNR" Then
sourceparmname = format(Val(Replace(vDB(i, 8), "label ", "")), "0000")
descript = vDB(i, 3)
signed = Val(Replace(vDB(i, 33), "Yes", 1))
msb = vDB(i, 34)
lsb = vDB(i, 35)
units = vDB(i, 6)
numbits = (msb - lsb + 1) 'Calculates the number of bits
scalefact = sourceres * (2 ^ (numbits)) 'Computes the scale factor by: source resolution *(2^(msb-lsb+1))
decim = 9
'Write data into text file
stream.Write vbCrLf & "; #### LABEL DEFINITION ####" & vbCrLf & _
"EQ_LABEL_DEF,02," & sourceparmname & vbCrLf & _
"UDB_LABEL," & Chr(34) & descript & Chr(34) & vbCrLf & _
"STD_SUB_LABEL," & Chr(34) & descript & Chr(34) & "," & lsb & "," & msb & "," & signed & vbCrLf & _
"STD_ENCODING," & Chr(34) & sformat & Chr(34) & "," & Chr(34) & units & Chr(34) & "," & scalefact & "," & numbits & "," & decim & vbCrLf & _
"END_EQ_LABEL_DEF"
End If
'Continue looping until the last row
Next i
stream.Write vbCrLf & "; #### END EQUIPMENT ID DEFINITION ####" & vbCrLf & _
"END_EQUIPMENT_ID_DEF"
'Close the text file
stream.Close
End Sub
I also created another sub that calls all the subs ("ic1080_1", test1, test2, test3, test4) to output all the text files and saves them into a folder:
Sub txt_files()
Dim fso As Scripting.FileSystemObject, NewFolderPath As String
Dim Path As String
'Retrieve Target Folder Path From User
NewFolderPath = Application.GetSaveAsFilename("")
Set fso = New Scripting.FileSystemObject
If Not fso.FolderExists(NewFolderPath) Then
fso.CreateFolder NewFolderPath
End If
'Call sub functions to generate text files and store them in NewFolderPath
Call ic1080_1.ic1080_1(NewFolderPath & "\ic1080_1.txt", 3, "ic1080_1")
Call ic1080_1.ic1080_1(NewFolderPath & "\test1.txt", 4, "test1")
End Sub
Pass the bits that change between the subroutines as parameters:
Sub txt_files()
'...
'Call sub function to generate text files and store them in NewFolderPath
GenericSub NewFolderPath, "ic1080_1", "1"
GenericSub NewFolderPath, "test1", "2"
GenericSub NewFolderPath, "test2", "3"
GenericSub NewFolderPath, "test3", "4"
GenericSub NewFolderPath, "test4", "5"
End Sub
Sub GenericSub(Path As String, something As String, somethingElse As String)
'...
Set stream = fso.CreateTextFile(Path & "\" & something & ".txt")
'...
stream.Write "EQUIPMENT_ID_DEF,02,0x" & somethingElse & "," & _
Chr(34) & something & Chr(34)
'...
If destgroup = something And ssystem = "A429" And sformat = "BNR" Then
'...
End If
'...
End Sub
I may not have picked up on all the places where you are using the different parameters, but that should give you something to go on.
And please don't use names such as something and somethingElse and even GenericSub - use something meaningful to describe them. I just used those names because I wasn't sure what they meant.
Is there a way to get the enums in VBA? Something like this example for C#, but for VBA?
using System;
class EnumsExampleZ
{
private enum SiteNames
{
SomeSample = 1,
SomeOtherSample = 2,
SomeThirdSample = 3
}
static void Main()
{
Type enumType = typeof(SiteNames);
string[] enumName = enumType.GetEnumNames();
for (int i = 0; i < enumName.Length; i++)
{
Console.WriteLine(enumName[i]);
}
}
}
Lets say we have the following:
Enum FruitType
Apple = 1
Orange = 2
Plum = 3
End Enum
How can we display on the immediate window these:
Apple
Orange
Plum
There is no built-in function, though it is easy enough to roll your own in a concrete case:
Enum FruitType
Apple = 1
Orange = 2
Plum = 3
End Enum
Function EnumName(i As Long) As String
EnumName = Array("Apple","Orange","Plum")(i-1)
End Function
If you have several different enums, you could add a parameter which is the string name of the enum and Select Case on it.
Having said all this, it might possible to do something with scripting the VBA editor, though it is unlikely to be worth it (IMHO).
Parsing the VBA code yourself with the VBIDE Extensibility library is going to appear nice & simple at first, and then you're going to hit edge cases and soon realize that you need to actually implement that part of the VBA spec in order to properly and successfully parse every possible way to define an enum in VBA.
I'd go with the simple solution.
That said Rubberduck is doing pretty much exactly that, and exposes an experimental COM API that allows you to enumerate all declarations (and their references) in the VBE, effectively empowering your VBA code with reflection-like capabilities; as of 2.0.11 (the latest release), the code would look something like this:
Public Enum TestEnum
Foo
Bar
End Enum
Public Sub ListEnums()
With New Rubberduck.ParserState
.Initialize Application.VBE
.Parse
Dim item As Variant
For Each item In .UserDeclarations
Dim decl As Rubberduck.Declaration
Set decl = item
If decl.DeclarationType = DeclarationType_EnumerationMember Then
Debug.Print decl.ParentDeclaration.Name & "." & decl.Name
End If
Next
End With
End Sub
And in theory would output this:
TestEnum.Foo
TestEnum.Bar
However we (ok, I did) broke something around the 2.0.9 release, so if you try that in 2.0.11 you'll get a runtime error complaining about an invalid cast:
That should be is an easy fix that we'll patch up by 2.0.12, but note that at that point the API is still experimental and very much subject to change (feature requests are welcome!), so I wouldn't recommend using it for anything other than toy projects.
If the reason you're looking for enum names is because you mean to use them in a user interface, know that even in C# that's bad practice; in .net you could use a [DisplayAttribute] to specify a UI-friendly display string, but even then, that's not localization-friendly.
In excel-vba you can use Excel itself to remove data from your code, by entering it into a table, that can live in a hidden worksheet that can literally act as a resource file:
Then you can have a utility function that gets you the caption, given an enum value:
Public Enum SupportedLanguage
Lang_EN = 2
Lang_FR = 3
Lang_DE = 4
End Enum
Public Function GetFruitTypeName(ByVal value As FruitType, Optional ByVal langId As SupportedLanguage = Lang_EN) As String
Dim table As ListObject
Set table = MyHiddenResourceSheet.ListObjects("FruitTypeNames")
On Error Resume Next
GetFruitTypeName = Application.WorksheetFunction.Vlookup(value, table.Range, langId, False)
If Err.Number <> 0 Then GetFruitTypeName = "(unknown)"
Err.Clear
On Error GoTo 0
End Function
Or something like it. That way you keep code with code, and data with data. And you can quite easily extend it, too.
No - there is no native way to do this. You'd need to fully parse all of the user code and read the type libraries of any loaded projects and finally determine what scope each reference was referring to.
Enumerations can't be treated like reference types in VBA, and this due to the deep roots that VBA has in COM. Enums in VBA are more like aliases, and in fact, VBA doesn't even enforce type safety for them (again, because of COM interop - MIDL specs require that they are treated as a DWORD).
If you really need to do this in VBA, a good workaround would be to create your own enumeration class and use that instead.
Public Enum col: [____]: cPath: cFile: cType: End Enum
Public Const colNames$ = "Path: cFile: cType"
Not directly an answer and might look pretty ugly, but I thought it might be useful to others.
In an old project I wanted to access columns with Enum (for example row(, col.cType) = 1).
I changed the column location, name, use, etc. pretty often, but with this lazy approach I could just rearrange the Enum and then copy paste the change in the string constant, and get the table headers:
Range("A1:C1").Value2 = Split(colNames, ": c")
Names starting with _ are hidden by default, so [____] is used for padding and to avoid "cPath = 1"
I think that the marvel CPearson's site has the answer with the [_First] and [_Last] trick.
I had the need of speed up a lot of DB reading just to populate combo and list boxes with values in some Office VBA application, and I just translate them to Enums.
Of course, do a For Each like, with the For Next is a must, and the [_First] and [_Last] is the way to go. The problem is that I have a lot of non-sequential Enums, each with 10 to 40 Enum items, and code for each is too tediously.
To unify all my combo and listbox feeding needs, I adapted CPearson's trick to non-sequential Enums too:
Sub EnumValueNamesWrapingAndUnwrapingToClipboard()
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This creates a text string of the comma separated value names of an
' Enum data type. Put the cursor anywhere within an Enum definition
' and the code will create a comma separated string of all the
' enum value names. This can be used in a Select Case for validating
' values passed to a function. If the cursor is not within an enum
' definition when the code is executed, the results are unpredicable by CPearson
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim N As Long
Dim txt As String, S As String
Dim SL As Long, EL As Long, SC As Long, EC As Long
Dim DataObj As MSForms.DataObject
Dim auxTitle As String, auxStrValue As String, strAuxCase As String
Dim counter As Integer, EnumMin As Integer, EnumMax As Integer
Dim auxValue As Variant
Dim EnumIsSequential As Boolean
Const STR_ENUM As String = "enum "
If VBE.ActiveCodePane Is Nothing Then
Exit Sub
End If
With VBE.ActiveCodePane
.GetSelection SL, SC, EL, EC
With .CodeModule
S = .Lines(SL, 1)
Do Until InStr(1, S, STR_ENUM, vbTextCompare) > 0
N = N + 1
S = .Lines(SL - N, 1)
Loop
'Function title
auxTitle = Right$(S, Len(S) - InStr(1, S, STR_ENUM, vbTextCompare) - Len(STR_ENUM) + Len(" "))
N = SL - N + 1
S = .Lines(N, 1)
Do
S = .Lines(N, 1)
If InStr(1, S, "end enum", vbTextCompare) = 0 And InStr(1, S, "'", vbTextCompare) = 0 Then
txt = txt & " " & Trim(S) & ","
End If
N = N + 1
Loop Until InStr(1, S, "end enum", vbTextCompare) > 0
ReDim auxValue(0)
ReDim Preserve auxValue(0 To StringCountOccurrences(txt, "=") - 2) 'because of [_First] and [_Last]
For counter = 1 To UBound(auxValue)
auxStrValue = RetornaElementoDesignado(counter + 1, Left(txt, Len(txt) - 1))
If counter = 1 Then
EnumMin = CInt(Trim$(Right$(auxStrValue, Len(auxStrValue) - InStrRev(auxStrValue, "="))))
auxValue(counter) = Trim$(Left$(auxStrValue, InStr(1, auxStrValue, " = ")))
ElseIf counter = UBound(auxValue) Then
EnumMax = CInt(Trim$(Right$(auxStrValue, Len(auxStrValue) - InStrRev(auxStrValue, "="))))
auxValue(counter) = Trim$(Left$(auxStrValue, InStr(1, auxStrValue, " = ")))
Else
auxValue(counter) = Trim$(Left$(auxStrValue, InStr(1, auxStrValue, " = ")))
End If
Next counter
End With
End With
EnumIsSequential = NumElements(auxValue) - 1 = EnumMax - EnumMin + 1
strAuxCase = "Function ReturnNameEnum" & auxTitle & " (ByVal WhichEnum As " & auxTitle & ")As String" & vbCrLf _
& " Select Case WhichEnum" & vbCrLf
For counter = 1 To UBound(auxValue)
strAuxCase = strAuxCase & " Case Is = " & auxTitle & "." & auxValue(counter) & vbCrLf _
& " ReturnNameEnum" & auxTitle & " = " & ParseSpecialCharsAndDataTypeForSQL(auxValue(counter), False, True, False) & vbCrLf
Next counter
If EnumIsSequential Then
strAuxCase = strAuxCase & " Case Else" & vbCrLf _
& " debug.print " & """Passed invalid """ & " & WhichEnum & " & """ WhichEnum As " & auxTitle & "! """ & vbCrLf _
& " End Select" & vbCrLf _
& "End Function" & vbCrLf _
& "Function LoadEnum" & auxTitle & "InArray () As Variant" & vbCrLf _
& " 'If Enum is Sequential" & vbCrLf _
& " Dim items() As Variant, item As Long, counter As Long" & vbCrLf _
& " For item = " & auxTitle & ".[_first] To " & auxTitle & ".[_last]" & vbCrLf _
& " counter = counter + 1" & vbCrLf _
& " Next" & vbCrLf _
& " ReDim items(counter * 2 - 1) '-1: it's 0-based..." & vbCrLf _
& " For item = " & auxTitle & ".[_first] To " & auxTitle & ".[_last]" & vbCrLf _
& " items(item * 2) = item" & vbCrLf _
& " items(item * 2 + 1) = ReturnNameEnum" & auxTitle & "(item)" & vbCrLf _
& " items(item * 2) = item" & vbCrLf _
& " Next" & vbCrLf _
& " LoadEnum" & auxTitle & "InArray=items()" & vbCrLf _
& "End Function"
Else
strAuxCase = strAuxCase & " Case Else" & vbCrLf _
& " debug.print " & """Passed invalid """ & " & WhichEnum & " & """ WhichEnum As " & auxTitle & "! """ & vbCrLf _
& " End Select" & vbCrLf _
& "End Function" & vbCrLf _
& "Function LoadEnum" & auxTitle & "InArray () As Variant" & vbCrLf _
& " 'For Non-Sequential Enum" & vbCrLf _
& " Dim items() As Variant, item As Long, ExistingEnum As Long" & vbCrLf _
& " For item = " & auxTitle & ".[_first] To " & auxTitle & ".[_last]" & vbCrLf _
& " if ReturnNameEnum" & auxTitle & "(item) <> """" then" & vbCrLf _
& " ExistingEnum = ExistingEnum + 1" & vbCrLf _
& " auxExistingEnum = auxExistingEnum & CStr(item) & "",""" & vbCrLf _
& " end if" & vbCrLf _
& " Next" & vbCrLf _
& " auxExistingEnum = Left$(auxExistingEnum, Len(auxExistingEnum) - 1)" & vbCrLf _
& " arrayExistingEnum = Split(auxExistingEnum, "","")" & vbCrLf _
& " ReDim items(ExistingEnum * 2 - 1) '-1: it's 0-based..." & vbCrLf _
& " If ReturnNameEnum" & auxTitle & "(arrayExistingEnum(item)) = """" Then GoTo continue" & vbCrLf _
& " items(item * 2) = arrayExistingEnum(item)" & vbCrLf _
& " items(item * 2 + 1) = ReturnNameEnum" & auxTitle & "(arrayExistingEnum(item))" & vbCrLf _
& "continue:" & vbCrLf _
& " Next" & vbCrLf _
& " LoadEnum" & auxTitle & "InArray=items()" & vbCrLf _
& "End Function"
End If
Set DataObj = New MSForms.DataObject
With DataObj
.SetText strAuxCase
.PutInClipboard
Debug.Print strAuxCase
End With
Set DataObj = Nothing
End Sub
I added skip comment lines - I do a lot while developing.
I did not treat Enum that is not in Ascendant order; could be done, but I'm too OCD to allow an unordered Enum ;) and ordinarily, my Enums are coming from DB with an ORDER BY on the proper value (see at end of this answer).
Of course, it depends on [_First] and [_Last] values added properly.
And, answering your question, you can do a:
?ReturnNameEnumWhateverNamedItIs(FruitType.Apple)
Apple
As a bonus, and for me the main reason to adapt the CPearson's procedure, it loads in a unidimensional array tuples of value/name of Enum; so, we can navigate all Enum values with:
auxArray=LoadEnumWhateverNameYouGaveItInArray()
For counter = lbound(auxArray) to ubound(auxArray) step 2
EnumValue = auxArray(counter)
EnumStringName = auxArray(counter+1)
Next counter
The procedure is generating one of two different functions LoadEnumWhateverNameYouGaveItInArray() versions based if Enum is sequential or not.
You can forget about the sequential; the non-sequential enum function grab both situations; I left here because I developed it first and after had to adapt it to the non-sequential case, and we never know when we'll need less code lines ;)
Notice that although Enum is natively Long, I used Integer in counter/EnumMin/EnumMax, just because the Enums that I need to iterate its names are less than hundred, like fruit names.
Hope it helps someone.
Edit:
To complete the explanation, this is the procedure that I use to extract Enum from tables and write them in a static module:
Sub CreateEnumBasedOnTableValues(ByVal EnumName As String, ByVal CnnStr As String _
, ByVal DataS As String, ByVal strSQL As String _
, ByVal EnumValueField As String, ByVal EnumNameField As String _
, ByVal TreatIllegalNames As Boolean, ByVal EliminateWhiteSpaces As Boolean _
, Optional ByVal ToEscapeWhiteSpace As String = "")
Dim DataObj As MSForms.DataObject
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim auxEnum As String, bBracket As String, eBracket As String, auxRegex As String
Dim LastValue As Long
Set cnn = New ADODB.Connection
Set rst = New ADODB.Recordset
cnn.Open CnnStr & vbCrLf & DataS
rst.Open strSQL, cnn, adOpenForwardOnly, adLockReadOnly, adCmdText
If TreatIllegalNames Then bBracket = "[": eBracket = "]"
auxEnum = "Public Enum " & EnumName & vbCrLf
auxEnum = auxEnum & " [_First] = "
With rst
.MoveFirst
auxEnum = auxEnum & CStr(.Fields(EnumValueField)) & vbCrLf
Do While Not .EOF
auxEnum = auxEnum & " " & bBracket _
& IIf(EliminateWhiteSpaces, Replace(.Fields(EnumNameField), " ", ToEscapeWhiteSpace), .Fields(EnumNameField)) _
& eBracket & " = " & CStr(.Fields(EnumValueField)) & vbCrLf
LastValue = .Fields(EnumValueField)
.MoveNext
Loop
.Close
End With
auxEnum = auxEnum & " [_Last] = " & CStr(LastValue) & vbCrLf
auxEnum = auxEnum & "End Enum " & vbCrLf
Set rst = Nothing
cnn.Close
Set cnn = Nothing
Set DataObj = New MSForms.DataObject
With DataObj
.SetText auxEnum
.PutInClipboard
Debug.Print auxEnum
End With
Set DataObj = Nothing
End Sub
Just remember to pass the strSQL like that:
"SELECT EnumNameField, EnumValueField " & _
"FROM tblTarget WHERE EnumValueField Is NOT NULL " & _
"ORDER BY EnumValueField"
Usually, I use the EliminateWhiteSpaces boolean with ToEscapeWhiteSpace = "_", but is a personal preference.
For above "John Coleman"'s example I suggest to use next functions:
Function FruitType2Int(Fruit As FruitType)
FruitType2Int = Format("0", Fruit)
Debug.Print FruitType2Int
End Function
Function int2FruitString(i As Integer) As String
If i = FruitType2Int(Orange) Then
int2FruitString = "Orange"
ElseIf i = FruitType2Int(Plum) Then
int2FruitString = "Plum"
ElseIf i = FruitType2Int(Apple) Then
int2FruitString = "Apple"
Else
int2FruitString = "?"
End If
Debug.Print int2FruitString
End Function
Direct use of an Array indexes (without LBound() and etc.) may cause different resuts, depends on value in Option Base 1
Here is a function I wrote to get the enumeration member name from the value supplied. Additionally, it will list the enum names in a module, or list constant names in a module.
Public Enum CodeInfoEnum
ciEnums
ciConstants
End Enum
'---------------------------------------------------------------------------------------
' Procedure : CodeInfo
'
' Author : RMittelman#gmail.com
'
' Purpose : Searches a module for enumerations & constants
'
' History : 11/13/2022 Original version
' 11/14/2022 Added feature to list enums in the module
' 11/14/2022 Added feature to list constants inn the module
'
' Parameters :
'
' CodeType : A CodeInfoEnum member indicating Enums or Constants
'
' ModuleName : Optional. Name of module containing ItemName
' If missing, defaults to the module this function is called from
'
' ItemName : Optional. Name of the enumeration to examine
' If "?" or missing, returns a list of enumerations in the module
'
' EnumValue : optional. Value of the enumeration member wanted
' If missing, defaults to 0
' Ignored if CodType is not ciEnums
' Ignored if ItemName is missing or "?"
'
' Returns : - The text value of the enumeration value supplied; or
' - A list of enumeration names in the module; or
' - A list of constant names in the module
'
' Notes : Only searches in the module's Declarations section
'
'---------------------------------------------------------------------------------------
'
Public Function CodeInfo(CodeType As CodeInfoEnum, Optional ModuleName As Variant, Optional ItemName As String = "?", Optional EnumValueWanted As Variant) As String
Dim myApp As Access.Application
Dim compMod As Object
Dim modLines As Long
Dim procStart As Long
Dim procLines As Long
Dim idx As Long
Dim codeText As String
Dim foundItem As Boolean
Dim foundMember As Boolean
Dim tempVal As Variant
Dim enumVal As Long
CodeInfo = ""
Set myApp = CurrentProject.Application
If IsMissing(ModuleName) Then ModuleName = Application.VBE.ActiveCodePane.CodeModule
If ModuleName <> "" Then
Set compMod = myApp.VBE.ActiveVBProject.VBComponents(ModuleName).CodeModule
With compMod
' get declaration code
modLines = .CountOfLines
procStart = 1
procLines = .CountOfDeclarationLines
' search code text for enumeration(s)
idx = 0
foundItem = False
Do While (Not foundItem) And (idx <= procLines)
idx = idx + 1
codeText = .Lines(idx, 1)
' if ItemName is "?", build list of all desired items
If ItemName = "?" Then
Select Case CodeType
Case CodeInfoEnum.ciEnums
If codeText Like "*Enum *" Then
tempVal = Trim$(Mid$(codeText, InStr(1, codeText, "Enum", vbTextCompare) + 4))
CodeInfo = CodeInfo & "," & tempVal
End If
Case CodeInfoEnum.ciConstants
If codeText Like "*Const *" Then
tempVal = Mid$(codeText, InStr(1, codeText, "Const", vbTextCompare) + 6)
tempVal = Trim$(Left$(tempVal, InStr(1, tempVal, " ")))
CodeInfo = CodeInfo & "," & tempVal
End If
End Select
' otherwise, just see if we can find ItemName wanted
Else
foundItem = codeText Like "*Enum " & ItemName
End If
Loop
' if a specific Enum is found, look for the value wanted
If foundItem Then
enumVal = 0
foundMember = False
codeText = ""
Do While (Not foundMember) And (idx <= procLines) And (Not codeText Like "*End Enum")
idx = idx + 1
codeText = .Lines(idx, 1)
If codeText Like "*=*" Then
tempVal = Trim$(Split(codeText, "=")(1))
If IsNumeric(tempVal) Then enumVal = CLng(tempVal)
End If
If enumVal = EnumValueWanted Then
CodeInfo = Trim$(Split(codeText, "=")(0))
foundMember = True
End If
enumVal = enumVal + 1
Loop
End If
End With
If CodeInfo Like ",*" Then CodeInfo = Mid$(CodeInfo, 2)
End If
Set compMod = Nothing
Set myApp = Nothing
End Function
Any method which does not return a keyed collection or (preferably a scripting dictionary) will be prone to errors if the enumeration range is not a contiguous range, such as the case where you are using the enumeration to map to bits. My solution to this has been to develop a class of 'EnumerationDictionary' which allows arrays of the enumeration or the enumeration names to be returned, and name to be looked up given an enumeration and a string to be used to retrieve an enumeration. The example below is for colours in a word document and shows how to combine an internal enumeration with additional user defined values. Its a bit clunky but works very well.
Option Explicit
' A new enumeration for colour has been created to allow
' the inclusion of custom colours
' The wdColor enumeration values are the RGB vlaue as a decimal signed long
' For the hexadecimal representation the colours are BGR not RGB
' e.g. 0xXXBBGGRR not Ox00RRGGBB
Public Enum UserColour
Aqua = wdColorAqua '13421619 0x00CCCC33
Automatic = wdColorAutomatic '-16777216 0xFF000000
Black = wdColorBlack '0 0x00000000
Blue = wdColorBlue '16711680 0x00FF0000
BlueGray = wdColorBlueGray '10053222
BrightGreen = wdColorBrightGreen '65280 0x0000FF00
Brown = wdColorBrown '13209
DarkBlue = wdColorDarkBlue '8388608
DarkGreen = wdColorDarkGreen '13056
DarkRed = wdColorDarkRed '128 0x00000080
DarkTeal = wdColorDarkTeal '6697728
DarkYellow = wdColorDarkYellow '32896
Gold = wdColorGold '52479
Gray05 = wdColorGray05 '15987699
Gray10 = wdColorGray10 '15132390
Gray125 = wdColorGray125 '14737632
Gray15 = wdColorGray15 '14277081
Gray20 = wdColorGray20 '13421772
Gray25 = wdColorGray25 '12632256
Gray30 = wdColorGray30 '11776947
Gray35 = wdColorGray35 '10921638
Gray375 = wdColorGray375 '10526880
Gray40 = wdColorGray40 '10066329
Gray45 = wdColorGray45 '9211020
Gray50 = wdColorGray50 '8421504
Gray55 = wdColorGray55 '7566195
Gray60 = wdColorGray60 '6710886
Gray625 = wdColorGray625 '6316128
Gray65 = wdColorGray65 '5855577
Gray70 = wdColorGray70 '5000268
Gray75 = wdColorGray75 '4210752
Gray80 = wdColorGray80 '3355443
Gray85 = wdColorGray85 '2500134
Gray875 = wdColorGray875 '2105376
Gray90 = wdColorGray90 '1644825
Gray95 = wdColorGray95 '789516
Green = wdColorGreen '32768
Indigo = wdColorIndigo '10040115
Lavender = wdColorLavender '16751052
LightBlue = wdColorLightBlue '16737843
LightGreen = wdColorLightGreen '13434828
LightOrange = wdColorLightOrange '39423
LightTurquoise = wdColorLightTurquoise '16777164
LightYellow = wdColorLightYellow '10092543
Lime = wdColorLime '52377
OliveGreen = wdColorOliveGreen '13107
Orange = wdColorOrange '26367
PaleBlue = wdColorPaleBlue '16764057
Pink = wdColorPink '16711935
Plum = wdColorPlum '6697881
Red = wdColorRed '255 0x000000FF
Rose = wdColorRose '13408767
SeaGree = wdColorSeaGreen '6723891
SkyBlue = wdColorSkyBlue '16763904
Tan = wdColorTan '10079487
Teal = wdColorTeal '8421376
Turquoise = wdColorTurquoise '16776960
Violet = wdColorViolet '8388736
White = wdColorWhite '16777215 0x00FFFFFF
Yellow = wdColorYellow '65535
' Add custom s from this point onwards
HeadingBlue = &H993300 'RGB(0,51,153) 0x00993300
HeadingGreen = &H92D050 'RGB(146,208,80) 0x0050D092
End Enum
Private Type Properties
enum_gets_string As Scripting.Dictionary
string_gets_enum As Scripting.Dictionary
End Type
Private p As Properties
Private Sub Class_Initialize()
Set p.enum_gets_string = New Scripting.Dictionary
Set p.string_gets_enum = New Scripting.Dictionary
With p.enum_gets_string
.Add Key:=Aqua, Item:="Aqua"
.Add Key:=Automatic, Item:="Automatic"
.Add Key:=Black, Item:="Black"
.Add Key:=Blue, Item:="Blue"
.Add Key:=BlueGray, Item:="BlueGray"
.Add Key:=BrightGreen, Item:="BrightGreen"
.Add Key:=Brown, Item:="Brown"
.Add Key:=DarkBlue, Item:="DarkBlue"
.Add Key:=DarkGreen, Item:="DarkGreen"
.Add Key:=DarkRed, Item:="DarkRed"
.Add Key:=DarkTeal, Item:="DarkTeal"
.Add Key:=DarkYellow, Item:="DarkYellow"
.Add Key:=Gold, Item:="Gold"
.Add Key:=Gray05, Item:="Gray05"
.Add Key:=Gray10, Item:="Gray10"
.Add Key:=Gray125, Item:="Gray125"
.Add Key:=Gray15, Item:="Gray15"
.Add Key:=Gray20, Item:="Gray20"
.Add Key:=Gray25, Item:="Gray25"
.Add Key:=Gray30, Item:="Gray30"
.Add Key:=Gray35, Item:="Gray35"
.Add Key:=Gray375, Item:="Gray375"
.Add Key:=Gray40, Item:="Gray40"
.Add Key:=Gray45, Item:="Gray45"
.Add Key:=Gray50, Item:="Gray50"
.Add Key:=Gray55, Item:="Gray55"
.Add Key:=Gray60, Item:="Gray60"
.Add Key:=Gray625, Item:="Gray625"
.Add Key:=Gray65, Item:="Gray65"
.Add Key:=Gray70, Item:="Gray70"
.Add Key:=Gray75, Item:="Gray75"
.Add Key:=Gray80, Item:="Gray80"
.Add Key:=Gray85, Item:="Gray85"
.Add Key:=Gray875, Item:="Gray875"
.Add Key:=Gray90, Item:="Gray90"
.Add Key:=Gray95, Item:="Gray95"
.Add Key:=Green, Item:="Green"
.Add Key:=Indigo, Item:="Indigo"
.Add Key:=Lavender, Item:="Lavender"
.Add Key:=LightBlue, Item:="LightBlue"
.Add Key:=LightGreen, Item:="LightGreen"
.Add Key:=LightOrange, Item:="LightOrange"
.Add Key:=LightTurquoise, Item:="LightTurquoise"
.Add Key:=LightYellow, Item:="LightYellow"
.Add Key:=Lime, Item:="Lime"
.Add Key:=OliveGreen, Item:="OliveGreen"
.Add Key:=Orange, Item:="Orange"
.Add Key:=PaleBlue, Item:="PaleBlue"
.Add Key:=Pink, Item:="Pink"
.Add Key:=Plum, Item:="Plum"
.Add Key:=Red, Item:="Red"
.Add Key:=Rose, Item:="Rose"
.Add Key:=SeaGree, Item:="SeaGreen"
.Add Key:=SkyBlue, Item:="SkyBlue"
.Add Key:=Tan, Item:="Tan"
.Add Key:=Teal, Item:="Teal"
.Add Key:=Turquoise, Item:="Turquoise"
.Add Key:=Violet, Item:="Violet"
.Add Key:=White, Item:="White"
.Add Key:=Yellow, Item:="Yellow"
.Add Key:=HeadingBlue, Item:="HeadingBlue"
.Add Key:=HeadingGreen, Item:="HeadingGreen"
End With
' Now compile the reverse lookup
Set p.string_gets_enum = ReverseDictionary(p.enum_gets_string, "Reversing userCOLOUR.enum_gets_string")
End Sub
Public Property Get Items() As Variant
proj.Log.Trace s.locale, "{0}.Items", TypeName(Me)
Set Items = p.enum_gets_string.Items
End Property
Public Property Get Enums() As Variant
' Returns an array of Enums")
Set Enums = p.enum_gets_string.Keys
End Property
Public Property Get Item(ByVal this_enum As UserColour) As String
' Returns the Item for a given Enum")
Item = p.enum_gets_string.Item(this_enum)
End Property
' VBA will not allow a property/function Item of 'Enum' so we use
' ü (alt+0252) to sidestep the keyword clash for this property Item
Public Property Get Enüm(ByVal this_item As String) As UserColour
Enüm = p.string_gets_enum.Item(this_item)
End Property
Public Function HoldsEnum(ByVal this_enum As UserColour) As Boolean
HoldsEnum = p.enum_gets_string.Exists(this_enum)
End Function
Public Function LacksEnum(ByVal this_enum As UserColour) As Boolean
LacksEnum = Not Me.HoldsEnum(this_enum)
End Function
Public Function HoldsItem(ByVal this_item As String) As Boolean
HoldsItem = p.string_gets_enum.Exists(this_item)
End Function
Public Function LacksItem(ByVal this_item As String) As Boolean
LacksItem = Not Me.HoldsItem(this_item)
End Function
Public Function Count() As Long
Count = p.enum_gets_string.Count
End Function
Plus the following utility to reverse dictionaries.
Public Function ReverseDictionary(ByRef this_dict As Scripting.Dictionary) As Scripting.Dictionary
' Swaps keys for items in scripting.dictionaries.
' Keys and items must be unique which is usually the case for an enumeration
Dim my_key As Variant
Dim my_keys As Variant
Dim my_reversed_map As Scripting.Dictionary
Dim my_message As String
On Error GoTo key_is_not_unique
Set my_reversed_map = New Scripting.Dictionary
my_keys = this_dict.Keys
For Each my_key In my_keys
my_reversed_map.Add Key:=this_dict.Item(my_key), Item:=my_key
Next
Set ReverseDictionary = my_reversed_map
Exit Function
key_is_not_unique:
On Error GoTo 0
MsgBox _
Title:="Reverse Dictionary Error", _
Prompt:="The key and item are not unique Key:=" & my_key & " Item:= " & this_dict.Item(my_key), _
Buttons:=vbOKOnly
Set ReverseDictionary = Nothing
End Function
This answer is similar to some other answers here. In this example, "ExecutionMode" is the name of the enum.
Public Const ExecutionModes As String = "Development, Testing, Production"
Enum ExecutionMode
Development
Testing
Production
End Enum
Function EnumToString(lEnum As Long, sList As String) As String
' return list-item by enum
Dim aList
aList = Split(sList, ",")
aList = Application.Trim(aList)
EnumToString = aList(lEnum + 1)
End Function
Function StringToEnum(sItem As String, sList As String) As Long
' return listposition of string
' this only works for ordered, sequential enums
Dim vArray
vArray = Split(sList, ",")
vArray = Application.Trim(vArray)
Dim lPos As Long
lPos = Application.Match(sItem, vArray, 0) - 1
StringToEnum = lPos
End Function
Function ExecMode(sMode as String) As ExecutionMode
' return active mode of book, as enum
' Development, Testing, or Production
ExecMode = StringToEnum(sMode, ExecutionModes)
End Function
Function ExecModeStr(eMode as ExecutionMode)As String
' return mode as string
ExecModeStr = EnumToString(eMode, ExecutionModes)
End Function
Drawback: This only works for ordered, sequential enums, i.e., 0, 1,2,3,4, etc. If your enum values are anything else (e.g., 2, 4, 6 or &H80000000, &H80000002) then this solution will fail.
I'm sure it could be made to work with arbitrary numbers, but the trick is to minimize redundant typing and keep IntelliSense. I think some of the other answers here suffer from one or more of these problems:
Requires sequential items starting from 0 or 1,
or, Requires typing names or values or both twice,
or, Doesn't provide IntelliSense.
or, Requires Trusted Access to VBA
This solution already requires typing the labels twice. If a solution to arbitrary values requires typing the values twice then I don't consider very usable.
Creating your own enum structure seems promising. But the question is:
Which VBA data-structure will give you IntelliSense for items?
Type, Enum, Class, Module... aren't data-structures. Array, Collection, and Dictionary don't give IntelliSense for items. If we can find a data-structure will give you IntelliSense for items, then we have a viable solution to this question. I've read XML might help here.
The easiest way to look this up is by utilizing the Object Browser built into the VBA editor. If the enum is user-defined, you will need to execute the code in the VBA editor window that contains the enum to load it into memory, then you should be able to view it in the Object Browser by going to View -> Object Browser or by pressing F2. Once opened, you can view all of the enums and their constant values.
If the enum is built-in (not user-defined), you will need to look up the name of the enum in the Object Browser in order to obtain its values. Generally, these are prefixed with either Mso (Microsoft Office), Xl (only for Excel), or Vb (Visual Basic). For instance:
Mso:
Xl:
Vb:
This is easy if you use the Enum Builder in Code VBA (image below):
Give enum name and values,
Check Enum_ToString which adds code returning the enum value name string for a given enum value,
Check Declare Enum with First and Last to have these attributes added to the enum ... and press OK which inserts the code.
Now in the Immediate Window insert the single line block of code
For i = Fruit.[_First] To Fruit.[_Last]: ?Fruit_ToString(cint(i)): Next
When [Enter] returns the required list.
I realized that in some cases the code was returning the "End Enum" statement if I supplied a value 1 higher than the last enumeration member, so I fixed the code for that. Here is the latest code, including making it work with Access or Excel:
'---------------------------------------------------------------------------------------
' Procedure : CodeInfo
'
' Author : RMittelman#gmail.com
'
' Purpose : Searches a module for enumerations & constants
'
' History : 11/13/2022 Original version
' 11/14/2022 Added feature to list enums in the module
' 11/14/2022 Added feature to list constants inn the module
' 11/15/2022 Fixed error returning "End Enum" statement
'
' Parameters :
'
' CodeType : A CodeInfoEnum member indicating Enums or Constants
'
' ModuleName : Optional. Name of module containing ItemName
' If missing, defaults to the module this function is called from
'
' ItemName : Optional. Name of the enumeration to examine
' If "?" or missing, returns a list of enumerations in the module
'
' EnumValue : optional. Value of the enumeration member wanted
' If missing, defaults to 0
' Ignored if CodType is not ciEnums
' Ignored if ItemName is missing or "?"
'
' Returns : - The text value of the enumeration value supplied; or
' - A list of enumeration names in the module; or
' - A list of constant names in the module
'
' Notes : Only searches in the module's Declarations section
'
'---------------------------------------------------------------------------------------
'
Public Function CodeInfo(CodeType As CodeInfoEnum, Optional ModuleName As Variant, Optional ItemName As String = "?", Optional EnumValueWanted As Variant) As String
Dim compMod As Object
Dim modLines As Long
Dim procStart As Long
Dim procLines As Long
Dim idx As Long
Dim codeText As String
Dim foundItem As Boolean
Dim foundMember As Boolean
Dim tempVal As Variant
Dim enumVal As Long
CodeInfo = ""
If IsMissing(ModuleName) Then ModuleName = Application.VBE.ActiveCodePane.CodeModule
If ModuleName <> "" Then
Set compMod = Application.VBE.ActiveVBProject.VBComponents(ModuleName).CodeModule
With compMod
' get declaration code
modLines = .CountOfLines
procStart = 1
procLines = .CountOfDeclarationLines
' search code text for enumeration(s)
idx = 0
foundItem = False
Do While (Not foundItem) And (idx <= procLines)
idx = idx + 1
codeText = .Lines(idx, 1)
' if ItemName is "?", build list of all desired items
If ItemName = "?" Then
Select Case CodeType
Case CodeInfoEnum.ciEnums
If codeText Like "*Enum *" Then
tempVal = Trim$(Mid$(codeText, InStr(1, codeText, "Enum", vbTextCompare) + 4))
CodeInfo = CodeInfo & "," & tempVal
End If
Case CodeInfoEnum.ciConstants
If codeText Like "*Const *" Then
tempVal = Mid$(codeText, InStr(1, codeText, "Const", vbTextCompare) + 6)
tempVal = Trim$(Left$(tempVal, InStr(1, tempVal, " ")))
CodeInfo = CodeInfo & "," & tempVal
End If
End Select
' otherwise, just see if we can find ItemName wanted
Else
foundItem = codeText Like "*Enum " & ItemName
End If
Loop
' if a specific Enum is found, look for the value wanted
If foundItem Then
enumVal = 0
foundMember = False
codeText = ""
Do While (Not foundMember) And (idx <= procLines) And (Not codeText Like "*End Enum")
idx = idx + 1
codeText = .Lines(idx, 1)
' don't process the "End Enum" statement
If Not codeText Like "*End Enum" Then
' reset the next enum value if the member has a specific value
If codeText Like "*=*" Then
tempVal = Trim$(Split(codeText, "=")(1))
If IsNumeric(tempVal) Then enumVal = CLng(tempVal)
End If
If enumVal = EnumValueWanted Then
CodeInfo = Trim$(Split(codeText, "=")(0))
foundMember = True
End If
End If
enumVal = enumVal + 1
Loop
End If
End With
If CodeInfo Like ",*" Then CodeInfo = Mid$(CodeInfo, 2)
End If
Set compMod = Nothing
End Function
This is more an observation than a real question: MS-Access (and VBA in general) is desperately missing a tool where error handling code can be generated automatically, and where the line number can be displayed when an error occurs. Did you find a solution? What is it? I just realized how many hundreds of hours I spared since I found the right answer to this basic problem a few years ago, and I'd like to see what are your ideas and solutions on this very important issue.
What about using "Erl", it will display the last label before the error (e.g., 10, 20, or 30)?
Private Sub mySUB()
On Error GoTo Err_mySUB
10:
Dim stDocName As String
Dim stLinkCriteria As String
20:
stDocName = "MyDoc"
30:
DoCmd.openform stDocName, acFormDS, , stLinkCriteria
Exit_mySUB:
Exit Sub
Err_mySUB:
MsgBox Err.Number & ": " & Err.Description & " (" & Erl & ")"
Resume Exit_mySUB
End Sub
My solution is the following:
install MZ-Tools, a very interesting add-on for VBA. No they did not pay me to write this. Version 3 was free, but since version 8.0, the add-in is commercially sold.
program a standard error handler code such as this one (see MZ-Tools menu/Options/Error handler):
On Error GoTo {PROCEDURE_NAME}_Error
{PROCEDURE_BODY}
On Error GoTo 0
Exit {PROCEDURE_TYPE}
{PROCEDURE_NAME}_Error:
debug.print "#" & Err.Number, Err.description, "l#" & erl, "{PROCEDURE_NAME}", "{MODULE_NAME}"
This standard error code can be then automatically added to all of your procs and function by clicking on the corresponding button in the MZ-Tools menu. You'll notice that we refer here to a hidden and undocumented function in the VBA standard library, 'Erl', which stands for 'error line'. You got it! If you ask MZ-Tools to automatically number your lines of code, 'Erl' will then give you the number of the line where the error occured. You will have a complete description of the error in your immediate window, such as:
#91, Object variable or With block variable not set, l# 30, addNewField, Utilities
Of course, once you realize the interest of the system, you can think of a more sophisticated error handler, that will not only display the data in the debug window but will also:
display it as a message on the screen
Automatically insert a line in an error log file with the description of the error or
if you are working with Access or if you are connected to a database, automatically add a record to a Tbl_Error table!
meaning that each error generated at the user level can be stored either in a file or a table, somewhere on the machine or the network. Are we talking about building an automated error reporting system working with VBA?
Well there are a couple of tools that will do what you ask MZ Tools and FMS Inc come to mind.
Basically they involve adding an:
On Error GoTo ErrorHandler
to the top of each proc
and at the end they put an:
ErrorHandler:
Call MyErrorhandler Err.Number, Err.Description, Err.LineNumber
label with usually a call to a global error handler where you can display and log custom error messages
You can always roll your own tool like Chip Pearson did. VBA can actually access it's own IDE via the Microsoft Visual Basic for Applications Extensibility 5.3 Library. I've written a few class modules that make it easier to work with myself. They can be found on Code Review SE.
I use it to insert On Error GoTo ErrHandler statements and the appropriate labels and constants related to my error handling schema. I also use it to sync up the constants with the actual procedure names (if the function names should happen to change).
There is no need to buy tools DJ mentioned. Here is my code for free:
Public Sub InsertErrHandling(modName As String)
Dim Component As Object
Dim Name As String
Dim Kind As Long
Dim FirstLine As Long
Dim ProcLinesCount As Long
Dim Declaration As String
Dim ProcedureType As String
Dim Index As Long, i As Long
Dim LastLine As Long
Dim StartLines As Collection, LastLines As Collection, ProcNames As Collection, ProcedureTypes As Collection
Dim gotoErr As Boolean
Kind = 0
Set StartLines = New Collection
Set LastLines = New Collection
Set ProcNames = New Collection
Set ProcedureTypes = New Collection
Set Component = Application.VBE.ActiveVBProject.VBComponents(modName)
With Component.CodeModule
' Remove empty lines on the end of the code
For i = .CountOfLines To 1 Step -1
If Component.CodeModule.Lines(i, 1) = "" Then
Component.CodeModule.DeleteLines i, 1
Else
Exit For
End If
Next i
Index = .CountOfDeclarationLines + 1
Do While Index < .CountOfLines
gotoErr = False
Name = .ProcOfLine(Index, Kind)
FirstLine = .ProcBodyLine(Name, Kind)
ProcLinesCount = .ProcCountLines(Name, Kind)
Declaration = Trim(.Lines(FirstLine, 1))
LastLine = FirstLine + ProcLinesCount - 2
If InStr(1, Declaration, "Function ", vbBinaryCompare) > 0 Then
ProcedureType = "Function"
Else
ProcedureType = "Sub"
End If
Debug.Print Component.Name & "." & Name, "First: " & FirstLine, "Lines:" & ProcLinesCount, "Last: " & LastLine, Declaration
Debug.Print "Declaration: " & Component.CodeModule.Lines(FirstLine, 1), FirstLine
Debug.Print "Closing Proc: " & Component.CodeModule.Lines(LastLine, 1), LastLine
' do not insert error handling if there is one already:
For i = FirstLine To LastLine Step 1
If Component.CodeModule.Lines(i, 1) Like "*On Error*" Then
gotoErr = True
Exit For
End If
Next i
If Not gotoErr Then
StartLines.Add FirstLine
LastLines.Add LastLine
ProcNames.Add Name
ProcedureTypes.Add ProcedureType
End If
Index = FirstLine + ProcLinesCount + 1
Loop
For i = LastLines.Count To 1 Step -1
If Not (Component.CodeModule.Lines(StartLines.Item(i) + 1, 1) Like "*On Error GoTo *") Then
Component.CodeModule.InsertLines LastLines.Item(i), "ExitProc_:"
Component.CodeModule.InsertLines LastLines.Item(i) + 1, " Exit " & ProcedureTypes.Item(i)
Component.CodeModule.InsertLines LastLines.Item(i) + 2, "ErrHandler_:"
Component.CodeModule.InsertLines LastLines.Item(i) + 3, " Call LogError(Err, Me.Name, """ & ProcNames.Item(i) & """)"
Component.CodeModule.InsertLines LastLines.Item(i) + 4, " Resume ExitProc_"
Component.CodeModule.InsertLines LastLines.Item(i) + 5, " Resume ' use for debugging"
Component.CodeModule.InsertLines StartLines.Item(i) + 1, " On Error GoTo ErrHandler_"
End If
Next i
End With
End Sub
Put it in a module and call it from Immediate Window every time you add new function or sub to a form or module like this (Form1 is name of your form):
MyModule.InsertErrHandling "Form_Form1"
It will alter your ode in Form1 from this:
Private Function CloseIt()
DoCmd.Close acForm, Me.Name
End Function
to this:
Private Function CloseIt()
On Error GoTo ErrHandler_
DoCmd.Close acForm, Me.Name
ExitProc_:
Exit Function
ErrHandler_:
Call LogError(Err, Me.Name, "CloseIt")
Resume ExitProc_
Resume ' use for debugging
End Function
Create now in a module a Sub which will display the error dialog and where you can add inserting the error to a text file or database:
Public Sub LogError(ByVal objError As ErrObject, moduleName As String, Optional procName As String = "")
On Error GoTo ErrHandler_
Dim sql As String
MsgBox "Error " & Err.Number & " Module " & moduleName & Switch(procName <> "", " in " & procName) & vbCrLf & " (" & Err.Description & ") ", vbCritical
Exit_:
Exit Sub
ErrHandler_:
MsgBox "Error in LogError procedure " & Err.Number & ", " & Err.Description
Resume Exit_
Resume ' use for debugging
End Sub
This code does not enter error handling if there is already "On Error" statement in a proc.
Love it Vlado!
I realize this is an old post, but I grabbed it and gave it a try, but I ran into a number of issues with it, which I managed to fix. Here's the code with fixes:
First of course, be sure to add the "Microsoft Visual Basic for Applications Extensibility 5.3" library to your project, and add these subroutines / modules to your project as well.
First, the module with the main code was named "modVBAChecks", and contained the following two subroutines:
To go through all modules (behind forms, sheets, the workbook, and classes as well, though not ActiveX Designers):
Sub AddErrorHandlingToAllProcs()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim lCtr As Long
StartNewWorksheetLog
Set VBProj = Workbooks("LabViewAnalysisTools.xla").VBProject
For Each VBComp In VBProj.VBComponents
If VBComp.Type <> vbext_ct_ActiveXDesigner Then
If VBComp.Name <> "modVBAChecks" And VBComp.Name <> "modLogToWorksheet" Then
AddToWksLog "============ Looking at Module """ & VBComp.Name & """"
'InsertErrHandling VBComp.Name
AddToWksLog
AddToWksLog
End If
End If
Next
MsgBox "Done!", vbSystemModal
End Sub
Then the modified version of your code (including a suggested change by
Rafał B.):
Public Sub InsertErrHandling(modsProcName As String)
' Modified from code submitted to StackOverflow by user Vlado, originally found
' here: https://stackoverflow.com/questions/357822/automatically-generating-handling-of-issues
Dim vbcmA As VBIDE.CodeModule
Dim ProcKind As VBIDE.vbext_ProcKind
Dim LineProcKind As VBIDE.vbext_ProcKind
Dim sProcName As String
Dim sLineProcName As String
Dim lFirstLine As Long
Dim lProcLinesCount As Long
Dim lLastLine As Long
Dim sDeclaration As String
Dim sProcType As String
Dim lLine As Long, lLine2 As Long
Dim sLine As String
Dim lcStartLines As Collection, lcLastlines As Collection, scProcsProcNames As Collection, scProcTypes As Collection
Dim bAddHandler As Boolean
Dim lLinesAbove As Long
Set lcStartLines = New Collection
Set lcLastlines = New Collection
Set scProcsProcNames = New Collection
Set scProcTypes = New Collection
Set vbcmA = Application.VBE.ActiveVBProject.VBComponents(modsProcName).CodeModule
' Remove empty lines on the end of the module. Cleanup, not error handling.
lLine = vbcmA.CountOfLines
If lLine = 0 Then Exit Sub ' Nothing to do!
Do
If Trim(vbcmA.Lines(lLine, 1)) <> "" Then Exit Do
vbcmA.DeleteLines lLine, 1
lLine = lLine - 1
Loop
lLine = vbcmA.CountOfDeclarationLines + 1
Do While lLine < vbcmA.CountOfLines
bAddHandler = False
' NOTE: ProcKind is RETRUNED from ProcOfLine!
sProcName = vbcmA.ProcOfLine(lLine, ProcKind)
' Fortunately ProcBodyLine ALWAYS returns the first line of the procedure declaration!
lFirstLine = vbcmA.ProcBodyLine(sProcName, ProcKind)
sDeclaration = Trim(vbcmA.Lines(lFirstLine, 1))
Select Case ProcKind
Case VBIDE.vbext_ProcKind.vbext_pk_Proc
If sDeclaration Like "*Function *" Then
sProcType = "Function"
ElseIf sDeclaration Like "*Sub *" Then
sProcType = "Sub"
End If
Case VBIDE.vbext_ProcKind.vbext_pk_Get, VBIDE.vbext_ProcKind.vbext_pk_Let, VBIDE.vbext_ProcKind.vbext_pk_Set
sProcType = "Property"
End Select
' The "lProcLinesCount" function will sometimes return ROWS ABOVE
' the procedure, possibly up until the prior procedure,
' and often rows BELOW the procedure as well!!!
lProcLinesCount = vbcmA.ProcCountLines(sProcName, ProcKind)
lLinesAbove = 0
lLine2 = lFirstLine - 1
If lLine2 > 0 Then
Do
sLineProcName = vbcmA.ProcOfLine(lLine2, LineProcKind)
If Not (sLineProcName = sProcName And LineProcKind = ProcKind) Then Exit Do
lLinesAbove = lLinesAbove + 1
lLine2 = lLine2 - 1
If lLine2 = 0 Then Exit Do
Loop
End If
lLastLine = lFirstLine + lProcLinesCount - lLinesAbove - 1
' Now need to trim off any follower lines!
Do
sLine = Trim(vbcmA.Lines(lLastLine, 1))
If sLine = "End " & sProcType Or sLine Like "End " & sProcType & " '*" Then Exit Do
lLastLine = lLastLine - 1
Loop
AddToWksLog modsProcName & "." & sProcName, "First: " & lFirstLine, "Lines:" & lProcLinesCount, "Last: " & lLastLine
AddToWksLog "sDeclaration: " & vbcmA.Lines(lFirstLine, 1), lFirstLine
AddToWksLog "Closing Proc: " & vbcmA.Lines(lLastLine, 1), lLastLine
If lLastLine - lFirstLine < 8 Then
AddToWksLog " --------------- Too Short to bother!"
Else
bAddHandler = True
' do not insert error handling if there is one already:
For lLine2 = lFirstLine To lLastLine Step 1
If vbcmA.Lines(lLine2, 1) Like "*On Error GoTo *" And Not vbcmA.Lines(lLine2, 1) Like "*On Error GoTo 0" Then
bAddHandler = False
Exit For
End If
Next lLine2
If bAddHandler Then
lcStartLines.Add lFirstLine
lcLastlines.Add lLastLine
scProcsProcNames.Add sProcName
scProcTypes.Add sProcType
End If
End If
AddToWksLog
lLine = lFirstLine + lProcLinesCount + 1
Loop
For lLine = lcLastlines.Count To 1 Step -1
vbcmA.InsertLines lcLastlines.Item(lLine), "ExitProc:"
vbcmA.InsertLines lcLastlines.Item(lLine) + 1, " Exit " & scProcTypes.Item(lLine)
vbcmA.InsertLines lcLastlines.Item(lLine) + 2, "ErrHandler:"
vbcmA.InsertLines lcLastlines.Item(lLine) + 3, " ShowErrorMsg Err, """ & scProcsProcNames.Item(lLine) & """, """ & modsProcName & """"
vbcmA.InsertLines lcLastlines.Item(lLine) + 4, " Resume ExitProc"
' Now replace any "On Error Goto 0" lines with "IF ErrorTrapping Then On Error Goto ErrHandler"
For lLine2 = lcStartLines(lLine) To lcLastlines(lLine)
sLine = vbcmA.Lines(lLine2, 1)
If sLine Like "On Error GoTo 0" Then
vbcmA.ReplaceLine lLine2, Replace(sLine, "On Error Goto 0", "IF ErrorTrapping Then On Error Goto ErrHandler")
End If
Next
lLine2 = lcStartLines.Item(lLine)
Do
sLine = vbcmA.Lines(lLine2, 1)
If Not sLine Like "* _" Then Exit Do
lLine2 = lLine2 + 1
Loop
vbcmA.InsertLines lLine2 + 1, " If ErrorTrapping Then On Error GoTo ErrHandler"
Next lLine
End Sub
And rather than pushing things to the Immediate window I used subroutines in a module I named "modLogToWorksheet", the full module being here:
Option Explicit
Private wksLog As Worksheet
Private lRow As Long
Public Sub StartNewWorksheetLog()
Dim bNewSheet As Boolean
bNewSheet = True
If ActiveSheet.Type = xlWorksheet Then
Set wksLog = ActiveSheet
bNewSheet = Not (wksLog.UsedRange.Cells.Count = 1 And wksLog.Range("A1").Formula = "")
End If
If bNewSheet Then Set wksLog = ActiveWorkbook.Worksheets.Add
lRow = 1
End Sub
Public Sub AddToWksLog(ParamArray sMsg() As Variant)
Dim lCol As Long
If wksLog Is Nothing Or lRow = 0 Then StartNewWorksheetLog
If Not (IsNull(sMsg)) Then
For lCol = 0 To UBound(sMsg)
If sMsg(lCol) <> "" Then wksLog.Cells(lRow, lCol + 1).Value = "'" & sMsg(lCol)
Next
End If
lRow = lRow + 1
End Sub
And finally, here's my Error Dialog generator:
Public Sub ShowErrorMsg(errThis As ErrObject, strSubName As String, strModName As String _
, Optional vbMBStyle As VbMsgBoxStyle = vbCritical, Optional sTitle As String = APP_TITLE)
If errThis.Number <> 0 Then
MsgBox "An Error Has Occurred in the Add-in. Please inform " & ADMINS & " of this problem." _
& vbCrLf & vbCrLf _
& "Error #: " & errThis.Number & vbCrLf _
& "Description: " & " " & errThis.Description & vbCrLf _
& "Subroutine: " & " " & strSubName & vbCrLf _
& "Module: " & " " & strModName & vbCrLf _
& "Source: " & " " & errThis.Source & vbCrLf & vbCrLf _
& "Click OK to continue.", vbMBStyle Or vbSystemModal, sTitle
End If
End Sub
Hope future users find it useful!