使用VBA的单元交叉引用

时间:2018-05-09 22:47:38

标签: excel vba excel-vba

我做了一些搜索,无法弄清楚我想要完成的语法。我想在摘要表上有一个特定的静态单元格自动更新到不同工作表上的动态单元格。我从以下代码开始:

Sheets("Summary").Activate
Range("B1").Select
ActiveCell.FormulaR1C1 = "='Current Billing'!R[46]C"
Range("B2").Select
ActiveCell.FormulaR1C1 = _
    "='Current Billing'!R[45]C[3]+'Current Billing'!R[45]C[4]"

在获得关于同一工作簿的不同主题的一些建议后,我现在知道了。选择是禁止的,应该避免。我也知道我在#34;当前账单中的最后一行"当我将代码复制到另一个工作簿以对项目进行计费时,工作表将会更改。这导致我修改我的代码,使其更加傻瓜和多才多艺。

我已经想出了如何从我的"当前结算"中插入单元格值?表格到我的"摘要"片。但是,如果某些事情发生变化,那么"当前结算"表格,"摘要"工作表不会自动更新。这是我有的代码:

Dim ws5 As Worksheet
'ws5 is "Current Billing"
Dim ws6 As Worksheet
'ws6 is "Summary"
Dim LRowB2 As Long
Dim LRowB3 As String
LRowB2 = ws5.Cells(Rows.Count, "B").End(xlUp).Row
LRowB3 = ws5.Cells(LRowB2, "B")
ws6.Cells(1, "B").Formula = LRowB3

我尝试了这两个代码序列,但不断出现错误:

Dim LRowB4 As String
Dim LRowE2 As Long
Dim LRowF2 As Long

LRowB4 = "= & ws5 & ! & LRowB3"
ws6.Cells(2, "B").Formula = "=sum(& LRowE2 &,& LRowF2 &)"

简而言之,有没有办法模仿第一个代码过程的功能,但是第二个过程的稳定性和万无一失?并且,有没有办法将a = Sum()公式集成到第二个过程中,这样我就可以添加来自"当前结算"的两个单元格。关于"摘要"页?谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

公式的语法类似于=SUM('Current Billing'!C9, 'Current Billing'!D9)

这将检查错误,并且更加动态

Option Explicit

Public Sub UpdateSummary()
    Dim wsCB As Worksheet, lrCB As Long, cbCellC As Range, cbCellD As Range
    Dim wsSummary As Worksheet, sumCell As Range

    Set wsCB = ThisWorkbook.Worksheets("Current Billing")
    Set wsSummary = ThisWorkbook.Worksheets("Summary")

    lrCB = wsCB.Cells(wsCB.Rows.Count, "C").End(xlUp).Row

    'Verify that we have the same last row for col C and D on sheet "Current Billing"
    If wsCB.Cells(wsCB.Rows.Count, "D").End(xlUp).Row = lrCB Then
        Set cbCellC = wsCB.Cells(lrCB, "C")     '"Current Billing".Cell(lr, C)
        Set cbCellD = wsCB.Cells(lrCB, "D")     '"Current Billing".Cell(lr, D)
        Set sumCell = wsSummary.Cells(2, "B")   '"Summary".Cell(2, B)
        sumCell = "Invalid 'Current Billing' values"    'Default (in case of errors)

        'Check "Current Billing" cells for errors (#N/A, #VALUE!, #REF!, #DIV/0!, etc)
        If Not IsError(cbCellC) And Not IsError(cbCellD) Then

            'Verify that "Current Billing" cells are numbers
            If IsNumeric(cbCellC) And IsNumeric(cbCellD) Then
                Dim cbC As String, cbD As String

                cbC = "'" & wsCB.Name & "'!" & cbCellC.Address(0, 0) 'Current Billing'!C9
                cbD = "'" & wsCB.Name & "'!" & cbCellD.Address(0, 0) 'Current Billing'!D9

                'Final format: =SUM('Current Billing'!C9, 'Current Billing'!D9)

                sumCell.Formula = "=SUM(" & cbC & ", " & cbD & ")"  'Update Summary cell
            End If
        End If
    End If
End Sub

如果公式包含除法,请验证除数不是0

但是如果您正在使用VBA,则可以简化语法: sumCell = cbCellC + cbCellD

注意:

当我们必须在引号内使用引号时,字符串变量变得更加复杂:

  • Str with ""double quotes""可以像这样构建

    • str = "Str with """"double quotes"""""
    • str = "Str with " & Chr(34) & """double quotes""" & Chr(34)
    • str = "Str with " & Chr(34) & Chr(34) & "double quotes" & Chr(34) & Chr(34)
  • 此字符串str = "Str with 'double quotes'"Str with 'double quotes'

答案 1 :(得分:0)

使用Workbook_SheetChange事件。这是在您的工作簿中的任何位置进行更改时触发的“事件”操作。在事件子中添加代码以使用公式中的值更新硬编码/静态单元格的值。

Workbook_SheetChange sub必须位于工作簿模块中(默认模块名称为“ThisWorkbook”)。

以下是如何使用它的示例。只需更新变量myStaticCellmyFormulaCell的工作表名称和范围地址。

在您的ThisWorkbook模块中:

Option Explicit

Public myVar As Variant ' stores last known value of static cell

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

    ' Define the locations of your formula cell and static cell.
    Dim myStaticCell As Range
    Dim myFormulaCell As Range
    Set myStaticCell = Worksheets("Sheet2").Range("A2")
    Set myFormulaCell = Worksheets("Sheet1").Range("A2")

    ' Ignore changes made directly to the static cell by comparing
    '   the sheet name and address where the workbook change
    '   occurred (variables Sh and Target which are built into the
    '   Workbook_SheetChange event) with the sheet name and address
    '   of your static cell.
    If Sh.Name = myStaticCell.Parent.Name And _
            Target.Address = myStaticCell.Address Then Exit Sub

    ' Save the value to a public variable so it can
    '   be checked the next time something changes.
    myVar = myFormulaCell.Value

    ' If different, update the static cell with the
    '   value from your formula.
    If myStaticCell <> myVar Then myStaticCell = myFormulaCell.Value
End Sub