首页 > 解决方案 > 如何在 VBA 中的两个变量点之间创建一个范围?

问题描述

我正在尝试编写自动化某些东西的代码:我有一个数据表,我需要在其中添加一列,然后将一个总和放入其中,一直到数据的底行,不再赘述。我知道如何将底行定义为变量;但是如果我输入数据的列也可以变化呢?在我的示例中,我想要进行求和的列始终位于标题为“16”的列的左侧。它总是从第 2 行开始,但并不总是 O 列。例如,它可能是 P 列或 Q 列。

Sub enter_column_and_add_calculations()

    Dim NBottomrow

    Call find_bottom_row
    NBottomrow = ActiveCell.Row
'find column entitled '16':
    Range("A1").Select
    Cells.Find(What:="16", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
        xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext,         
    MatchCase:=False _
        , SearchFormat:=False).Activate
'insert new column to the left:
    Selection.EntireColumn.Insert , CopyOrigin:=xlFormatFromLeftOrAbove
'insert text in the cell:
    ActiveCell.FormulaR1C1 = "OOT Debt"
'offset one cell below:
    ActiveCell.Offset(1, 0).Range("A1").Select
'i'm now in the cell i want my range to start at. In this example it's cell O2, but it often varies:

    ActiveCell.FormulaR1C1 = "=SUM(RC[1]:RC[5])"
    Selection.AutoFill Destination:=Range("O2:O" & NBottomrow)

End Sub

Private Sub find_bottom_row()

    Range("A1").Select
    Selection.End(xlDown).Select

End Sub

非常感谢您的帮助 :-)

标签: excelvba

解决方案


尝试,

Sub enter_column_and_add_calculations()

    dim m as variant, lr as long

    with worksheets("sheet1")

        m = application.match(16, .rows(1), 0)
        if iserror(m) then exit sub

        lr = .cells(.rows.count, m).end(xlup).row

        .cells(lr+1, m).formula = "=sum(" & .range(.cells(2, m), .cells(lr, m)).address(0,0) & ")"

    end with

end sub

推荐阅读