这是我前一段时间收到的另一个答案。
Turn a value range in a cell into a comma separated list
以下代码很棒,但现在我希望它也能输出4位数的每个数字。因此,如果我得到1,2,3的回报,我希望它返回为“0001,0002,0003”。
Function NumRange(v)
Dim arrC, arr, x As Long, rv As String, sep As String, e
arrC = Split(v, ",")
rv = ""
For Each e In arrC
If InStr(e, "-") Then
arr = Split(e, "-")
arr(0) = Trim(arr(0))
arr(1) = Trim(arr(1))
If IsNumeric(arr(0)) And IsNumeric(arr(1)) Then
For x = CLng(arr(0)) To CLng(arr(1))
rv = rv & sep & x
sep = ","
Next x
End If
ElseIf IsNumeric(e) Then
rv = rv & sep & CLng(e)
sep = ","
End If
Next e
NumRange = rv
End Function
答案 0 :(得分:1)
这是一种蛮力,但您可以使用LPAD
或PadLeft()
函数/方法的这种方便翻译的变体:
Any method equivalent to PadLeft/PadRight?
Function NumRange(v)
Dim arrC, arr, x As Long, rv As String, sep As String, e
arrC = Split(v, ",")
rv = ""
For Each e In arrC
If InStr(e, "-") Then
arr = Split(e, "-")
arr(0) = Trim(arr(0))
arr(1) = Trim(arr(1))
If IsNumeric(arr(0)) And IsNumeric(arr(1)) Then
For x = CLng(arr(0)) To CLng(arr(1))
rv = rv & sep & Right("0000" & x, 4)
sep = ","
Next x
End If
ElseIf IsNumeric(e) Then
rv = rv & sep & Right("0000" & e, 4)
sep = ","
End If
Next e
NumRange = rv
End Function
现在是一个包含公式的单元格:
=NumRange("1-10")
将包含:
001,002,003,004,005,006,007,008,009,010
答案 1 :(得分:0)
这是一个格式化整数的简单函数:
Function PadLeft(Value, FillerChar, Size)
PadLeft = Right(String(Size, FillerChar) + cStr(Value), Size)
End Function
使用示例
Dim StringToPrint = PadLeft(7, "0", 4)
' StringToPrint value is now "0007"