Excel VBA:如何从字符串中提取数字?

时间:2011-11-11 21:21:33

标签: excel-vba excel-2007 vba excel

我想从字符串中提取数字。这些字符串就像这样写在每个单元格中。

1, 1
1, 2
1, 3

数字简单地用逗号分隔。

如何在Excel VBA中从中提取数字?

非常感谢。

3 个答案:

答案 0 :(得分:6)

如果我的问题正确,则单元格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)

答案 1 :(得分:4)

* 假设期望的结果是11,12和13.

以下内容已编写为函数,但可以轻松更改为子例程。我不想进入设定范围,只关注功能。

如果您的数据只是用逗号和空格分隔的数字,那么只需使用replace:

Function ExtractNumber(ByVal text As String) As String

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

End Function

如果你想要一个更复杂的功能,提取所有数字而不管字符串中的其他内容,这里是我的RegexExtract函数。默认情况下,我将其设置为以逗号分隔所有捕获,但您可以将其指定为无:

=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

答案 2 :(得分:1)

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