简体   繁体   中英

VBA Excel array error

I have to generate an ID using a macro and I'm facing some problems when there are 8 numeric values required. The ID has to include numeric values for the 1st-8th charactera and the 9th must be alphabetic. From the 10th character onwards it has to be spaces. These are my codes and I'm certain that there are no issues with the formula

Function GenerateRB()

strLastCharSelections = "X,W,M,L,K,J,E,D,C,B,A"

intNumber = GenerateRandomNumber(1000000, 9999999)

ReDim a(8)
For i = 1 To 8
a(i) = Mid(intNumber, i, 1)
Next

intTotal = a(1) * 9 + a(2) * 8 + a(3) * 7 + a(4) * 6 + a(5) * 5 + a(6) * 4 + a(7) * 3 + a(8) * 2


intRemainder = intTotal Mod 11

arrstrSplitLastCharSelections = Split(strLastCharSelections, ",")
strLastChar = arrstrSplitLastCharSelections(intRemainder)
GenerateRB = intNumber & strLastChar
End Function

The code works when its

    ReDim a(7)
For i = 1 To 7
a(i) = Mid(intNumber, i, 1)
Next

intTotal = a(1) * 9 + a(2) * 8 + a(3) * 7 + a(4) * 6 + a(5) * 5 + a(6) * 4 + a(7) * 3

Any help will be appreciated as I'm very new to this, Thank you!

I'm assuming that GenerateRandomnNumber will return a numeric in the specified range - in this case, a seven digit number between 1000000 and 9999999.

So when selecting the i th digit in the statement a(i) = Mid(intNumber, i, 1) , there are no issues when i is 1 to 7 - however, when it's 8 - there is no eighth digit, so the code will fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM