excel - 使用 Excel 在 VBA 中循环期间有条件地跳过 CSV 文件中的一行
问题描述
将数据从 CSV 文件导入 Excel 电子表格时,我想跳过重复的行。我只需要每行的一个实例(以数字表示,每行的第一项)
数据格式如下例: 01;text;more-text 02;text;more-text 02;text;more-text 02;text;more-text 03;text;more-text 05;text;more-text 06;文本;更多文本 06;文本;更多文本 07;文本;更多文本
如下面的代码所示,我尝试使用“GoTo”方法来跳过行,仍然将 rowNum 递增 1,希望程序能够继续超过该行,但无论如何,我仍然会导入文件的所有行进入我的电子表格。
Open myFile For Input As #1
rowNum = 0
Do Until EOF(1)
Line Input #1, textline
LineItems = Split(textline, ";")
If ActiveCell.Offset(rowNum, 0).Value = ActiveCell.Offset(rowNum - 1, 0).Value Then GoTo SkipLine Else GoTo Continue
Continue:
ActiveCell.Offset(rowNum, 0).Value = LineItems(0)
ActiveCell.Offset(rowNum, 1).Value = LineItems(1)
ActiveCell.Offset(rowNum, 2).Value = LineItems(5)
rowNum = rowNum + 1
If 1 = 1 Then GoTo LoopAgain
SkipLine:
rowNum = rowNum + 1
LoopAgain:
Loop
Close #1
谢谢
解决方案
如果您逐步执行代码,您会意识到您正在ActiveCell.Offset(rowNum, 0).Value
比较ActiveCell.Offset(rowNum - 1, 0).Value
但是您尚未输入任何数据,ActiveCell.Offset(rowNum, 0).Value
因此该值永远不会为真。
快速解决方法是将行更改为
If LineItems(0) = ActiveCell.Offset(rowNum - 1, 0).Value Then GoTo SkipLine Else GoTo Continue
但这会给你留下空白行,你真的想避免使用 GoTo。我会这样重写代码:
Open myFile For Input As #1
rowNum = 1 'this should start at 1
Dim xls As Excel.Worksheet 'create a worksheet object
Set xls = ThisWorkbook.Worksheets("Sheet1") 'set to your required sheet
Do Until EOF(1)
Line Input #1, textline
lineitems = Split(textline, ";")
If rowNum <> 1 Then 'set an exception for the first row
If lineitems(0) <> xls.Cells(rowNum - 1, 1) Then 'check if this is the same as the last row written
xls.Cells(rowNum, 1) = lineitems(0)
xls.Cells(rowNum, 2) = lineitems(1)
xls.Cells(rowNum, 2) = lineitems(5)
rowNum = rowNum + 1 'only increment once the row is written
End If
End If
Loop
Close #1
推荐阅读
- audio - OpenMusic 不播放音频
- python - 通过 numpy 数组用行和列替换子集 pandas 数据框
- flutter - 减小从颤振相机插件捕获的图像大小的正确方法是什么
- python - 如何解码 base64 图像并为我的图像分类模型 FastAPI API 获取它的类
- sql - 为什么 sum 函数只显示单个结果?
- javascript - JS函数不会在按钮单击时初始化
- sql - Ruby on Rails 难查询
- angular - 如何使用角度在浏览器的新选项卡中实现打开链接?
- hadoop - 有没有办法 hadoop getmerge 部分文件不是所有文件?
- python - 使用 Python ctypes 作为示例从 Ruby 中 FFI 中包装的 C 库获取返回值的问题