[英]Find cell before last that is greater than 0
我在 VBA 中有以下代碼來查找大於 0 的范圍內的最后一個單元格:
Set myRange = .Range(.Cells(1, 14), .Cells(1, 23))
count = 0 'Counter
For Each cll In myRange
If cll.Value > 0 Then
count = count + 1
NoZeroDir = cll.Address
End If
Next
它獲取該范圍內最后一個大於 0 的單元格的地址。 但是,在最后一個之前,我如何從大於 0 的單元格中獲取地址?
我正在考慮使用偏移量,但這樣我會在最后一個> 0之前獲得單元格,但這個單元格不能> 0。
為了說明這一點,作為一個例子,我有:
2 3 5 0 1 7 0 8 1 0 1
最后一個單元格 > 0 的地址將是 (1,11),但我想要那個 > 0 之前的單元格,即 (1,9),而不是 (1,10),因為這是 0。
查找倒數第二個>0
的數字
Option Explicit
Public Sub FindSecondLastValueGreaterZero()
Dim MyRange As Range
Set MyRange = Range("A1:K1")
Const MAXSKIPS As Long = 1 ' skip 1 number that is >0
Dim Skips As Long
Dim iCol As Long
For iCol = MyRange.Columns.Count To 1 Step -1
If MyRange(1, iCol).Value > 0 And Skips < MAXSKIPS Then
Skips = Skips + 1
ElseIf MyRange(1, iCol).Value > 0 Then
Debug.Print "Found at: " & MyRange(1, iCol).Address
Exit For
End If
Next iCol
End Sub
這將在 K 循環中向后開始,直到找到0
然后繼續執行直到跳過>0
為1
並打印地址I1
作為結果。
由於這從右到左向后循環,它應該比您的代碼更快地找到結果(在大多數情況下)。
使用 Worksheetfunction Filter()
的替代方法(與 MS 365 相比)
基於較新的 WorksheetFunction Filter()
(自 MS/Excel 365 版本起可用)並使用 OP 的范圍指示
=FILTER(COLUMN(A1:K1),A1:K1>0)
您可以通過對廣義公式模式的評估從大於零 (0) 的單元格中獲取列號數組。
如果您得到至少兩列剩余的列(即上限UBound() > 1
),您將通過i = cols(UBound(cols) - 1)
獲得所需的倒數第二列編號,並可以通過Cells(1, i).Address
) 將其轉換為地址Cells(1, i).Address
。
Public Sub SecondLastValGreaterZero()
'a) construct formula to evaluate
Const FormulaPattern As String = "=FILTER(COLUMN($),$>0)"
Dim rng As Range
Set rng = Sheet1.Range("A1:K1") ' << change to your needs
Dim myFormula As String
myFormula = Replace(FormulaPattern, "$", rng.Address(False, False, external:=True))
'b) get tabular column numbers via Evaluate
Dim cols As Variant
cols = Evaluate(myFormula)
'c) get the 2nd last column number of cell values > 0
Dim i As Long
If Not IsError(cols) Then
If UBound(cols) > 1 Then i = cols(UBound(cols) - 1)
End If
'd) display result
If i > 0 Then
Debug.Print "Found at column #" & i & ": " & Cells(1, i).Address
Else
Debug.Print "Invalid column number " & CStr(i)
End If
End Sub
VB 編輯器立即 window 中的示例結果
Found at column #9: $I$1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.