以特定方式导入原始文件

时间:2014-08-22 04:12:03

标签: excel vba parsing import

我想导入一个非纯文本的原始文件。 我想要导入的值是我需要导入的单行字符,拆分为单个字符,并转换为介于00和FF之间的十六进制值。 有49152个字符,我希望它能在3列中导入。一个3 x 16384 像这样:

01 02 03
04 05 06

↓这个↓有效,但没有给出前导零。 (1应为01)。另外,它忽略了不包括所有三列的值。↓

Sub Demo()     Dim fl As String     Dim dat As Variant     Dim fn As Integer     Dim rOutput As Range     Dim idx As Long     Dim FileLength As Long     Dim v

fn = FreeFile
fl = "C:\Users\1097180551N\Desktop\untitled.png"

Set rOutput = [A1]

Open fl For Binary Access Read As #fn

FileLength = LOF(fn)
ReDim dat(1 To FileLength \ 3, 1 To 3)

For idx = 1 To UBound(dat, 1)
    v = Input(3, #fn)
    dat(idx, 1) = Hex(Asc(Mid$(v, 1, 1)))
    dat(idx, 2) = Hex(Asc(Mid$(v, 2, 1)))
    dat(idx, 3) = Hex(Asc(Mid$(v, 3, 1)))
Next
rOutput.Resize(UBound(dat, 1), 3) = dat
Close #fn
End Sub

1 个答案:

答案 0 :(得分:1)

您的上一个更新代码几乎就在那里。我会将文件读作二进制而不是输入,并将字符转换为可打印的形式。此外,使用变体数组将比直接编写工作表更快

Sub Demo()
    Dim fl As String
    Dim dat As Variant
    Dim fn As Integer
    Dim rOutput As Range
    Dim idx As Long
    Dim FileLength As Long
    Dim v

    fn = FreeFile
    fl = "C:\Users\1097180551N\Desktop\txt.raw"

    Set rOutput = [A1]

    Open fl For Binary Access Read As #fn

    FileLength = LOF(fn)
    ReDim dat(1 To FileLength \ 3, 1 To 3)

    For idx = 1 To UBound(dat, 1)
        v = Input(3, #fn)
        dat(idx, 1) = Hex(Asc(Mid$(v, 1, 1)))
        dat(idx, 2) = Hex(Asc(Mid$(v, 2, 1)))
        dat(idx, 3) = Hex(Asc(Mid$(v, 3, 1)))
    Next
    rOutput.Resize(UBound(dat, 1), 3) = dat

    Close #fn
End Sub