Question

I need to find the max value in a column by EXCEL 2012 VBA. Some cells have "#VALUE!". My code does not work.

Sub find_max()
   Dim rng As Range
   Dim dblMax As Double
  dblMax = 0
  Set rng = Range("A2:A11")
  For Each cell In rng
     If (cell.Value <> "#VALUE!") Then    // error ! type mismatch
         If dblMax < CDbl(cell.Value) Then
             dblMax = CDbl(cell.Value)
         End If
    End If
 Next cell
 MsgBox dblMax
End Sub

I also need to print the cell location (mark it with a color) with the max value.

Any help would be appreciated.

Was it helpful?

Solution

If your range has constants, use

application.WorksheetFunction.Max(range("B6:C13").SpecialCells(xlcelltypeconstants,xlNumbers ))

if it has formulas, use

application.WorksheetFunction.Max(range("B6:C13").SpecialCells(xlcelltypeformulas,xlNumbers ))

For the range where it's found, .Find should work fine:

Sub find_max()


 Dim rng As Range
   Dim dblMax As Double, rgMax As Range

    Set rng = Range("A2:A11")

    dblMax = Application.WorksheetFunction.Max(rng.SpecialCells(xlCellTypeFormulas, xlNumbers))

    Set rgMax = rng.Find(dblMax, , xlValues, xlWhole)

 MsgBox rgMax.Address & ": " & dblMax

End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top