Search code examples
macrosautofill

How do I get this formula to fill in only blank cells?


I'm trying to autofill only blank cells with this formula on the range that I've set.

I've tested adding cells.specialcells(xlCellTypeBlanks) but it is not working.

Sub test()

    Dim lastRw As Long
    Dim Rng As Range

    lastRw = Cells(Rows.Count, "P").End(xlUp).Row
    Set Rng = Range("Q1:Q" & lastRw)
    Rng = "=IFERROR(VLOOKUP(RC[-1],R1C1:R1C14,14,FALSE),"""")"
    Rng.Value = Rng.Value

End Sub

I want it to be able to paste the formula only on blank cells.


Solution

  • Welcome to SO. I'd suggest that for the future make sure you add appropriate tags for the specific language. This is for me clearly VB6 (vba), but for others it might be unclear. A clear tag will help receive answers.

    I'll try to keep it simple. An idea:

    1. Find all cells that should potentially be fileld
    2. Go through them and figure out if they are empty
    3. Either fill cells 1-by-1 or redefine the range to only include the none empty cells.

    I'll go with '1-by-1' using a for loop.

    sub test()
    
        dim fillRange as range
        dim lastRow as long
        dim i as range 'instead of cell / cells
    
        lastRow = activesheet.usedrange.rows.count 'Alternative for finding last row
        set fillRange = range("Q1:Q" & lastRow)
        for each i in fillRange 'i will be 1 cell in filLRange at a time
            'check if the current cell is empty (="") or contains nothing (isnull). If it does, insert formula
            if i = "" or isnull(i) then i = "=IFERROR(VLOOKUP(RC[-1],R1C1:R1C14,14,FALSE),"""")"
        next i
        calculate 'Make sure the formula takes effect
    
    end sub
    

    There might be a few spelling errors, as i'm writing it off the top of my head. (Especially the row count, just use your own if it fails. i as cell might have to be i as cells as well.) But it should do the trick.