Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

vba - If...Then statement for "if value is present in a specified column"

I'm trying to write an If...Then condition such that:

If the value of cell A3 in Sheet1 is present in column A of Sheet2 then...

I have tried with this code but it doesn't work (Error) :

If Worksheets("Sheet1").Range("A3") = Worksheets("Sheet2").Range("A:A") Then
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not quite sure why you're getting an error here, but your If..Then condition is definitely not working the way you're hoping/expecting it will.

You're trying to compare a single value (the value of A3 in Sheet1) to an entire column (column A in Sheet2), which is definitely not the same as looking to see if that value is in that column.

You can use the Range.Find method to determine whether a value is present in a given range, as shown below.

Dim varFindThis As Variant
Dim rngLookIn As Range

varFindThis = Worksheets("Sheet1").Range("A3")
Set rngLookIn = Worksheets("Sheet2").Range("A:A")

If Not rngLookIn.Find(varFindThis, LookIn:=xlValues) Is Nothing Then
    ...
End If

See this MSDN page for more details on the function and how it can be used.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...