退出条件在Do Until循环中不触发

我试图编写一个应用程序,它需要一个报表(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 

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

任何想法为什么?

在你的内部做直到..循环检查三个不同的条件,如果这三个条件都不符合,你的代码将继续删除工作表的第一行。 这导致Excel不断添加行到工作表的底部。

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

 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 

我还没有运行这个代码,因为我不知道你需要testing什么样的数据集。 但基本上,如果删除一行,则需要返回到外部do循环来检查数据是否已用完,如果有,则停止执行。