簡體   English   中英

Excel VBA:如何從字符串中提取數字?

[英]Excel VBA : How do I extract number from a string?

我想從字符串中提取數字。 字符串像這樣寫在每個單元格中。

1, 1
1, 2
1, 3

數字簡單地用逗號分隔。

如何在Excel VBA中從中提取數字?

非常感謝你。

如果我的問題正確,則單元格A1中的“1,1”,單元格A2中的“1,2”,單元格A3中的“1,3”。

如果您分別想要單元格B1,B2和B3中逗號之前的數字以及單元格C1,C2和C3中逗號之后的數字,則可以執行以下操作:

VBA解決方案:

Public Sub test()
    'the variables' declaration has been corrected, check 
    'the post's comments below to find out which correction were made
    Dim lngLeft as Long, lngRight as Long, lngCommaPos As Long
    Dim intI As Integer
    For intI = 1 To 3
        lngCommaPos = InStr(1, Range("A" & intI).Value, ",")
        lngLeft = Left(Range("A" & intI).Value, lngCommaPos - 1)
        lngRight = Right(Range("A" & intI).Value, Len(Range("A" & intI).Value) - lngCommaPos - 1)
        Range("B" & intI).Value = lngLeft
        Range("C" & intI).Value = lngRight
    Next intI
End Sub

非VBA解決方案:

在單元格B1中插入以下公式:
= VALUE(左(A1,FIND(“,”,A1)-1))

在單元格C1中插入以下公式:
= VALUE(右(A1,LEN(A1)-FIND(“,”,A1)-1))

將單元格B1和C1粘貼到單元格B2到C3中

如果你想在B和C列中有字符串(而不是有數字),你可以刪除VALUE函數,單元格B1和C1中的公式將是
= LEFT(A1,FIND( “”,A1)-1)
= RIGHT(A1,LEN(A1) -查找( “”,A1)-1)

* 假設期望的結果是11,12和13。

以下內容已編寫為函數,但可以輕松更改為子例程。 我不想進入設定范圍,只關注功能。

如果您的數據只是用逗號和空格分隔的數字,那么只需使用replace:

Function ExtractNumber(ByVal text As String) As String

ExtractNumber = Replace(text, ", ", "")

End Function

如果你想要一個更復雜的函數來提取所有數字而不管字符串中的其他內容 ,這里是我的RegexExtract函數。 默認情況下,我將其設置為以逗號分隔所有捕獲,但您可以將其指定為none:

=RegexExtract(A1, "(\d)", "")
  • (\\ d)表示捕獲任何數字0-9
  • 第三個參數是你如何將所有捕獲分開(如果有的話)

這是功能:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = ", ") As String

Application.ScreenUpdating = False
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
Dim i As Long, j As Long
Dim result As String

RE.Pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.Count - 1
    For j = 0 To allMatches.Item(j).submatches.Count - 1
        result = result & (seperator & allMatches.Item(i).submatches.Item(j))
    Next
Next

If Len(result) <> 0 Then
    result = Right$(result, Len(result) - Len(seperator))
End If

RegexExtract = result
Application.ScreenUpdating = True

End Function

如果你不想使用VBA,你也可以使用Text to Columns,請參閱: http//support.microsoft.com/kb/214261

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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