将Sum函数的结果放入变量Excel中

时间:2013-11-15 18:57:01

标签: excel vba excel-vba

我有一个子程序,它对可变行进行求和。我需要获取这两个总和的结果并将它们相加,将结果(和标题)放在同一工作表的其他位置。我尝试使用的方法是捕获最后一行,如果两列被求和,进行求和,然后(我认为)将结果值放入我可以稍后处理的两个变量中。代码是:

Dim LastRowD As Long 
Dim LastRowF As Long
Dim ValD As Long
Dim Valf As Long

LastRowD = ActiveSheet.Cells(Rows.Count, "D").End(xlUp).Row
LastRowF = ActiveSheet.Cells(Rows.Count, "F").End(xlUp).Row

With ActiveSheet.Cells(Rows.Count, "D").End(xlUp)(2, 1)
    .Clear
    .Formula = "=SUM(D2:" & .Offset(1, 0).Address & ")"
End With

ActiveWindow.DisplayFormulas = False
With ActiveSheet.Cells(Rows.Count, "F").End(xlUp)(2, 1)
    .Clear
    .Formula = "=SUM(F2:" & .Offset(-1, 0).Address & ")"
End With

ValD = Cells(LastRowD + 1, "D").Value
ValF = Cells(LastRowE + 1, "F").Value

当我检查VALD和VALF的值时,它们都是空的。查看工作表时,单元格的总和为VALUE;公式栏显示公式。如何将单元格的值放入两个变量中?

1 个答案:

答案 0 :(得分:0)

尝试使用此功能来捕获值:

With ActiveSheet.Cells(Rows.Count, "D").End(xlUp)(2, 1)
    .Clear
    .Formula = "=SUM(D2:" & .Offset(1, 0).Address & ")"
    ValD = .Value
End With

ActiveWindow.DisplayFormulas = False
With ActiveSheet.Cells(Rows.Count, "F").End(xlUp)(2, 1)
    .Clear
    .Formula = "=SUM(F2:" & .Offset(-1, 0).Address & ")"
    ValF = .Value
End With