[英]Excel vba: Find function with additional conditions
我有这张表,应该只知道其ID,才能获得类别“ 3”的每个元素的“适用性”。
示例:findAppl(0709_2014)=“是”
这是我的代码:
Function findAppl(id As Range)
Set t1 = Sheets("Sheet1").Range("Table1")
Set ids = Sheets("Sheet1").Range("ids")
Set id = ids.find(id.value, LookIn:=xlValues)
If Not IsEmpty(table.Rows(id.Row - 1).value) Then
findAppl = t1.Rows(id.Row - 1).value
End if
End Function
问题是find函数总是返回给定id的第一个范围,该范围对应于category = 2的范围。 为了解决这个问题,我在find函数之后设置了if条件,但是代码不再起作用,我还使用了'After:='选项,但是它似乎无法正常工作
PS的适用性不取决于每个ID的类别,我们可以拥有一两个类别
这是用于循环的代码。 如果行数不多,可以使用此选项...
Sub Test()
lrow = Sheets("Sheet1").Range("A65536").End(xlUp)
For cel = 1 To lrow
If Cells(cel, 3) = "yes" And Cells(cel, 2) = 3 Then
MsgBox Cells(cel, 1)
End If
Next
End Sub
请找到使用find函数的简单循环,而不是遍历所有单元格...希望这对您有用...
Sub test()
With Worksheets(1).Range("B1:B500")
Set c = .Find(2, LookIn:=xlValues) 'give the category value here ex:2
If Not c Is Nothing Then
If Range(c.Address).Offset(0, 1).Value = "yes" Then
firstAddress = c.Address
Do
MsgBox Range(c.Address).Offset(0, -1)
Set c = .FindNext(c)
If c Is Nothing Then Exit Do
Loop While Not c Is Nothing And (c.Address <> firstAddress)
End If
End If
End With
End Sub
我不知道您所说的“得到”是什么意思。 但是您当然可以使用自动过滤器返回所需的值。 以下代码使用您的数据,将结果放在表旁边。 您可以将其放在另一个工作表,另一个位置,VBA阵列中或任何位置:。 显然,您需要一个输入例程来查找ID和类别。
Option Explicit
Sub FindApp()
Dim WS As Worksheet
Const Category As Long = 2
Const ID As String = "0709_2014"
Dim rTable As Range
Set WS = ActiveSheet
Set rTable = Range("Table1")
rTable.AutoFilter field:=1, Criteria1:=ID
rTable.AutoFilter 2, Category
Range("g1:I1").EntireColumn.Clear
rTable.Rows(0).Copy Range("g1")
rTable.SpecialCells(xlCellTypeVisible).Copy Range("g2")
rTable.AutoFilter 'Turn off autofilter
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.