Pad Number String with Zeroes(在字符串左侧补0)

例如,在设计框架或写脚本的时候,总会碰见日期格式的问题,需要在不够十位的月份上补0,等等。。

实现方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 '*******************************************************************************
'Description : Pads a number with zeroes on the left, according to the expected maximum length of the numbers in the list. ' 

'Purpose : To keep a number list sorted properly, as with a file list (001, 002,..., 010, and not 1, 10, 11,..., 2, 20). ' 

'Arguments : intCurrentNum (the current number to be padded) 
            'intMaxNumInList (the top number in the list) 

'Note: The arguments are always taken in absolute values 

'Returns : The padded intCurrentNum (for example, If 1 and 9999 are sent to the function, the result will be 0001) ' 

'*******************************************************************************  
Public Function PadNumber(ByVal intCurrentNum, ByVal intMaxNumInList) 
   
'Validates the arguments - if invalid then it returns the value as is     
    If (Not IsNumeric(intCurrentNum) Or Not IsNumeric(intMaxNumInList)) Then         
        PadNumber = intCurrentNum         
        Exit Function     
    End If    
     
    If (Abs(intCurrentNum) >= Abs(intMaxNumInList)) Then         
        PadNumber = intCurrentNum         
        Exit Function     
    End If     
    
    PadNumber = String(len(CStr(Abs(intMaxNumInList)))-len(CStr(Abs(intCurrentNum))), "0") _  
                 & CStr(Abs(intCurrentNum)) 
                   
End Function 


'*******************************************************************************  
'Msgbox PadNumber(4, 34567)    'Returns 00004 
'Msgbox PadNumber(-4, 34567)   'Returns 00004  
'Msgbox PadNumber(4, -34567)   'Returns 00004 
'Msgbox PadNumber(34567, 4)    'Returns 34567 
'Msgbox PadNumber(4, 9)        'Returns 4 
'Msgbox PadNumber("Hello", 9999) 'Returns Hello

唐胡璐 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
分享创造价值,您的支持将鼓励我继续前行!