Lấy số từ một chuỗi kí tự cho trước trong Excel

Đê lấy số từ chuỗi kí tự trong một Cell trong Excel thì bạn phải viết một Macro cách thức như sau

1. Mở File Excel bạn muốn làm

2. Bấm tổ hợp phím Alt-F11 . Cửa sổ Microsoft Visual Basic hiện ra

3. Bạn chọn Insert --> Module . Một cửa số trắng Book1 : Module hiện ra .

4. Bạn Copy toàn bộ nội dung bên dưới

 Function ExtractNumber(rCell As Range, _
     Optional Take_decimal As Boolean, Optional Take_negative As Boolean) As Double


Dim iCount As Integer, i As Integer, iLoop As Integer

    Dim sText As String, strNeg As String, strDec As String

    Dim lNum As String

    Dim vVal, vVal2

    sText = rCell

    If Take_decimal = True And Take_negative = True Then

        strNeg = "-"

        strDec = "."

    ElseIf Take_decimal = True And Take_negative = False Then

        strNeg = vbNullString

        strDec = "."

    ElseIf Take_decimal = False And Take_negative = True Then

        strNeg = "-"

        strDec = vbNullString

    End If

    iLoop = Len(sText)

           For iCount = iLoop To 1 Step -1

            vVal = Mid(sText, iCount, 1)


                If IsNumeric(vVal) Or vVal = strNeg Or vVal = strDec Then

                    i = i + 1

                    lNum = Mid(sText, iCount, 1) & lNum

                        If IsNumeric(lNum) Then

                            If CDbl(lNum) < 0 Then Exit For

                        Else

                          lNum = Replace(lNum, Left(lNum, 1), "", , 1)

                        End If

                End If

                If i = 1 And lNum <> vbNullString Then lNum = CDbl(Mid(lNum, 1, 1))

            Next iCount

  

  ExtractNumber = CDbl(lNum)

End Function

 

5. Quay trở lại Excel

Cách thức sử dụng như sau

Hàm ExtractNumber có hai tham số lựa chọn đó là lấy phần thập phân và lấy số âm

Nếu cả hai đều là False có nghĩa là bỏ qua

 

Nội dung trong ô A1

a-bg-12909-                        =ExtractNumber(A1,,TRUE)            -12909

a-bg-12909-                        =ExtractNumber(A2)                         12909

a.a1.2...                               =ExtractNumber(A3,TRUE)              1.2

a.a1.2...                                =ExtractNumber(A4)                        12

a.a-1.2….                             =ExtractNumber(A5,TRUE,TRUE)   -1.2

abg1290.11                          =ExtractNumber(A6,TRUE)             1290.11

abg129013Agt                     =ExtractNumber(A7)                         129013

abg129012                           =ExtractNumber(A8)                        129013