使用Excel VBA从数字中分隔字符串

时间:2011-11-21 12:41:30

标签: regex excel vba excel-vba excel-2010

我需要

a)从数字中选择单元格的字符串

b)将分隔的字符串和数字放在不同的列中。

例如,Excel表格如下:

     A1          B1
  100CASH     etc.etc.

结果应为:

   A1            B1          C1
  100           CASH       etc.etc.

正则表达式的使用将很有用,因为可能存在不同的单元格格式,例如100-CASH,100 / CASH,100%CASH。一旦设置了该过程,就不难为不同的变化使用正则表达式。

我遇到一个UDF用于从单元格中提取数字。这可以很容易地修改,以便从单元格中提取字符串或其他类型的数据,只需更改正则表达式。

但我需要的不仅仅是UDF,而是使用正则表达式拆分单元格并将分离的数据放入单独的列中的子过程。

我在SU中也发现了类似的问题,但它不是VBA。

2 个答案:

答案 0 :(得分:1)

看看这是否适合您:

更新11/30:

Sub test()

    Dim RegEx As Object
    Dim strTest As String
    Dim ThisCell As Range
    Dim Matches As Object
    Dim strNumber As String
    Dim strText As String
    Dim i As Integer 
    Dim CurrCol As Integer


    Set RegEx = CreateObject("VBScript.RegExp")
    ' may need to be tweaked
    RegEx.Pattern = "-?\d+"

    ' Get the current column
    CurrCol = ActiveCell.Column

    Dim lngLastRow As Long
    lngLastRow = Cells(1, CurrCol).End(xlDown).Row

    ' add a new column & shift column 2 to the right
    Columns(CurrCol + 1).Insert Shift:=xlToRight

    For i = 1 To lngLastRow  ' change to number of rows to search
        Set ThisCell = ActiveSheet.Cells(i, CurrCol)
        strTest = ThisCell.Value
        If RegEx.test(strTest) Then
            Set Matches = RegEx.Execute(strTest)
            strNumber = CStr(Matches(0))
            strText = Mid(strTest, Len(strNumber) + 1)
            ' replace original cell with number only portion
            ThisCell.Value = strNumber
            ' replace cell to the right with string portion
            ThisCell.Offset(0, 1).Value = strText
        End If
    Next

    Set RegEx = Nothing
End Sub

答案 1 :(得分:0)

怎么样:

Sub UpdateCells()
Dim rng As Range
Dim c As Range
Dim l As Long
Dim s As String, a As String, b As String

''Working with sheet1 and column C
With Sheet1
    l = .Range("C" & .Rows.Count).End(xlUp).Row
    Set rng = .Range("C1:C" & l)
End With

''Working with selected range from above
For Each c In rng.Cells
    If c <> vbNullString Then
        s = FirstNonNumeric(c.Value)

        ''Split the string into numeric and non-numeric, based
        ''on the position of first non-numeric, obtained above. 
        a = Mid(c.Value, 1, InStr(c.Value, s) - 1)
        b = Mid(c.Value, InStr(c.Value, s))

        ''Put the two values on the sheet in positions one and two 
        ''columns further along than the test column. The offset 
        ''can be any suitable value.
        c.Offset(0, 1) = a
        c.Offset(0, 2) = b
    End If
Next
End Sub

Function FirstNonNumeric(txt As String) As String
    With CreateObject("VBScript.RegExp")
        .Pattern = "[^0-9]"
        FirstNonNumeric = .Execute(txt)(0)
    End With
End Function