我想从字符串中提取数字。字符串在每个单元格中都是这样写的。
1, 1
1, 2
1, 3数字只用逗号分隔。
如何在Excel VBA中从它们中提取数字?
非常感谢。
发布于 2011-11-12 08:07:59
如果我没记错的话,单元格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(LEFT(A1,FIND(",",A1)-1))
在单元格C1中插入以下公式:
=(RIGHT(A1,LEN(A1)-FIND(",",A1)-1))
将单元格B1和C1粘贴到单元格B2到C3中
如果您希望在B和C列中包含字符串(而不是数字),则可以删除VALUE函数,单元格B1和C1中的公式将为
=LEFT(A1,FIND(",",A1)-1)
=RIGHT(A1,LEN(A1)-FIND(",",A1)-1)
发布于 2011-11-12 09:10:47
*假设期望结果为11、12和13。
下面的代码已经写成了函数,但也可以很容易地改为子例程。我不想进入设置范围,只专注于功能。
如果您的数据只是由逗号和空格分隔的数字,那么只需使用replace:
Function ExtractNumber(ByVal text As String) As String
ExtractNumber = Replace(text, ", ", "")
End Function如果您想要一个更复杂的函数,它将提取所有数字,而不管字符串中可能有什么,这里是我的RegexExtract函数。默认情况下,我将其设置为用逗号分隔所有捕获,但您可以将其指定为none:
=RegexExtract(A1, "(\d)", "")下面是函数:
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发布于 2012-06-22 15:17:21
如果您不想使用VBA,也可以使用文本到列,请参阅:http://support.microsoft.com/kb/214261
https://stackoverflow.com/questions/8100125
复制相似问题