VBA:从字符串中解析前面的数字

时间:2014-06-02 20:40:37

标签: vba

我需要将一个字符串解析为两个子字符串,该字符串始终以数字文本开头,后跟字母数字文本。字符串可能会有所不同,但不会太多。下面是传入格式和我需要的字符串的示例:

"00 10 50 Information to Bidders"   ==> "00 10 50", "Information to Bidders"
"001050 Information to Bidders"     ==> "001050", "Information to Bidders"    
"00 10 50 - Information to Bidders" ==> "00 10 50", "Information to Bidders"
"001050 -- Information to Bidders"  ==> "001050", "Information to Bidders"

我希望它只有6行VBA,但是我的代码变成了一个循环,我测试字符串中的每个字符,看看从仅数字转换到非数字的位置,然后根据转换位置解析字符串。没什么大不了的,但比我希望的更乱。是否有VBA函数可以消除迭代每个字符串字符的需要?

1 个答案:

答案 0 :(得分:2)

好吧,你的问题很糟糕,如果你想在Word,Excel等中完成这个问题,你甚至都不说...

我假设是Excel。所以,这要么做你想做的,要么给你一个良好的开端! 它读取A列中的值并将结果吐出到B列中。

Sub FormatMePlease()

Dim row As Integer
row = 1

Do While (True)

    If Range("A" & row).Value = "" Then
        Exit Do
    End If

    Dim originalValue As String
    originalValue = Range("A" & row).Value
    originalValue = Replace(originalValue, Chr(34), "") 'chr(34) is double quote
    originalValue = Replace(originalValue, "-", "") 'be gone oh evil dash
    originalValue = Replace(originalValue, "  ", " ") 'double white space? Never! Single white space will be more than enough

    Dim result As String

    result = Chr(34)
    For i = 1 To Len(originalValue)

    Dim currentCharacter As String
    currentCharacter = Mid(originalValue, i, 1)

    If (IsNumeric(currentCharacter) Or currentCharacter = " ") Then
        result = result + currentCharacter
    Else
        result = Left(result, i - 1)
        result = result & Chr(34) & ", " & Chr(34)
        result = result & Mid(originalValue, i)
        Exit For            
    End If

    Next i

    result = result & Chr(34)

    Range("B" & row).Value = result

    row = row + 1

Loop

End Sub

使用Excel进行屏幕截图:

enter image description here