Search code examples
vbaautofill

How to autofill a range in VBA with differing variables


I am trying to figure out how to autofill a specific range of cells based on already defined data in the same row. My task is more complex, but a simplification of the step can be seen in the code below. What I want to achieve is:

  1. Define a range where I want to output my values
  2. Multiply two values in the same row of the selected range cell (to its left), and output this number in the currently selected range cell. To do this, one of the numbers to be multiplied will be dependant on a string also in the row (which describes its type).
  3. Loop through the defined range and repeat the calculation on each row.

My current code is as follows and outputs a "application defined or object defined error".

Any help would be much appreciated.

For a = Range("P12") To Range("P33") 'Range of cells I want to fill.
    If Cells(a, -10).Value = "B" 'If the cell 10 to the left of our "a" value is = "B".
    Then c = Cells(a, -10).Value * Worksheets("LCI").Range("D4").Value 'Then new variable "c" = (cell 9 to left of a) * (number from another sheet containing a database)
            
    Cells(a).Value = c 'Update value of selected range cell to contain c which we calculated.
Next 'Repeat for all rows in range.

Solution

  • You are close.

    1. You need to think of a as a cell or Range object. That variable is the cell itself which has properties like a.row and a.column that describe its location on the sheet in which it lives. When you say Cells(a, -10) you are saying "On the Activesheet I want a Cell where the row is a, and where the column has the number -10". There is no row a (as a is a range/cell object and because you didn't specify which property of a you are wanting here it will default to a.value which is probably nothing) and there is no column -10 on the Activesheet.

    2. Your loop is defined incorrectly. You can use a For Each loop to loop through cells in a range.

    Instead:

    For Each a In Range("P12:P33")
        'clear `c` each loop 
        c=0
        If a.Offset(,-10).Value = "B" Then 'start at cell `a` and move back 10 columns and grab the value
            c = a.Offset(, -10).Value * Worksheets("LCI").Range("D4").Value
        End If
        a.Value = c
    Next a