我想在VBA中创建一个宏,我输入“ Cliente”编号,然后在此表中找到与“ Cliente”编号匹配的最高“ Aditivo”编号。
例如:
如果我输入“ 5”,则应该返回“ 6” 如果输入“ 3”,则应返回“ 5”
答案 0 :(得分:2)
正如其他人所说,您可以摆脱工作表公式。但是如果需要VBA,那么...无论如何都要使用工作表公式:
尝试一下:
Sub findHighestNo()
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Sheet1")
Dim lRow As Long
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
Dim max_rng As Range
Set max_rng = ws.Range("B1:B" & lRow)
Dim cliente: cliente = InputBox("Select your cliente ID")
Dim Result
' If IsNumeric(cliente) Then
'
' Result = WorksheetFunction.MaxIfs(max_rng, max_rng.Offset(, -1), cliente)
' MsgBox Result, vbInformation, "Max result"
' Else
' MsgBox "Input a number instead!"
' End If
Dim arrData As Variant
arrData = max_rng.Offset(, -1).Resize(, 2)
Dim arrTmp() As Long: ReDim arrTmp(1 To lRow)
If IsNumeric(cliente) Then
Dim R As Long
For R = LBound(arrData) To UBound(arrData)
If arrData(R, 1) = CLng(cliente) Then
arrTmp(R) = arrData(R, 2)
End If
Next R
Result = WorksheetFunction.Max(arrTmp)
MsgBox Result, vbInformation, "Max result"
Else
MsgBox "Input a number instead!"
End If
End Sub
编辑:为MAX
添加了一种替代方法,因为MAXIFS
仅在Office 365 / 2019中可用。