从一个工作簿到另一个具有命名单元格的VBA公式

时间:2016-03-23 19:56:03

标签: excel vba excel-vba formula

我不能让我的配方工作。您可以看到我只是想从一个工作簿到另一个工作簿中减去另一个值(单元格中有一个公式)。我错过了什么?它将公式复制到正确的单元格中但不计算。结果#NAME?。

Sub changeReports()
    Dim currentWk As Worksheet
    Dim prevYr As Worksheet
    Dim prevWk As Worksheet
    Dim File_Path As String
    Dim Source_Workbook As Workbook
    Dim Target_workbook As Workbook

    File_Path = "B:\Operations\Aging 031416Wk11.xlsm"
    Destination_Path = "B:\Operations\Aging 032116Wk12.xlsm"
    Set Source_Workbook = Workbooks.Open(File_Path)
    Set Target_workbook = Workbooks.Open(Destination_Path)
    Set prevWk = Source_Workbook.Worksheets("2016 Reports")
    Set currentWk = Target_workbook.Worksheets("2016 Reports")       
    currentWk.Activate  

    ' code works to insert formula in cell but formula not working the way    it is written
    Range("chgBox").formula = "=currentWk.Range(""grBox"")- prevWk.Range(""grBox"")"     
End Sub

1 个答案:

答案 0 :(得分:0)

如果你想在Range(“chgBox”)单元格中减去结果,那么就进行实际的计算。

Range("chgBox") = currentWk.Range("grBox") - prevWk.Range("grBox")

如果希望公式保留在Range(“chgBox”)单元格中,则将VBA单元格引用转换为地址,并连接一个代表工作表公式的字符串。

Range("chgBox").Formula = "=" & currentWk.Range("grBox").Address(external:=true) & _
                            "-" & prevWk.Range("grBox").Address(external:=true)

您收到#NAME!错误,因为工作表无法理解currentWk.Range(""grBox"")是什么。

附录:

我已经完成了一个完整的样本测试环境,公式和直接结果都是如上所述。我已经清理了下面的其余代码。

Option Explicit

Sub changeReports()
    Dim currentWk As Worksheet
    Dim prevWk As Worksheet
    Dim filePath As String, destinationPath As String
    Dim sourceWorkbook As Workbook, targetWorkbook As Workbook

    filePath = "B:\Operations\Aging 031416Wk11.xlsm"
    destinationPath = "B:\Operations\Aging 032116Wk12.xlsm"
    filePath = Environ("TMP") & "\Aging 031416Wk11.xlsm"
    destinationPath = Environ("TMP") & "\Aging 032116Wk12.xlsm"

    Set sourceWorkbook = Workbooks.Open(filePath)
    Set targetWorkbook = Workbooks.Open(destinationPath)
    Set prevWk = sourceWorkbook.Worksheets("2016 Reports")
    Set currentWk = targetWorkbook.Worksheets("2016 Reports")

    With currentWk
        .Range("chgBox") = .Range("grBox") - prevWk.Range("grBox")
        '.Range("chgBox").Formula = "=" & currentWk.Range("grBox").Address & _
                            "-" & prevWk.Range("grBox").Address(external:=True)
    End With

    sourceWorkbook.Close savechanges:=False
    targetWorkbook.Close savechanges:=True

End Sub