对于循环忽略ELSE存在时的真IF条件

在循环体中存在一个ELSE条件时,看起来我有一个让我的For循环确认我有一个True IF条件的问题。 这是我写的:

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'TEST FIND/SEARCH FEATURES Dim String2Find As String = txtCPUSerial.Text Dim ColumnNumber As Integer = 1 'Access the worksheet Dim xlApp As Excel.Application xlApp = CreateObject("Excel.Application") xlApp = GetObject(, "Excel.Application") Dim xlWB As Excel.Workbook = xlApp.Workbooks.Open("C:\Users\Machine\Desktop\DocDirectory\MyDoc.xls") Dim xWS As Excel.Worksheet xWS = xlWB.Worksheets("Sheet1") 'TRY TO LOOP THROUGH THE ROWS.. For x As Integer = 1 To xWS.Rows.Count Step 1 'Check if cell value matches the search string... If xWS.Cells(x, ColumnNumber).value = String2Find Then MessageBox.Show("Got it..." & String2Find & " in row " & x) Else MessageBox.Show("Item not in the sheet...") Exit For End If Next End Sub 

我已经试过在我的ElseString2Find <> txtCPUSerial.Text写一个简单的语句,但是语法爆炸,或者我仍然得到“Item not in the sheet …”的消息对话框,因此我的For循环的真实部分被逐步忽略,并且在得到True条件时不会返回对话框。

如果我删除了我的Else ,那么很明显,代码会相应地循环,如果文本框的值存在于我的工作表中(我已经在工作表中写入了一个任意值来查找,那么我将不包含或指定这个值这发生?

似乎更容易向您展示如何find它的示例,而不是解释代码中的所有问题:

 Dim xlApp = New Excel.Application ' this starts new Excel Application Dim xlWB = xlApp.Workbooks.Open("C:\Users\Machine\Desktop\DocDirectory\MyDoc.xls") Dim xlWS = xlWB.Worksheets("Sheet1") Dim xlColA = xlWS.Range("A:A") ' Column A Dim xlCell = xlColA.Find(txtCPUSerial.Text) ' or .Find(txtCPUSerial.Text,,,XlLookAt.xlWhole) If xlCell Is Nothing Then MsgBox(txtCPUSerial.Text & " not found") Else MsgBox(txtCPUSerial.Text & " found on row " & xlCell.Row) End If ' don't forget to close the Workbook and Excel Application xlWB.Close() xlApp.Quit() 

如何以编程方式在工作表范围中search文本

如果代码的目的是find所有的出现,并用其他东西replace ,我build议使用查找和replace方法

示例代码,testing和工作:

 Sub FindAndReplace() Dim FoundCell As Range With Columns("A:A") Set FoundCell = .Find(What:="old", After:=.Cells(1), _ LookIn:=-4163, LookAt:=1, SearchOrder:=1, SearchDirection:=1, MatchCase:=True, MatchByte:=False, SearchFormat:=False) If FoundCell Is Nothing Then MsgBox ("Item not in the sheet...") Exit Sub Else .Replace What:="old", Replacement:="new", LookAt:=1, _ SearchOrder:=1, MatchCase:=True, SearchFormat:=False, _ ReplaceFormat:=False End If End With End Sub 

它能做什么:

  1. find方法返回find的单元格的Range object ,如果没有find,则返回Nothing 。 将结果存储在FoundCellvariables中。
  2. 它检查FoundCellvariables是否为Nothing
  3. 如果没有,它显示消息并退出子。
  4. 如果它不是什么(意思是find了一个匹配),它会使用replace方法将所有“旧”值更改为“新”值。