3

我正在尝试编写一个应用程序,它需要一个报告(Excel 工作表),操作一行,然后转到下一行,然后是下一行,等等,然后在下一个中的前两个单元格中退出 Do Until 循环行为空(表示没有更多行要处理),如下所示:

Imports Excel = Microsoft.Office.Interop.Excel

Dim MSExcel As New Excel.Application
MSExcel.Visible = True

Dim WorkbookA As Excel.Workbook
Dim WorksheetA As Excel.Worksheet

Dim i As Integer = 2 'Skipping header row
Dim Split() As String
Dim SomeStrings() As String = {"StringA", "StringB"} 'etc... an array of strings

WorkbookA = MSExcel.Workbooks.Open(TextBox1.Text)
WorksheetA = WorkbookA.Sheets.Item(1)

Do Until WorksheetA.Cells(i, 1).Value = "" And WorksheetA.Cells(i, 2).Value = ""

'~~If Column A cell does not contain 'valueA' or Column E cell does not contain 'valueB', delete the row
        Do Until InStr(WorksheetDisplay.Cells(i, 1).Value, "ValueA") <> 0 And InStr(WorksheetDisplay.Cells(i, 5).Value, "ValueB") <> 0 _
            And InStr("somenumbershere", Strings.Left((WorksheetDisplay.Cells(i, 3).Value), 1)) <> 0 'Only keeps entries that begin with a certain number
            WorksheetDisplay.Rows(i).Delete() 'Otherwise we delete the row
        Loop

        For Each Str As String In SomeStrings
            If Str = WorksheetDisplay.Cells(i, 3).Value Then
                Split = Strings.Split(WorksheetDisplay.Cells(i, 3).Value, " ")
                WorksheetDisplay.Cells(i, 3).Value = Split(0) & " some text here"
            End If
        Next

        i = i + 1

Loop

但是程序永远不会停止运行。

知道为什么吗?

4

1 回答 1

2

在您检查三个不同条件的内部执行 until..loop 中,如果不满足所有这三个条件,您的代码将继续删除工作表的第一行。这会导致 Excel 不断向工作表底部添加行。

因此,这个内部 do 循环有可能永远运行,防止外部 do 循环评估空白单元格的存在。更好的逻辑安排可能是:

Do Until WorksheetA.Cells(i, 1).Value = "" And WorksheetA.Cells(i, 2).Value = ""
  If InStr(WorksheetDisplay.Cells(i, 1).Value, "ValueA") <> 0 And InStr(WorksheetDisplay.Cells(i, 5).Value, "ValueB") <> 0 _
            And InStr("somenumbershere", Strings.Left((WorksheetDisplay.Cells(i, 3).Value), 1)) <> 0 'Only keeps entries that begin with a certain number
    WorksheetDisplay.Rows(i).Delete() 'Otherwise we delete the row
    'Decrement i so that the row that used to be beneath the row just deleted is not skipped.
    i = i - 1
  Else
    For Each Str As String In SomeStrings
      If Str = WorksheetDisplay.Cells(i, 3).Value Then
        Split = Strings.Split(WorksheetDisplay.Cells(i, 3).Value, " ")
        WorksheetDisplay.Cells(i, 3).Value = Split(0) & " some text here"
      End If
    Next
  End If
  i = i + 1
Loop

我没有运行这段代码,因为我不知道你需要测试什么样的数据集;但基本上,如果你删除一行,你需要回到外部循环来检查你是否已经用完了数据,如果有就停止执行。

于 2013-09-11T13:30:14.877 回答