excel 使用动态范围进行自动填充

n3schb8v  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(131)

我想添加一个公式到一个单元格,然后自动填充所有的方式下降到lr。
目前我正在使用:

lr = Cells.Find("*", Cells(1,1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row
Dim header as range
Set header = range("A1:AA1")

' The Group column has empty cells. It just has header as Group.
' This code finds the column header Group for me and puts formula in 1 cell under it. This part is fine.
header.Find("Group").Offset(1,0).FormulaR1C1 = "=left(rc[-1],4)"

' Now I need to autofill that formula all the way down to lr
' I'm currently using this
header.Find("Group").Offset(1,0).Autofill Range ("B2:B" & lr)

我不想使用“B2:B”作为集团列可以在任何其他地方。我希望它是更动态。
是否有办法更改“B2:B”,使其查找Group header并自动填充1个单元格,直至lr?

krcsximq

krcsximq1#

在标题下方填充

Option Explicit

Sub FillBelowHeader()
    
    Const hRow As Long = 1
    Const Header As String = "Group"
    Const Formula As String = "=LEFT(RC[-1],4)"
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    ' If the worksheet is filtered, the Find method will fail.
    If ws.AutoFilterMode Then ws.AutoFilterMode = False 
    
    Dim hrg As Range: Set hrg = ws.Rows(hRow)
    
    ' To find the index of the first occurrence of a string
    ' in a one-row or one-column range, you can use 'Application.Match'.
    ' It is case-insensitive.
    Dim hCol As Variant: hCol = Application.Match(Header, hrg, 0)
    If IsError(hCol) Then ' check if there was no match
        MsgBox "Header not found.", vbCritical
        Exit Sub
    End If
    
    Dim lRow As Long
    lRow = ws.UsedRange.Find("*", , xlFormulas, , xlByRows, xlPrevious).Row
    If lRow = hRow Then ' check if no data below headers
        MsgBox "No data below headers.", vbCritical
        Exit Sub
    End If
    
    hrg.Cells(hCol).Resize(lRow - hRow).Offset(1).FormulaR1C1 = Formula
    ' e.g. hCol is 5 (column 'E') and lRow is 10:
    ' ws.Range("A1:XFD1").Cells(5).Address(0, 0) = "E1"
    ' ws.Range("E1").Resize(10 - 1).Address(0, 0) = "E1:E9"
    ' ws.Range("E1:E9").Offset(1).Address(0, 0) = "E2:E10"
    
End Sub

相关问题