简体   繁体   English

Excel VBA填充到上一列中使用的最后一行

[英]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. 我找到的所有答案都使用Range命令,但是我找不到如何使用colNum变量来实现的。

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. Range.Offset属性是对此的理想解决方案。 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. .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 :)). 它在第一行中查找一个单元格“ Bdate”,如果找到它,则在右侧插入列(如果没有,则会出现错误:)。 After this, it inserts a formula 1+1 for each cell, which is to the right. 此后,它为每个单元格在右侧插入一个公式1+1 Anyhow, something like this: 无论如何,是这样的:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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