首页 > 解决方案 > 使用 vba 将 Txt 文件行输入到数组

问题描述

我有一个 txt 文件,我需要将它输入到一个字符串数组中,其中每一行都是数组中的一项。

我以前对 vba 做了很多处理,但从不编辑 Word 和 Excel 以外的文件,所以这对我来说是新的。

以下是我的子的一部分(从网上某处复制,所以我不太明白)

Sub TxtFileToArray(FilePath As String, LineArray As Variant, Optional Delimiter As String = vbCrLf)
'adapted from https://www.thespreadsheetguru.com/blog/vba-guide-text-files
Dim TextFile As Integer
Dim FileContent As String
    
'Open the text file in a Read State
  TextFile = FreeFile
  Open FilePath For Input As TextFile
  
'Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

'Close Text File
  Close TextFile

失败就行了FileContent = Input(LOF(TextFile), TextFile)。错误信息是:

运行时错误“62”:
输入超过文件末尾

变量Textfile= 1,并且LOF(Textfile)= 4480

我应该怎么办?

编辑:
该文件充满了 xml 数据(它实际上是一个已转换为 .txt 的 .odc 文件)。我应该做些什么来将它全部转换为字符串?也许我可以以某种方式将它作为一个巨大的字符串导入,然后将其拆分为数组?

标签: excelvbainputtexttxt

解决方案


文本文件到数组

  • 这只是对可能即将发布的答案的补充,以展示如何为您的任务使用函数(我不知道究竟是什么binary或 a binary file)。
  • 在我的简短调查中,它使用json文件进行了测试。对我来说有趣的是它与Inputand一起使用Binary,并且它需要vbLf而不是vbCrLfas Delimiter
  • 请注意,如果您选择了错误的分隔符,您可能会在数组中得到一个值,就像在这种情况下发生的那样。
  • A测试过程会将行(数组中的值)写入ActiveSheet.

编码

Option Explicit

Sub TESTtextFileToArray()
    Const FilePath As String = "F:\Test\2020\TXT\test.json"
    Dim TextLines As Variant
    ' Note the 'vbLf' instead of 'vbCrLf'.
    TextLines = TextFileToArray(FilePath, vbLf)
    If Not IsEmpty(TextLines) Then
        ' Note that 'Transpose' has a 65536 limit per dimension.
        Range("A1").Resize(UBound(TextLines) + 1).Value _
            = Application.Transpose(TextLines)
        'Debug.Print Join(TextLines, vbLf)
        MsgBox "Found " & UBound(TextLines) + 1 & " lines."
    Else
        MsgBox "No lines found."
    End If
End Sub

' The result is a 0-based 1D array.
Function TextFileToArray( _
    ByVal FilePath As String, _
    Optional Delimiter As String = vbCrLf) _
As Variant
    
    Const ProcName As String = "TextFileToArray"
    On Error GoTo clearError

    Dim TextFile As Long
    TextFile = FreeFile
    
    Open FilePath For Input Access Read As TextFile
    On Error Resume Next
    TextFileToArray = Split(Input(LOF(TextFile), TextFile), Delimiter)
    On Error GoTo clearError
    Close TextFile

ProcExit:
    Exit Function

clearError:
    Debug.Print "'" & ProcName & "': Unexpected Error!" & vbLf _
              & "    " & "Run-time error '" & Err.Number & "':" & vbLf _
              & "        " & Err.Description
    Resume ProcExit

End Function

推荐阅读