我创建了一个包含多个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
答案 0 :(得分:0)
你需要对自己的条件进行空值检查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
- 没有值,没有公式。foundCell.Offset(0, 9).Value <> vbNullString
将返回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
答案 1 :(得分:-2)
如果Not FoundCell Is Nothing and foundCell.Offset(0,9)&lt;&gt; “”然后