查找单元格中是否存在另一个范围/单元格中的值

我需要一段代码,它从单元格中获取值,然后检查另一列的值,然后返回一个真/假答案或类似的结果。

然后我会用条件来说一些类似的东西

If "Value in cell B1" exists in Column C Then Do nothing Else Msgbox "Please enter existing/valid value in B1" End if 

我根本无法弄清楚如何做到这一点。 提前感谢任何帮助!

吉姆

你可以使用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的任何单元格中

rngvariables将指向C列中第一次出现的b1值。

有关.find所有参数的更多信息, .find参见msdn: https : .find

像这样的东西应该工作。 在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