简体   繁体   中英

Is there an excel/VBA formula to find the min/max/average etc of a range of cells that varies in length?

I would like to know if there is a way to find something like the min/max/average etc of a range of cells within a spreadsheet, when I don't know where the end of the range is (I already know one way but wondering if there is another)?

Within my macro I currently use the following:

Raw1.Range("H4").Value = Application.WorksheetFunction.Max(Range(Sheets("Raw").Range("A3"), Sheets("Raw").Range("A3").End(xlDown)))

I would like to use different then this, because this way gives "one of value" each time the code is run...I want the value of H4 to change each time the values of A3 changes without having to run the macro...So more like a formula

I was thinking something like below:

Raw1.Range("H3").Value = "= Min((A3:A & Range.End(xlDown).Row))"

I have tried various things but can not get it to work?

Does anyone know if this is possible?

Since you don't want actively to have to run a macro, the suggestion below is coded in the Worksheet_Change() event procedure :

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect(Range("A:A"), Target) Is Nothing Then
        If Target.Cells.Count > 1 Then Exit Sub
        Dim lastCell As Long, pos As Long, formulaCell As Range
        Set formulaCell = Range("H4")
        lastCell = Cells(Rows.Count, 1).End(xlUp).Row
        pos = InStr(1, formulaCell.Formula, "(") - 1
        formulaCell.Formula = Left(formulaCell.Formula, pos) & "(A2:A" & lastCell & ")"
    End If
End Sub

it is premised on the examples in your OP, in that the cell in question contains a simple formula (ie the address of the referenced cells comes after the 1st ( of the existing formula, and there is nothing, other than the ) after this reference), the range reference for which the event procedure will update whenever a change in column A is detected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM