【问题标题】:Is there a way to retrieve information from a text file in vba?有没有办法从 vba 中的文本文件中检索信息?
【发布时间】:2019-10-10 01:50:22
【问题描述】:

我需要将文本文件中的信息保存到数组中。但我不知道具体的语法是什么。

来自文本文件的信息大约有 2000 行,显然您不能将其存储在 vba 脚本中。文字看起来像下面这样一个

35SLFR0006350
35SLFR0026350
35SLFR0106350
BARSQR1306000
C280BD1016000
C280BD1016000_mitre
C280BD1016000_square
C280FR0006000
C280MU0006000
C280MU0026000
C280SH0006000
C280SH0006000_outer frame
C305BD0006000
C305BD0006000_mitre
C305BD0006000_square
C305BD0016000
C305BD0016000_mitre
C305BD0016000_square
C305BD2006000
C305BD2006000_mitre
C305BD2006000_square
C305FR0006000
C305MU0006000
C305MU0026000
C305MU0046000
C305SH0006000
C305SH0006000_Un E frame
C340BD1006000_mitre
C340BD1006000_Right,Left,Horizontal
C340BD1006000_Right,Left,Vertical
C340BD1006000_square
C340FR00060000
C340MU0006000
C340MU0026000
C340SH0006000

【问题讨论】:

标签: excel vba


【解决方案1】:

如果要将输入文件保存为数组,可以先读取整个文件并将其保存为一个完整的字符串。 然后,您可以使用带有分隔符 \n 的 Split 函数返回一个数组,其中每个元素对应于文件的一行。

Const file As String = "<pathToFile>"
Dim ResultArray() As String
Dim tempString As String
Dim fn As Integer

fn = FreeFile()

Open file For Input As fn
While Not EOF(fn)
   Line Input #fn, LineString
   tempString = tempString & LineString & "\n"
Wend

ResultArray = Split(tempString, "\n")

【讨论】:

  • Sub data() Const file As String = "C:\Users\dperks\Desktop\PROFILES.txt" Dim ResultArray() As String Dim tempString As String Dim fn As Integer fn = FreeFile()打开文件输入为 fn 而不是 EOF(fn) 行输入 #fn, LineString tempString = tempString & LineString & "\n" Wend ResultArray = Split(tempString, "\n") End Sub
  • 问题是它带有这个错误:需要常量表达式,所以它不能识别程序中的文件
  • 它适合我,我不知道为什么它不适合你...试试这个代码:Sub data() Dim file As String Dim ResultArray() As String Dim tempString As String Dim fn As Integer file = "&lt;pathToYourFile&gt;" fn = FreeFile() Open file For Input As fn While Not EOF(fn) Line Input #fn, LineString tempString = tempString &amp; LineString &amp; "\n" Wend ResultArray = Split(tempString, "\n") End Sub
  • 谢谢,但它仍然说同样的错误。见下文。有什么办法可以将变量存储到数组中? Sub TextFile_PullData() Dim TextFile As Integer Dim FilePath As String Dim FileContent As String '文本文件 FilePath 的文件路径 = "C:\Users\chris\Desktop\MyFile.txt" '确定下一个可供 FileOpen 使用的文件号function TextFile = FreeFile '打开文本文件 Open FilePath For Input As TextFile '在变量中存储文件内容 FileContent = Input(LOF(TextFile), TextFile) '关闭文本文件 Close TextFile End Sub
  • 已修复。我编辑了这一行,说 Open "PROFILES.txt" For Input As fn。感谢您的帮助
猜你喜欢
  • 2021-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 2014-04-10
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
相关资源
最近更新 更多