问题
I am using the below code:
Sub Evaluation_Formula()
Dim i As Long
With Worksheets("Sheet1")
i = .Evaluate("MIN(IF((LEFT($B$1:$B$89,5)*1)=C1,$B$1:$B$89,""""))")
.Range("F3").Value2 = i
End With
End Sub
However, the formula is limited to B89, how can I use Last Row in Column B in the formula ?
回答1:
For all intents and purposes you are really only concerned with the last number in column B, not specifically the last row. To do that in a worksheet formula you would use something like this array formula.
=MIN(IF(--LEFT(B1:INDEX(B:B, MATCH(1E+99,B:B )),5)=C1, B1:INDEX(B:B, MATCH(1E+99,B:B))))
That can translate into your VBA Evaluate method like the following.
Sub Evaluation_Formula()
Dim i As Long
With Worksheets("Sheet1")
i = .Evaluate("MIN(IF(--LEFT(B1:INDEX(B:B, MATCH(1E+99,B:B )),5)=C1, B1:INDEX(B:B, MATCH(1E+99,B:B))))")
.Range("F3").Value2 = i
End With
End Sub
The double unary (aka double-minus or --
) does the same job as multiplying the text result from the LEFT function by 1. There is no need to pass a zero-length string (e.g. ""
) in as the FALSE is sufficient for non-matches in the IF function. Since you are evaluating text into a formula, there is no need for the $
absolute markers.
Keep the .
in .Evaluate
or add the worksheet name to the cell references in the formula. Without it you run the risk of evaluating another worksheet's B1:B89 and C1 cells if Sheet1 does not hold the workbook's ActiveSheet property.
回答2:
I guess this will post proper code:
Sub Evaluation_Formula_w_LR()
Dim i As Long
Dim LR As Long
With Worksheets("Sheet1")
LR = .Cells(.Rows.Count, 2).End(xlUp).Row
i = Evaluate("MIN(IF((LEFT($B$1:$B$" & LR & ",5)*1)=C1,$B$1:$B$" & LR & ",""""))")
.Range("F10").Value2 = i
End With
End Sub
来源:https://stackoverflow.com/questions/34294086/last-row-in-excel-vba-evaluate