【问题标题】:Recorded Excel macro with countIf function with lastrow使用 lastrow 的 countIf 函数记录 Excel 宏
【发布时间】:2016-06-09 06:56:15
【问题描述】:

我的问题如下。我正在为范围是动态的工作表录制宏。

公式为=CountIF(A:A;A2)并记录下来:

Range("M2").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(C[-12],RC[-12])"
Range("M2").Select
Selection.AutoFill Destination:=Range("M2:M4333"), Type:=xlFillDefault
Range("M2:M4333").Select

由于行是动态的,我想将每个公式都结束到最后一行。我在这里搜索答案并将这个函数复制到宏的开头。

Function GetLastRow(sht As Worksheet, col As String) As Integer
GetLastRow = sht.Range(col & CStr(sht.Rows.Count)).End(xlUp).row

现在我正在尝试将其调用为原始录制的宏

Range("M2").Select
Range(Selection, Selection.End(xlDown)).Select
Formula1 = "=COUNTIF(A:A" & GetLastRow(Sheets("Sheet1"), "A") & ",A2))"

我将其更改为看起来像是在工作表中复制的公式,而不是像它记录的那样。我将不胜感激。如果 lastrow 函数与记录的公式一起使用会更好,因为我还有很多其他公式会遇到同样的问题。

【问题讨论】:

标签: excel macros vba


【解决方案1】:

您希望将 M 列从第 2 行向下填充到 M 列中与 A 列中最后一个填充单元格相接的行。使用 Range.Offset propertyRange.Address property 获取要在 COUNTIF function 中使用的正确地址.

With Worksheets("Sheet1")  'you should know what worksheet you are on!
    With .Range("M2:M" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        .FormulaR1C1 = "=COUNTIF(" & .Offset(0, -12).Address(ReferenceStyle:=xlR1C1) & ", RC1)"
    End With
End With

        

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多