Zac*_*ach 1 excel vba excel-vba
我有一张excel表,其中单元格A1-C20 = =INT(RAND()*10)
.这是我的数据范围.单元格E1 = 1,E2 = 2,E3 = 3等.这些是我想要找到的值.我设置单元格F1 = =MATCH(E1,A:C,0)
,F2 = =MATCH(E1,A:C,0)
等.
但是,所有MATCH
函数都返回#N/A
,因为输入范围是多维的.如何测试给定值(1,2,3,4等)是否存在于多维范围(A1-C20)?
/ edit: 这个功能有效,但不仅仅是我需要的.有没有办法让它返回TRUE或FALSE,具体取决于查找值是否在范围内?
Function OzgridLookup(Find_Val As Variant, Occurrence As Long, Table_Range As Range, _
Offset_Cols As Long, Optional Column_Lookin As Long, Optional Row_Offset As Long) As Variant
Dim lLoop As Long
Dim FoundCell As Range
If Column_Lookin = 0 Then 'No column # specified
With Table_Range
'Top left cell has Find_Val & Occurrence is 1
If Table_Range.Cells(1, 1) = Find_Val And Occurrence = 1 Then
OzgridLookup = .Cells(1, 1)(1, Offset_Cols + 1)
Exit Function 'All done :)
Else 'No column # specified so search all for _
nth Occurrence reading left to right
Set FoundCell = .Cells(1, 1) 'Set cell variable for Find start
For lLoop = 1 To Occurrence 'Loop as many times as Occurrences _
and each time Set "FoundCell" to start next Find from
Set FoundCell = _
Table_Range.Find(What:=Find_Val, After:=FoundCell, _
LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlRows, SearchDirection:=xlNext)
Next lLoop
End If
End With
Else 'column # specified
With Table_Range.Columns(Column_Lookin) 'Work with column # specified
Set FoundCell = .Cells(1, 1) 'Set cell variable for Find start
For lLoop = 1 To Occurrence 'Loop as many times as Occurrences _
and each time Set "FoundCell" to start next Find from
Set FoundCell = _
Table_Range.Find(What:=Find_Val, After:=FoundCell, _
LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlRows, SearchDirection:=xlNext)
Next lLoop
End With
End If
OzgridLookup = FoundCell.Offset(Row_Offset, Offset_Cols)
End Function
Run Code Online (Sandbox Code Playgroud)
您可以使用COUNTIF执行此操作,因为您只想知道该数字是否存在(而不是其位置).
=COUNTIF(A:C,E1)>0
Run Code Online (Sandbox Code Playgroud)
如果存在则返回"TRUE",如果不存在则返回"FALSE".
只是为了好玩,这是一个工作表函数解决方案,它返回与查找值匹配的单元格地址.它使用的事实是您只搜索3列.
=IF(ISERROR(MATCH(E1,A:A,0)),IF(ISERROR(MATCH(E1,B:B,0)),IF(ISERROR(MATCH(E1,C:C,0)),"Not found.","C"&MATCH(E1,C:C,0)),"B"&MATCH(E1,B:B,0)),"A"&MATCH(E1,A:A,0))
Run Code Online (Sandbox Code Playgroud)
我想我也会投入一个VBA解决方案,可以在(连续)范围内返回匹配位置.它从左到右一次查看一列,并返回找到的第一个匹配的地址.
Public Function MDMATCH(srchfor As String, lookin As Range) As String
Application.Volatile
Dim RngArray() As Variant
Dim topleft As String
Dim tmpval As String
topleft = lookin.Address
topleft = Left(topleft, InStr(topleft, ":") - 1)
tmpval = "Not found."
RngArray = lookin
For i = 1 To UBound(RngArray, 2)
If tmpval = "Not found." Then
For j = 1 To UBound(RngArray, 1)
If RngArray(j, i) = srchfor Then
tmpval = Range(topleft).Offset(j - 1, i - 1).Address
Exit For
End If
Next j
Else
Exit For
End If
Next i
MDMATCH = tmpval
End Function
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4716 次 |
最近记录: |