Search code examples
vbaexceljump-table

Can I create a Jump table in VBA for Excel?


I wrote a simple translator / parser to process an EDI (830) document using multiple Select Case statements to determine the code to be executed. I’m opening a file in binary mode and splitting the document into individual lines, then each line is split into the various elements where the first element of every line has a unique segment identifier.

My code works perfectly as written. However, Select Case requires checking every Case until a match is found or the Case Else is executed. I’ve sequenced the Case statements in such a manner that the segments that appear most frequently (as in the case of loops), are placed first to minimize the number of "checks before code is actually executed.

Rather than using multiple Select Cases, I would prefer to determine an index for the segment identifier and simply call the appropriate routine using that index. I’ve used jump tables in C and Assembler and anticipated similar functionality may be possible in VBA.


Solution

  • You can do jump tables in VBA by using the Application.Run method to call the appropriate routine by name. The following code demonstrates how it works:

    Public Sub JumpTableDemo()
    
      Dim avarIdentifiers() As Variant
      avarIdentifiers = Array("Segment1", "Segment2")
      Dim varIdentifier As Variant
      For Each varIdentifier In avarIdentifiers
        Run "Do_" & varIdentifier
      Next varIdentifier
    
    End Sub
    
    Public Sub Do_Segment1()
      Debug.Print "Segment1"
    End Sub
    
    Public Sub Do_Segment2()
      Debug.Print "Segment2"
    End Sub