slyclam
slyclam

Reputation: 290

vb excel drag formula for variable number of rows

I have a excel sheet which I am populating using a VB program. The output sheet can have variable number of rows but has 6 columns (A:F). Now I want the column G to have hex2dec of all the rows in column A. Here's an example: Say column A has 400 rows (A1:A400) then I want G1:G400 to have values HEX2DEC(A1:A400). But this is just an example the rows can vary. I have this code so far:

Sub DataMod()

Dim i As Long, R3 As Long
R3 = 1

For i = 1 To sheet.UsedRange.Rows.Count
sheet.Cells(i, 7).Formula = "=HEX2DEC" & sheet.Cells(R3, 1)
R3 = R3 + 1
Next i

End Sub

But it's not working.

Upvotes: 0

Views: 500

Answers (2)

MikeD
MikeD

Reputation: 8941

Review your HEX2DEC formula string

  • it doesn't include the necessary ()
  • the Cells() would return the value of the target cell, not its address (i.e. the result would be =HEX2DEC(1234) instead of =HEX2DEC(A1) - which may or may not be a problem
  • you could use variable i instead of R3, they both increment from the same starting point at the same increment

I recommend to use FormulaR1C1, you do not have variants there

Sub DataMod()
Dim C As Range

    For Each C In ActiveSheet.UsedRange.Columns(1).Cells
        C(1, 7).FormulaR1C1 = "=HEX2DEC(RC[-6])"
    Next C

End Sub

The danger of UsedRange is that it might include any header rows, so you might want to get around this by selecting the input range manually before you fire your Sub() and work with the Selection object, e.g.

For Each C In Selection.Columns(1).Cells

Upvotes: 1

John Bustos
John Bustos

Reputation: 19544

Try This:

Sub DataMod()

   ' Get the number of rows used in Column A:
   Dim NumRows as Long
   NumRows = Range("A1").End(xlDown).Row

   ' Put the formulas in Column G all at once:
   Range("G1:G" & NumRows).FormulaR1C1 = "=Hex2Dec(RC1)"    

End Sub

Upvotes: 1

Related Questions