在 VBA 中逐行读取/解析文本文件 [英] Read/Parse text file line by line in VBA

查看:58
本文介绍了在 VBA 中逐行读取/解析文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 VBA 解析文本文档并返回文本文件中给出的路径.例如,文本文件看起来像:

I'm trying to parse a text document using VBA and return the path given in the text file. For example, the text file would look like:

*Blah blah instructions
*Blah blah instructions on line 2
G:\Folder...data.xls
D:\AnotherFolder...moredata.xls

我希望 VBA 一次加载 1 行,如果它以 * 开头,则移动到下一行(类似于被注释的那一行).对于带有文件路径的行,我想将该路径写入单元格,例如 A2 表示第一个路径,B2 表示下一个路径,等等.

I want the VBA to load 1 line at a time, and if it starts with a * then move to the next line (similar to that line being commented). For the lines with a file path, I want to write that path to cell, say A2 for the first path, B2 for the next, etc.

我希望回答的主要问题是:

The main things I was hoping to have answered were:

  1. 使用 VBA 阅读文本文件的最佳/简单方法是什么?
  2. 我该如何逐行执行此操作?

推荐答案

对于文本文件最基本的读取,使用 open

for the most basic read of a text file, use open

示例:

Dim FileNum As Integer
Dim DataLine As String

FileNum = FreeFile()
Open "Filename" For Input As #FileNum

While Not EOF(FileNum)
    Line Input #FileNum, DataLine ' read in data 1 line at a time
    ' decide what to do with dataline, 
    ' depending on what processing you need to do for each case
Wend

#作者注 - 请停止添加 close #FileNum - 它已在评论中解决,并且不需要作为对这个答案的改进

#Author note - Please stop adding in close #FileNum - it's addressed in the comments, and it's not needed as an improvement to this answer

这篇关于在 VBA 中逐行读取/解析文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆