|
楼主 |
发表于 2017-8-16 08:51
|
显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
看来这个功能大家用的少,可有可无,不怎么关注。
现在只好自己做一个这样的函数了。
代码如下,分享给大家,请点评!
- Public Function NumArr(ByVal NumStr As String) As Variant
- '使用此函数前,应提示或说明使用方法、要求;
- '功能:输入字符串"1,3,5-8",输出数组Array(1,3,5,6,7,8)
- '参数格式:用正整数、逗号、减号组成的字符串,不含其它字符;
- '1≤整数≤1048576,逗号(,)表示分隔,减号(-)表示整数连续。
- Dim i As Long, j As Long, L As Long, R As Long, V As Variant
- NumStr = Replace(Replace(Replace(NumStr, vbCr, ""), vbLf, ""), " ", "")
- NumStr = Replace(Replace(Replace(NumStr, ",", ","), "-", "-"), " ", "")
- For i = 1 To Len(NumStr)
- If Mid(NumStr, i, 2) = ",," Then Mid(NumStr, i, 2) = " ,"
- If Mid(NumStr, i, 2) = "--" Then Mid(NumStr, i, 2) = " -"
- Next i: NumStr = Replace(NumStr, " ", "")
- If Left(NumStr, 1) = "," Or Left(NumStr, 1) = "-" Then NumStr = Right(NumStr, Len(NumStr) - 1)
- If Right(NumStr, 1) = "," Or Right(NumStr, 1) = "-" Then NumStr = Left(NumStr, Len(NumStr) - 1)
- NumArr = Array(0): If NumStr = "" Then Exit Function
- V = Split(Replace(NumStr, "-", ","), ",")
- For i = LBound(V) To UBound(V)
- If IsNumeric(V(i)) Then
- If V(i) < 1 Or V(i) > 1048576 Then MsgBox "转换的数字超出限制范围!": Exit Function
- If CLng(V(i)) <> CDbl(V(i)) Then MsgBox "转换的数字含有小数!": Exit Function
- Else: MsgBox "转换的数字不合规范!": Exit Function
- End If: Next i: V = Split(NumStr, ","): NumStr = ""
- For i = LBound(V) To UBound(V)
- If IsNumeric(V(i)) Then
- NumStr = NumStr & V(i) & ","
- Else: L = InStr(V(i), "-"): R = Len(V(i))
- If L > 1 And L < R And Len(Replace(V(i), "-", "")) = R - 1 Then
- R = CLng(Right(V(i), R - L)): L = CLng(Left(V(i), L - 1))
- If L > R Then j = L: L = R: R = j '在L变动前先R赋值
- For j = L To R: NumStr = NumStr & j & ",": Next j
- Else: MsgBox "输入的字符串不合规范!": Exit Function
- End If: End If: Next i: NumArr = Split(Left(NumStr, Len(NumStr) - 1), ",")
- End Function
复制代码
开始以为这个函数的代码很简单,可在做的过程中发现也不简单。
主要问题是:无法规范输入的字符串。
当任意的字符串进来后,就要对其进行规整、判断。
函数的大部分代码(约3/4)都是在处理这个问题。 |
|