1

I need to left pad an alphanumeric string with 0s to make the numeric part of the string a total of 5 digits.

For eg:

1843Q -> 01843Q

691B -> 00691B

My problem arises when special characters are introduced in the string.

For eg:

4361G-3 -> 04361G-3

What my code does:

4361G-3 -> 04361G-

My code is

    str1 = "-*"
    str = Job
    For i = 1 To Len(str)
     chr = Mid(str, i, 1)
     result = str Like str1
     If IsNumeric(chr) Then
      If result = False Then
       strg = strg & chr
      End If
     ElseIf isalpha(chr) Then
      If result = False Then
       strg2 = strg2 & chr
     End If
     ElseIf chr = "-" Then
      strg3 = strg3 & chr
     ElseIf strg3 Like "-" Then
      strg3 = strg3 & chr
     ElseIf strg3 Like "[-]*" Then
      strg3 = strg3 & chr
     End If
Next i
strg = Format(strg, "00000") & strg2 & strg3
Job = strg

How do I need to change this to get what I want?

4

1 回答 1

0

我认为有一种更简单的方法来编写你的函数。这是一个即时窗口会话,演示了您可以使用的 VBA 功能。

strFoo = "1843Q"
? Val(strFoo)
 1843 
? CStr(Val(strFoo))
1843
? Len(CStr(Val(strFoo)))
 4 
? Mid(strFoo, Len(CStr(Val(strFoo))) + 1)
Q
? Right(String(5, "0") & CStr(Val(strFoo)), 5)
01843
? Right(String(5, "0") & CStr(Val(strFoo)), 5) & _
    Mid(strFoo, Len(CStr(Val(strFoo))) + 1)
01843Q

' test with another value ...
strFoo = "4361G-3"
? Right(String(5, "0") & CStr(Val(strFoo)), 5) & _
    Mid(strFoo, Len(CStr(Val(strFoo))) + 1)
04361G-3

我懒得实际编写函数。如果您愿意,请自己尝试一下。如果您遇到麻烦,请向我们展示您的代码、错误消息,并指出哪一行触发了错误。

于 2013-08-29T17:23:43.523 回答