2014-10-02 37 views
1

我正嘗試使用以下代碼來填充帶有標籤值的列表框。在for循環中,我創建要插入列表框的標記。我的問題是如何使用零填充標籤名稱編號?例如ValveName001 - ValveName120?如何在VBscript中創建帶填充零的標籤

Dim i, listbox1, listbox2, tag 
    Set listbox1 = ScreenItems("ListBoxValveName") 

    For i = 1 To 120 
     tag = "ValveName" & "##" & i & "" 
     listbox1.SelectedIndex = i 
     Set listbox1.SelectedText = SmartTags.Item(tag) 
    Next 

回答

1
tag = "ValveName" & Right("00" & i, 3) 

包括填充,只得到所需要的字符

1

或投資於一個更普遍適用的(更安全)功能。爲了讓你開始:

Option Explicit 

' pad (stringable) value v on the left to width w using fill character f 
Function padLeft(v, w, f) 
    If Len(v) < w Then 
    padLeft = Right(String(w, f) & v, w) 
    Else 
    padLeft = v 
    End If 
End Function 

Dim v : v = "1" 
Dim w : w = 3 
Dim f : f = "0" 
WScript.Echo v, w, f, padLeft(v, w, f) 

輸出:

cscript 26163030.vbs 
1 3 0 001 

改進功能(來自@被盜邦德的評論):

Function padLeft(v, w, f) 
    Dim l : l = Len(v) 
    If l < w Then 
    padLeft = String(w - l, f) & v 
    Else 
    padLeft = v 
    End If 
End Function 
+1

或'padLeft =字符串(W - 萊恩(V), f)&v',它交換'Len()'調用的'Right()'調用。 – Bond 2014-10-02 15:31:05