如何在VBscript中创建带填充零的标记

时间:2014-10-02 14:26:07

标签: vbscript

我正在尝试使用以下代码来填充带有标记值的列表框。在for循环中,我创建了要插入列表框的标记。我的问题是如何用零填充标签名称编号?例如ValveName001 - ValveName120?

    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

2 个答案:

答案 0 :(得分:1)

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

包含填充并仅获取所需的字符

答案 1 :(得分: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

改进功能(从@Bond&#39评论中被盗):

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