初始化正确的值以避免对象variables或未设置块variables

我有一块代码,我正在使用一个For... Next循环来通过一个Excel工作表,并告诉我,如果在文本框中input的值是否被发现。 如果值匹配,我已经修改它的工作。 然而,我收到的对象/阻塞variables没有设置错误,它令我困惑。 我创build了以下内容:

  Dim Value2Find_1 As String = txtMachNumber.Text 'Serial number value. Dim Value2Find_2 As String = txtMachName.Text 'Machine name value. Dim ReplaceWithValue1 As String = "" 'Replaces the serial number value if found in the sheet. Dim ReplaceWithValue2 As String = "" 'Replaces the machine name value if found in the sheet. Dim ReplaceWithValue3 As String = "" 'Replacement for the date-time in the Date Column. Dim Range2Use_1 = xlWS.Range("A1:A4000") 'Range to span the A Column. Dim Range2Use_2 = xlWS.Range("B1:B4000") 'Range to span the B Column. Dim Range2Use_3 = xlWS.Range("F1:F4000") 'Range to span the F Column. Dim xlCell_A = Range2Use_1.Find(txtMachNumber.Text) 'Looks up the searched serial value in A Column. Dim xlCell_B = Range2Use_2.Find(txtMachName.Text) 'Looks up the searched machine value in B Column. Dim LastRow = xlWS.Range("A4000").End(Excel.XlDirection.xlUp).Row + 1 Dim i As Integer With xlWS For i = 1 To LastRow If Not (Value2Find_1 = txtMachNumber.Text And Value2Find_2 = txtMachName.Text) Then MessageBox.Show("No value exists here...") Else Range2Use_1.Find(What:=Value2Find_1, MatchCase:=True) Range2Use_2.Find(What:=Value2Find_2, MatchCase:=True) MsgBox("Found both values: " & Value2Find_1 & " and " & Value2Find_2 & " on row " & xlCell_A.Row) End If Exit Sub Next End With 

如果我的文本框条目不在工作表中,则错误将在以下代码行中返回:

 MsgBox("Found both values: " & Value2Find_1 & " and " & Value2Find_2 & " on row " & xlCell_A.Row) 

我已经缩小了它与返回所find的文本框条目的行号的variables – xlCell_A 。 然而,这是我卡住的地方。 为了避免Object / With Blockvariables未设置错误,我需要将其设置为什么? 恐怕我不知道这是什么要求。

我认为你的代码的问题在于Find方法在没有find匹配的情况下返回Nothing ,正如它的文档所述 。 因此, xlCell_A.Row返回错误,因为无法在Nothing上调用Row方法。

其实,我发现你的代码还有一些问题:

  1. for循环的内部不依赖于循环variablesi 。 因此,它在每个交互中都完全一样。
  2. With块的variablesxlWS从不使用,这使得With块不一致。
  3. 循环中Find方法的返回值永远不会被分配给任何东西。 正因为如此,他们没有效果。
  4. if语句中的条件总是返回False因为您永远不会更改Value2Find_1Value2Find_2的值,并将其分别初始化为txtMachNumber.TexttxtMachName.Text

如果您打算评估txtMachNumber.TexttxtMachName.Text是否分别存在于列A和B中,则可以只testingxlCell_AxlCell_B是否为Nothing

既然你想要在同一行find两个使用Find不能保证的行,那么使用循环可能会更容易,但是用Range2Use_1.Cells(i,1)Range2Use_2.Cells(i,1)replacetxtMachNumber.TextRange2Use_2.Cells(i,1)在if语句中。 (这将第i行中的值与要search的值进行比较。)显然,您必须在find匹配项后退出循环,例如使用break语句。