Vba 使用搜索功能查找“-”并仅提取数字修复错误

Vba find "-" by using seach function and extract only numbers fix errors

你能帮我解决 vba 中的以下错误吗?公式有效但有错误。我的场景是需要在数字之间提取(两个“-”之间)

Ite1-223466678-ghtrdhjuyr321
Ite-654354477-hjuyt-
Dftehh-767678765-4yutiuy

仅提取“-”之间的这 9 位数字,需要应用到我的 excel 到 VBA

的最后一行

公式:

= Value(mid(A1,search("-",A1)+1, search ("-",A1, search ("-", A1)+1-search("-", A1)-1))

VBA:

Sub Data2

Dim lastrow as long 

Lastrow=Range("A"&rows.count).end(xlup).row
Range("F2:F" & lastrow).formula = " = 
Value(mid(A1,search("-",A1)+1, search 
("-",A1, search ("-", A1)+1- 
 search("-.   ", A1)-1)"

End sub

错误

试一试:

Sub BetweenDashs()
    Dim lastrow As Long, i As Long
    lastrow = Range("A" & Rows.Count).End(xlUp).Row
    
    For i = 2 To lastrow
        arr = Split(Range("A" & i).Value, "-")
        If UBound(arr) > 0 Then
            Range("F" & i).Value = CLng(arr(1))
        End If
    Next i
End Sub

编辑#1:

如果您的数据位于 C 列而不是 A 列,则使用:

Sub BetweenDashs()
    Dim lastrow As Long, i As Long
    lastrow = Range("C" & Rows.Count).End(xlUp).Row
    
    For i = 2 To lastrow
        arr = Split(Range("C" & i).Value, "-")
        If UBound(arr) > 0 Then
            Range("F" & i).Value = CLng(arr(1))
        End If
    Next i
End Sub