簡體   English   中英

Excel VBA:如何將范圍轉換為數字並在列表中獲取 output

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM