开发者

Splitting a string with variable number of spaces VBA

开发者 https://www.devze.com 2022-12-18 19:13 出处:网络
I have a file with a bunch of numbers in columns. These numbers are separated by a variable number of spaces. I want to skip the first line and get all the other lines and separate each number on the

I have a file with a bunch of numbers in columns. These numbers are separated by a variable number of spaces. I want to skip the first line and get all the other lines and separate each number on the line. Finally, I want to write each number in Excel. I've been able to get the lines and write them on Excel but I can't separate each number (I'm getting the whole line as one string).

Does any body know how to split a string that has a variable number of spaces?

Here is my code.

Sub Test()

    r = 0

    With New Scripting.FileSystemObject
        With .OpenTextFile("C:\Users\User\Desktop\File.tab", ForReading)
            If Not .AtEndOfStream Then .SkipLine
            Do Until .AtEndOfStream
                ActiveCell.Offset(r, 0) = Split(.ReadLine, vbCrLf)
                r = r + 1
            Loop
    开发者_JAVA技巧    End With
    End With
End Sub


If you use the Excel worksheet function trim in place of the VBA function then excel will remove multiple spaces within a cell (not just from the left and right ends). Something like the below should solve the problem. I'm afraid I've not tested it as I haven't a copy of Excel handy.


Sub Test()

Dim splitValues As Variant
Dim i As Long

r = 0

With New Scripting.FileSystemObject
    With .OpenTextFile("C:\Users\User\Desktop\File.tab", ForReading)
        If Not .AtEndOfStream Then .SkipLine
        Do Until .AtEndOfStream
            ActiveCell.Offset(r, 0) = Split(.ReadLine, vbCrLf)
        Application.Trim(ActiveCell.Offset(r, 0))
        splitValues = Split(ActiveCell.Offset(r, 0), " ")

        For i = 0 To UBound(x)
            ActiveCell.Offset(r, i+1) = splitValues(i)
        Next
        Loop
    r = r + 1
    End With
End With
0

精彩评论

暂无评论...
验证码 换一张
取 消