VBA/EXCEL: extract numbers from one cell that contained multiple values with comma

安稳与你 提交于 2019-12-12 01:53:40

问题


http://i.stack.imgur.com/53tz0.jpg is the images.

Hello I would like to modify this code, so it understands multiple values. the best I came was the barcode scanner, I'm a novice in vba but I really enjoy it. this is a fun project that I do so please help me. Thanks guys.

Private Sub Worksheet_Change(ByVal Target As Range)

    Const SCAN_CELL As String = "A1"
    Const RANGE_BC As String = "A5:A500"
    Dim val, f As Range, rngCodes As Range

    If Target.Cells.Count > 1 Then Exit Sub
    If Intersect(Target, Me.Range(SCAN_CELL)) Is Nothing Then Exit Sub

    val = Trim(Target.Value)
    If Len(val) = 0 Then Exit Sub

    Set rngCodes = Me.Range(RANGE_BC)

    Set f = rngCodes.Find(val, , xlValues, xlWhole)
    If Not f Is Nothing Then
        With f.Offset(0, 2)
            .Value = .Value + 1
        End With
    Else
        Set f = rngCodes.Cells(rngCodes.Cells.Count).End(xlUp).Offset(1, 0)
        f.Value = val
        f.Offset(0, 1).Value = "enter description"
        f.Offset(0, 2).Value = 1
    End If

    Application.EnableEvents = False
    Target.Value = ""
    Application.EnableEvents = True

    Target.Select
End Sub

回答1:


To get multiple values stored in one cell that are separated by a comma or any special character you can use the vba function Split.

For example, let's say we have a cell C5 that have the following four numbers separated by a comma :

122.20,358.55,155.58,758.33

Here is how you can use the Split function to return an array storing each number from cell C5:

msgbox(split(range("c5"),",")(0))    'This will return 122.20
msgbox(split(range("c5"),",")(1))    'This will return 358.55
msgbox(split(range("c5"),",")(2))    'This will return 155.58
msgbox(split(range("c5"),",")(3))    'This will return 758.33

Hope this helps



来源:https://stackoverflow.com/questions/29047849/vba-excel-extract-numbers-from-one-cell-that-contained-multiple-values-with-com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!