简体   繁体   中英

Excel VBA filldown to last row used in previous column

I've been looking all afternoon for the answer to this.

the code works as I want (after lots of time researching, I'm rather green to this) except I'd like to fill down to the last row used in previous column rather than the whole sheet.

I can't give exact referece to the previous column because it isn't always in the same place hence why I am looking it up and doing everything based on that look up result.

All answers I have found use the Range command but I can't find how to use my colNum variable for that.

Sub cndob()
'
' cndob change dob
'
' find column number and select
'
    Dim colNum As Integer
    colNum = WorksheetFunction.Match("BDate", Range("1:1"), 0)
    Columns(colNum + 1).Select

' insert column right

    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

' formula fill down
    Cells(2, colNum + 1).Select
    ActiveCell.FormulaR1C1 = "=RIGHT(RC[-1],2)&CHAR(47)&MID(RC[-1],5,2)&CHAR(47)&LEFT(RC[-1],4)"
    Range(ActiveCell, ActiveCell.End(xlDown)).FillDown

Please help

The Range.Offset property is the perfect solution for this. Change your last line of code to:

Range(ActiveCell, ActiveCell.Offset(0, -1).End(xlDown)).FillDown

The first argument to .Offset is the row offset. That we don't want to change. The column offset, though, is set to one to the left of the active column.

I am not sure what exactly do you want to do, but from what I understood, something like this will do the job:

Option Explicit

Sub TestMe()

    Dim colNum      As Long
    Dim sht         As Worksheet
    Dim rng         As Range

    Set sht = ActiveSheet

    colNum = WorksheetFunction.Match("BDate", Range("1:1"), 0)

    Set rng = sht.Cells(1, colNum)

    rng.Offset(0, 1).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    rng.Offset(0, 1).FormulaR1C1 = "=1+1"

    Range(rng, rng.End(xlDown)).Offset(0, 1).FillDown

End Sub

What it does? It looks for a cell "Bdate" on the first row and if it finds it, it inserts column to the right (if not, it gives an error :)). After this, it inserts a formula 1+1 for each cell, which is to the right. Anyhow, something like this:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM