Question

I need to do some calculations for each cell in two aligned columns in EXCEL 2010 by VBA on Win7. Write the result in a cell of another column.

My code:

   Set result_rng = Range("H2:H10")
   Set aRng = Range("C2:C10")
   Set bRng = Range("F2:F10")
   For Each aCell, bCell, cCell In aRng, bRng, result_rng   // **error here** 
      cEll.Value = Cdl(aCell.Value) - Cdl(b.Cell.Value)
   Next aCell

I also need to check wether F column is "NULL", if yes, I will not do calculation and just update a counter.

update new error of caling a sub

find_max rng1:=rng  // error !!! ByRef argu mismatch 

Sub find_max(ByRef rng1 As Range)
 Dim dblM As Double
 dblM = -9E+307
 Dim maxCellAddress As String
 For Each Cell In rng
    If IsNumeric(c) Then
           If dblMax < CDbl(Cell.Value) And Cell.Value <> "" Then
               dblM = CDbl(Cell.Value)
               maxCellAddress = (Cell.Address)
           End If
    End If
 Next Cell
 End Sub

Any help would be appreciated.

Was it helpful?

Solution

UPDATE 1

Try this one:

Sub test()
    Dim rng As Range, c As Range
    Set rng = Range("C2:C10")

    For Each c In rng
        If c.Offset(0, 3).Value <> "NULL" Then
            c.Offset(0, 5).Value = c.Value - c.Offset(0, 3).Value
        End If
    Next c
End Sub

where c.Offset(0, 3) means offset to the right on 3 columns, i.e. if c refers to cell in column C, then c.Offset(0, 3) gives you corresponding value from column F and c.Offset(0, 5) gives you corresponding value from column H.

If it seems too tricky, you can use this one instead:

Range("H" & c.Row).Value = c.Value - Range("F" & c.Row).Value

UPDATE 2

Sub test()
    Dim result_rng As Range, c As Range
    Dim dblM As Double
    Dim maxCellAddress As String

    Set result_rng = Range("H2:H10")

    dblM = -9E+307

    For Each c In result_rng
        If IsNumeric(c) Then
            If dblM < CDbl(c.Value) And c.Value <> "" Then
                dblM = CDbl(c.Value)
                maxCellAddress = c.Address
            End If
        End If
    Next c
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top