问题描述
我有一列超过500行的数字。我需要使用VBA检查变量X是否匹配列中的任何值。有人可以帮助我吗?
如果你想做这个没有 VBA,你可以使用 IF
, ISERROR
和 MATCH
。
所以如果所有值都在列A中,在列B中输入此公式:
= IF(ISERROR(MATCH(12345,A:A ,0)),未找到,在行上找到的值和MATCH(12345,A:A,0))
这将寻找值12345(也可以是单元格引用)。如果没有找到该值, MATCH
返回#N / A, ISERROR
/ p>
如果要使用VBA,最快的方法是使用FOR循环:
code> Sub FindMatchingValue()
Dim i as Integer,intValueToFind as integer
intValueToFind = 12345
对于i = 1到500'修改500以包含所有值
如果Cells(i,1).Value = intValueToFind then
MsgBox(Found value on row& i)
Exit Sub
End If
Next i
'这个MsgBox将只显示循环是否完成
MsgBox(在范围内找不到值)
End Sub
您可以在VBA中使用Worksheet函数,但它们很挑剔,有时会抛出无意义的错误。 FOR
循环非常简单。
I have a column of numbers of over 500 rows. I need to use VBA to check if variable X matches any of the values in the column.
Can someone please help me?
If you want to do this without VBA, you can use a combination of IF
, ISERROR
, and MATCH
.
So if all values are in column A, enter this formula in column B:
=IF(ISERROR(MATCH(12345,A:A,0)),"Not Found","Value found on row " & MATCH(12345,A:A,0))
This will look for the value "12345" (which can also be a cell reference). If the value isn't found, MATCH
returns "#N/A" and ISERROR
tries to catch that.
If you want to use VBA, the quickest way is to use a FOR loop:
Sub FindMatchingValue()
Dim i as Integer, intValueToFind as integer
intValueToFind = 12345
For i = 1 to 500 ' Revise the 500 to include all of your values
If Cells(i,1).Value = intValueToFind then
MsgBox("Found value on row " & i)
Exit Sub
End If
Next i
' This MsgBox will only show if the loop completes with no success
MsgBox("Value not found in the range!")
End Sub
You can use Worksheet Functions in VBA, but they're picky and sometimes throw nonsensical errors. The FOR
loop is pretty foolproof.
这篇关于检查VBA中列中是否存在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!