2017-09-15 53 views
0

我創建了一個用戶窗體,其中有幾個textboxes,我使用foundcell根據參考編號返回一行的值。根據多個標準在用戶窗體中查找函數

但是我想要做的是搜索一個參考,它是基於searchrange下面是在,如果.Range("AK")是空白返回。否則,msgbox會說該條件無效。

請參閱我試圖代碼

Private Sub CommandButton1_Click() 

Dim searchRange As Range 
Dim foundCell As Range 
Dim mysearch As String 

mysearch = Ref.Value 

With Sheets("X") 
    Set searchRange = Sheets("X").Range("AB2", .Range("AB" & .Rows.Count).End(xlUp)) 
End With 

Set foundCell = searchRange.Find(what:=mysearch, Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False) 

     If Not foundCell And foundCell.Offset(0, 9) Is Nothing Then 

      Me.C.Value = foundCell.Offset(0, -12).Value 
      Me.DD.Value = foundCell.Offset(0, -10).Value 
      Me.RD.Value = foundCell.Offset(0, -16).Value 
      Me.BN.Value = foundCell.Offset(0, -9).Value 
      Me.FN.Value = foundCell.Offset(0, -8).Value 
      Me.SHARP.Value = foundCell.Offset(0, -1).Value 
      Me.PGP.Value = foundCell.Offset(0, -7).Value 
      Me.ISS.Value = foundCell.Offset(0, -6).Value 
      Me.DE.Value = foundCell.Offset(0, -2).Value 
      Me.UN.Value = foundCell.Offset(0, -5).Value 
      Me.W.Value = foundCell.Offset(0, -4).Value 
      Me.IN.Value = foundCell.Offset(0, -3).Value 
      Me.CVAL.Value = foundCell.Offset(0, -20).Value 
      Me.ADD.Value = foundCell.Offset(0, -11).Value 
      Me.RESPONSE.Value = foundCell.Offset(0, 1).Value 
      Me.NRESPONSE.Value = foundCell.Offset(0, 2).Value 
      Me.MAREC.Value = foundCell.Offset(0, 4).Value 
      Me.MORET.Value = foundCell.Offset(0, 5).Value 
      Me.CNREC.Value = foundCell.Offset(0, 8).Value 
      Me.CNREF.Value = foundCell.Offset(0, 6).Value 
      Me.NVALUE.Value = foundCell.Offset(0, 7).Value 
      Me.CBY.Value = foundCell.Offset(0, 10).Value 
      Me.CDAT.Value = foundCell.Offset(0, 11).Value 

     Else 

      MsgBox "The Reference you have entered does not qualify and cannot be located. Please try another reference!" 
End If 

End Sub 

回答

-2

如果不foundCell一無所有,foundCell.Offset(0,9)<> 「」 「」 那

+0

每當'foundCell是Nothing'這將提高運行時錯誤91。條件表達式不會在VBA中短路,無論第一部分評估爲「False」,都會對其進行全面評估。另外''>「」「」'意味着你正在驗證單元格不包含兩個雙引號,只要'foundCell'不是' Nothing'。 –

0

你需要爲null檢查foundCell其自己的條件,VBA的And邏輯運算符不像VB.NET的AndAlso和C#的&&運算符短路。

If Not foundCell Is Nothing Then 

而且foundCell.Offset(0,9)可以包含一個誤差值,這將使任何比較操作拋出一個「類型不匹配」運行時錯誤。使用IsError之前驗證其錯誤狀態你認爲它含有比一個錯誤的任何其他:

If Not IsError(foundCell.Offset(0, 9).Value) Then 

最後,如果你的目的是爲了驗證是否foundCell.Offset(0, 9)不爲空,您可以通過多種方式檢查,但Is Nothing是不是其中之一:

  • IsBlank(foundCell.Offset(0, 9).Value)將返回True如果單元格中包含什麼 - 沒有價值,沒有公式。如果單元格的值爲空字符串,或者其公式計算爲空字符串,則返回True
  • foundCell.Offset(0, 9).Value <> ""將執行與<> vbNullString相同的操作。

這樣:

If Not foundCell Is Nothing Then 
    If Not IsBlank(foundCell.Offset(0, 9).Value) Then 

或者:

If Not foundCell Is Nothing Then 
    If Not IsError(foundCell.Offset(0, 9).Value) Then 
     If foundCell.Offset(0, 9).Value <> vbNullString Then 
相關問題