MICROSOFT

EP02. “Read Data from Text File 读取文本文件”

首页 Microsoft 工具 Excel · VBA · Application Object · EP02
约 4 分钟· #EP02#Excel#Application Object
🔒 登录后可标记已读
  • 讲怎么用 VBA 打开一个外部文本文件、逐行读取内容
  • 再用 InStr/Mid 从文字里截取出需要的数据写进单元格
  • 范例是从一份含经纬度的文本文件里,抓出 Latitude 和 Longitude 两个数值
  • 前置知识:InStr、Mid 这两个字符串函数的基本用法

重点内容


适用版本

桌面版通用(Excel 365 / 2021 / 2019 等)。


完整代码

Dim myFile As String, text As String, textline As String, posLat As Integer, posLong As Integer

myFile = "C:\test\geographical-coordinates.txt"
' 或者用文件选择对话框:myFile = Application.GetOpenFilename()

Open myFile For Input As #1

Do Until EOF(1)
    Line Input #1, textline
    text = text & textline
Loop

Close #1

posLat = InStr(text, "latitude")
posLong = InStr(text, "longitude")

Range("A1").Value = Mid(text, posLat + 10, 5)
Range("A2").Value = Mid(text, posLong + 11, 5)

逻辑说明

  • myFile 存放文件路径,可以写死路径,也可以用 Application.GetOpenFilename() 弹出选择文件的对话框
  • Open ... For Input As #1:以「读取模式」打开文件,#1 是这个文件的代号
  • Do Until EOF(1) 循环:从头到尾(直到 End Of File)逐行读取,用 Line Input 把每一行接到 text 变量后面
  • Close #1:读完一定要关闭文件
  • InStr 找到 "latitude"、"longitude" 这两个关键字在整段文字里的位置
  • Mid 从找到的位置往后数固定字符数,截取出对应的数值

学完你会

  • ✅ 用 Open ... For Input 打开外部文本文件读取内容
  • ✅ 用 Do Until EOF(1) + Line Input 逐行读完整个文件
  • ✅ 搭配 InStr/Mid 从读到的文字里截取需要的数据

常见错误

  • 读完文件忘记 Close #1,文件被占用,之后想再打开会出错
  • Mid 函数的起始位置和长度算错,截出来的数字多字或少字
  • 文件路径写死,换一台电脑或换文件夹就找不到文件——可以改用 Application.GetOpenFilename() 让使用者自己选

Sources

Blog / Website:

  1. Read Data from Text File