[英]Excel VBA: How to convert ranges to numbers and get output in a column as list
我需要将范围转换为数字列表。 输入中的所有字母都需要省略,只考虑整数、逗号和破折号。 output列表需要5位,小于5位需要加前缀“0”。
示例:在A列中输入“Group 10,20-22,31”,“Group 00022-00024”和“Group 35”需要转换为B列中的output列表(如下所述)。
| Column A [INPUT] | Column B [OUTPUT] |
Row 1 Group 10,20-22,31 00010
Row 2 Group 00022-00024 00020
Row 3 Group 35 00021
Row 4 00022
Row 5 00023
Row 6 00024
Row 7 00031
Row 8 00035
我从以下链接中提到的 function 获得了帮助,但只能扩展第一个和最后一个整数之间的范围,但这也包括介于两者之间的数字,这些数字在输入中不可用。 Excel:将范围转换为数字
你能帮忙修改上面链接中提到的function吗? 或者建议一个新的 function?
我是 Stackoverflow 和 VBA 的新手。 为输入的变化道歉,希望现在很清楚。
由于您在链接中引用了 function,因此我将在我提出的解决方案中重用它。
Function SplitStr(xx As String) As String
valu = Split(xx, ",")
Stri = ""
For Each nn In valu
If InStr(1, nn, "-") > 0 Then
For i = Left(nn, InStr(1, nn, "-") - 1) To Right(nn, Len(nn) - InStr(1, nn, "-"))
If Stri <> "" Then
Stri = Stri & "," & i
Else
Stri = i
End If
Next
Else
If Stri <> "" Then
Stri = Stri & "," & Trim(nn)
Else
Stri = Trim(nn)
End If
End If
Next
SplitStr = Stri
End Function
这是我的解决方案,请参阅评论以获取解释:
Sub Explode()
Dim srcRange As Range
Dim arrValue() As String
Dim currentRow As Long, i As Integer
' Take the string result of the function SplitStr and assign it to an array
arrValue = Split(SplitStr(ActiveSheet.Range("A1").Value), ",")
' Clear B column
ActiveSheet.Range("B:B").Clear
' B row counter
currentRow = 1
' Loop through each values
For i = arrValue(LBound(arrValue())) To arrValue(UBound(arrValue()))
' Assign the value to B column
ActiveSheet.Range("B" & currentRow).Value = i
'advance to next "B" row
currentRow = currentRow + 1
Next i
End Sub
运行 Explode() Sub 并查看 B 列填充了 Range("A1") 中指示的值范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.