Search code examples
vbamap-basic

Label a set of objects with (A->Z,AA->ZZ, AAA->ZZZ) in VBA


I have a set which has an unknown number of objects. I want to associate a label to each one of these objects. Instead of labeling each object with a number I want to label them with letters.

For example the first object would be labeled A the second B and so on.

When I get to Z, the next object would be labeled AA

AZ? then BA, BB, BC.

ZZ? then AAA, AAB, AAC and so on.

I'm working using Mapbasic (similar to VBA), but I can't seem to wrap my head around a dynamic solution. My solution assumes that there will be a max number of objects that the set may or may not exceed.

label = pos1 & pos2

Once pos2 reaches ASCII "Z" then pos1 will be "A" and pos2 will be "A". However, if there is another object after "ZZ" this will fail.

How do I overcome this static solution?


Solution

  • Basically what I needed was a Base 26 Counter. The function takes a parameter like "A" or "AAA" and determines the next letter in the sequence.

    Function IncrementAlpha(ByVal alpha As String) As String
    
    Dim N As Integer
    Dim num As Integer
    Dim str As String
    
    Do While Len(alpha)
        num = num * 26 + (Asc(alpha) - Asc("A") + 1)
        alpha = Mid$(alpha, 2,1)
    Loop
    N = num + 1
    
    Do While N > 0
        str = Chr$(Asc("A") + (N - 1) Mod 26) & str
        N = (N - 1) \ 26
    Loop
    IncrementAlpha = str
    End Function