首页 文章

lastRow&lastRow2使用Excel中的宏动态地将公式添加到表中

提问于
浏览
0

我在Excel宏中遵循VBA代码:

Sub calcular_datos()

' ************************************************************************************************
' Aplicamos fórmulas a las celdas de Datos
' ************************************************************************************************

    With Sheets("Datos")
        lastRow = .Cells(.Rows.Count, "AC").End(xlUp).Row
        lastRow2 = .Cells(.Rows.Count, "AD").End(xlUp).Row + 1
        .Range("AD" & lastRow2 & ":AD" & lastRow).Formula = _
            "=IF([@[ga:visits]]=0,0,1)"
    End With
With Excel.Application
        .ScreenUpdating = True
        .Calculation = Excel.xlCalculationAutomatic
        .EnableEvents = True
End With

End Sub

代码的目的是动态地将公式集成到添加到表中的新行 . 因为文件会定期更新并且会有很多行和计算单元格,所以我不想让表格中的公式(它会自动整合公式),而是每次运行宏时添加它然后复制并粘贴值 .

lastRow确定最后一个文本列中的行数(计算列开始之前的最后一行) .

lastRow2确定第一个空白单元格的位置,并告诉Excel应该从哪里开始添加公式 .

例如:如果lastRow返回14922和lastRow2 12352,则宏应将公式添加到单元格AD12352:AD14922中 .

Excel不报告错误,因此我认为代码完全不错 . 但是添加了任何公式 .

桌上有什么特别之处吗?

1 回答

  • 0

    您的评论是正确的,找到您需要的第一个空白单元格:

    Range("AD1").End(xlDown).Offset(1, 0).Select
    

    这会使你的宏:

    Sub calcular_datos()
    
    ' ************************************************************************************************
    ' Aplicamos fórmulas a las celdas de Datos
    ' ************************************************************************************************
    
        With Sheets("Datos")
            lastRow = .Cells(.Rows.Count, "AC").End(xlUp).Row
            lastRow2 = Range("AD1").End(xlDown).Offset(2, 0).Select 
            .Range("AD" & lastRow2 & ":AD" & lastRow).Formula = _
                "=IF([@[ga:visits]]=0,0,1)"
        End With
    With Excel.Application
            .ScreenUpdating = True
            .Calculation = Excel.xlCalculationAutomatic
            .EnableEvents = True
    End With
    
    End Sub
    

    Offset(2,0) 将选择空白单元格下面的单元格 . 我假设你想从你的_1345222中得到这个 . 要选择空白单元格,请使用 Offset(1,0)

    希望它能做到这一点!

相关问题