从Excel VBA中的列格式到多列格式

时间:2013-04-05 16:05:06

标签: excel excel-vba string-formatting vba

我有块格式的.txt数据:

1
1
2
2
3
3

在这个例子中,我有3个大小为2的块。大小不随块而变化,它是固定的。我的真实案例有大约500个大小为500的块。我想在Excel中以格式

导入这些数据
1 2 3
1 2 3

即每列代表一个块。我正在寻找一个在线工具,它可以提供一个简单的复制到剪贴板工具,但我找不到。考虑到我的列范围和块的大小(此处范围为A1:A6和块大小2),您将如何在Excel VBA中执行此操作?

1 个答案:

答案 0 :(得分:1)

Sub Tester()
    ReadBlocks "C:\local files\tmp.txt", 100, ActiveSheet.Range("a1")
End Sub


Sub ReadBlocks(sPath As String, BlockSize As Long, rngDest As Range)

    Dim fso As Object, f As Object, val, r As Long, c As Long

    On Error GoTo haveError

    Set fso = CreateObject("scripting.filesystemobject")
    Set f = fso.opentextfile(sPath, 1) '1=forReading

    r = 0
    c = 0
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Do Until f.AtEndOfStream
        rngDest.Offset(r, c).Value = f.ReadLine
        If (r + 1) Mod BlockSize = 0 Then
            r = 0
            c = c + 1
        Else
            r = r + 1
        End If
    Loop

haveError:

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub