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

js0*_*823 3 excel vba excel-2007 excel-vba

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

1, 1
1, 2
1, 3
Run Code Online (Sandbox Code Playgroud)

数字简单地用逗号分隔.

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

非常感谢你.

Bru*_* 82 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
Run Code Online (Sandbox Code Playgroud)

非VBA解决方案:

在单元格B1中插入以下公式:
= VALUE(LEFT(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)

  • 有点无关,但你确实知道lngLeft和lngRight在这里被声明为变量,对吧?VBA不允许您像在代码中那样声明变量.:) (2认同)