首页 > 解决方案 > 使用 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

谢谢

标签: excelvbacsv

解决方案


如果您逐步执行代码,您会意识到您正在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

推荐阅读