使用VBA读取CSV时出错 [英] Error while reading CSV with VBA

查看:733
本文介绍了使用VBA读取CSV时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用VBA读取CSV。在遵循本教程时,我会收到以下代码:

I'm trying to read a CSV with VBA. When following this tutorial, I get the following code:

Sub OpenTextFile()

Dim FilePath As String
FilePath = "C:\path\to\file\mycsv.csv"
Open FilePath For Input As #1
row_number = 0

Do Until EOF(1)
    Line Input #1, LineFromFile
    LineItems = Split(LineFromLine, ",")

    ActiveCell.Offset(row_number, 0).Value = LineItems(2)
    ActiveCell.Offset(row_number, 1).Value = LineItems(1)
    ActiveCell.Offset(row_number, 2).Value = LineItems(0)

    row_number = row_number + 1
Loop

Close #1

End Sub

这是我的CSV:

peter,paris,23
mary,london,34
steve,rome,56
lily,madrid,65

执行代码时出现错误:


索引超出范围

Index out of range

此行标记为黄色:

ActiveCell.Offset(row_number, 0).Value = LineItems(2)


推荐答案

您有拼写错误:

LineItems = Split(LineFromLine, ",")

应为

LineItems = Split(LineFromFile, ",")


b $ b

如果你在模块开头使用 Option Explicit ,就不会发生这种情况);

This would not have happened if you used Option Explicit at the beginning of your module ;)

这篇关于使用VBA读取CSV时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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