我需要一段代码从单元格获取值并检查另一列的值,然后返回一个真/假答案或类似的代码。
然后我将使用条件来说出类似
的内容If "Value in cell B1" exists in Column C Then
Do nothing
Else
Msgbox "Please enter existing/valid value in B1"
End if
我根本无法弄清楚如何做到这一点。在此先感谢您的帮助!
Rgards 吉姆
答案 0 :(得分:3)
您可以使用Range.Find
执行此操作。
Dim rng as Range
Set rng = Range("C:C").Find(What:=Range("B1").Value), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If rng is nothing Then
Msgbox "Please enter existing/valid value in B1"
Else
' value of b1 found in column C
' do something else
End If
这将检查单元格B1的值是否在C列的任何单元格中。
rng
变量将指向C列中第一个出现的b1值。
有关.find
的所有参数的更多信息,请访问msdn:https://msdn.microsoft.com/de-de/library/office/ff839746.aspx
答案 1 :(得分:3)
这样的事情应该有效。插入VBA编辑器中的新模块,然后在Worksheet
中使用自定义函数,如下所示:
=find_string(B1,C:C)
Function Find_String(ByVal SearchTerm As String, ByVal Rng As Range) As String
Dim FindString As String
If Trim(SearchTerm) <> "" Then
With Rng
Set Rng = .Find(What:=SearchTerm, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
'Do something!
'Examples:
Application.Goto Rng, True
Find_String = "Found in cell " + Rng.Address
Else
MsgBox "Please enter existing/valid value in B1"
Find_String = "Nothing Found"
End If
End With
End If
End Function