VBA行位置
我目前正在使用由其他人编译的Excel工作表(所以我不能删除或添加列)。 我正在为工作表的用户创build与VBA的接口。 在其中一个选项卡中,有三列我希望能够find在前两列中find两个参数的行,这样我可以input一个数字。 作为参考,我正在使用下拉选项为用户select前两个参数,并在第三个input框中input。 需要find两个input相匹配的位置,并且能够在不同的列中分配相同的行。
例如(find梨绿色的行)[答案是第9行,并用此input第9行中的input]
Fruit Color Amount Apple Red Apple Green Apple Blue Orange Red Orange Green Orange Blue Pear Red Pear Green Pear Blue
这是一个起点:
Function FindOccurence(Fruit As String, Color As String) As Long Dim WS As Worksheet Set WS = ActiveSheet Dim L As Long L = WS.Cells(WS.Rows.Count, 1).End(xlUp).Row For Each Cell In WS.Range("A2:A" & L) If Cell.Value = Fruit And Cell.Offset(0, 1).Value = Color Then FindOccurence = Replace(Cell.Address(0, 0), "A", "") Exit Function End If FindOccurence = 0 Next Cell End Function Sub Main() Debug.Print (FindOccurence("Apple", "Green")) End Sub
要小心,这发现你第一次出现 。
这是另一种方法。 这是一个起点,可以调整以find您的工作表中的所有事件。 这使用.findnext
属性
Sub FindValue() Dim ws As Worksheet Dim NoRow As Integer Dim rng As Range Dim firstaddress As String Dim c Set ws = ThisWorkbook.Sheets("Fruit") ' Change to your sheet name With ws NoRow = .Range("A" & .Rows.Count).End(xlUp).Row Set rng = .Range("A2:A" & NoRow) With rng Set c = .Find("Pear", LookIn:=xlValues) ' Change Pear to your test value If Not c Is Nothing Then firstAddress = c.Address Do If c.Offset(0, 1) = "Green" Then ' Change this to the second cell value MsgBox c.Address End If Set c = .FindNext(c) Loop While Not c Is Nothing And c.Address <> firstAddress End If End With End With End Sub
这应该会更快,然后使用for循环