excel vba根据我的表格大小自动计算公式

标签 excel vba range formula rows

我需要知道是否可以自动根据列使用范围公式。 这是我原来的代码:

    Sub Formulas_new_sheet()
' Cambiar los rangos acorde al numero de filas usadas

    ' Formula Costo unitario
    Range("D2").Select
    ActiveCell.Formula = "=C2/B2"
    'ActiveCell.FormulaR1C1 = "=RC[-1]/RC[-2]"
    Range("D2").Select
    Selection.AutoFill Destination:=Range("D2:D7"), Type:=xlFillDefault
    Range("D2:D7").Select
    '________________________
    ' Formula de extra / ganancia
    Range("E2").Select
    ' Variar según el porcentaje de ganancia que se busca
     ' recordando .55 = 55% , .30 = 30%
    ActiveCell.Formula = "=D2+(D2*0.55)"
    Selection.AutoFill Destination:=Range("E2:E7"), Type:=xlFillDefault
    Range("E2:E7").Select
    'Formula para precio de venta c/u
    Range("G2").Select
    ActiveCell.Formula = "=E2+F2"
    Range("G2").Select
    Selection.AutoFill Destination:=Range("G2:G7"), Type:=xlFillDefault
    Range("G2:G7").Select
End Sub

然后我在论坛上得到了帮助,我得到了这个:

    Sub Macro3()
TableLastRow = 15
Range("D2:D" & TableLastRow).FormulaR1C1 = "=RC[-1]/RC[-2]"
Range("E2:E" & TableLastRow).FormulaR1C1 = "=RC[-1]+(RC[-1]*0.55)"
Range("G2:G" & TableLastRow).FormulaR1C1 = "=RC[-2]+RC[-1]"
End Sub

但现在我想知道是否有进一步自动化的方法。每次我执行不同的表格大小行数时,不要更改TableLastRow 谢谢

最佳答案

编写列公式

  • 由于您没有错误处理功能,因此可以得出结论,B 列始终包含数字,因此您可以使用它来计算“最后一行”,即最后一个非空的行细胞...

    ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
    

    ...或者只是确定最后一个非空单元格...

    ws.Cells(ws.Rows.Count, "B").End(xlUp)
    

    ...如以下代码所示:

Sub WriteFormulas()
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    With ws.Range("B2", ws.Cells(ws.Rows.Count, "B").End(xlUp))
        .Offset(, 2).FormulaR1C1 = "=RC[-1]/RC[-2]"
        .Offset(, 3).FormulaR1C1 = "=RC[-1]+(RC[-1]*0.55)"
        .Offset(, 5).FormulaR1C1 = "=RC[-2]+RC[-1]"
    End With

End Sub

关于excel vba根据我的表格大小自动计算公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71980595/

相关文章:

excel - 有没有一种好方法可以跟踪 GIT 存储库中 Excel 工作表的变化?

excel - 在 VBA Excel 2003 中获取 "My Documents"文件夹的独立于语言的方法

excel - 单击按钮后用户窗体未出现

vba - 升级 VBA 6->7 导致错误 : If Exists in Collection

image - 如何更改图像中的像素值范围?

使用带有排除的最后一个数字的范围的 Pythonic 方法?

python - 将 .xll 作为 AddIn 添加到 Excel

vba - 不使用 VBA 或 VSTO 的本地(特定于工作簿)函数

excel - VBA有Hash_HMAC吗

mysql - 根据两列中的日期范围重复行