在两个工作簿中调用公式结果更改的macros
我的问题很简单:我有两个工作簿(假设他们是wb1和wb2)。
在wb2的ws2上,我在Range("A1")
有一个像='[wb1.xlsm]ws1'B1
。 因此,当wb1的ws1上的B1变化时,wb2的ws2上的A1也变化(这是目标)。
我的问题是如何在ws2上A1的值改变时触发一个macros? Worksheet_Change
不会触发,并且Workbook_SheetChange
在这种情况下不适合…
编辑顺便说一下, Worksheet_Calculate
不适合太。 的确,我不知道ws2的价值在哪里会改变。
在回答你的问题之前,我不得不强调有很多真正的理由来避免链接工作簿。 它总是以痛苦,痛苦,失去的数据和花费在试图追踪数据源头上的浪费时间来结束。 Rant,这里是你如何忽略我的build议。
此代码使用VBA收集对象,这是非常垃圾。 VBScript包含更好的字典对象 ,您可以在VBA中使用它。 我强烈build议进一步调查…
代码有两部分。 第一个元素运行一次。 它会查找并开始跟踪给定工作表中的每个外部参考。
' Find all formulas that point to external workbook. ' Store current value. Sub Initialise() Dim c As Range ' Used to loop over all cells, looking for external. ' Ready collection for use. Set ExternalFormula = New Collection For Each c In [Sheet1].UsedRange ' Check if external, will start: =[ If c.HasFormula And c.Formula Like "=[[]*" Then ' Value added to collection contains key, for later use. ' Collections cannot return keys. ' Dictionaries are better, but require an external reference. ExternalFormula.Add c.address & "~~~" & c.Value, c.address End If Next End Sub
下一部分包含在Calculate
事件中。 Calculate
不提供更新的单元格地址。 但是使用ExternalFormula
集合我们可以找出哪个单元已经被更新了。
' Check external formula for changes. Private Sub Worksheet_Calculate() Dim c As Integer ' Used to loop over forumla. Dim address As String ' A1 style address of current forumla. Dim oldValue As String ' Value before any updates. ' Loop over stored values, looking for change. If ExternalFormula.Count > 0 Then For c = 1 To ExternalFormula.Count ' Extract address and old value. address = Split(ExternalFormula.Item(c), "~~~")(0) oldValue = Split(ExternalFormula.Item(c), "~~~")(1) ' Check for changes. If [Sheet1].Range(address).Value <> oldValue Then ' Change found. MsgBox address & " updated", vbInformation ' Update stored value. ExternalFormula.Remove address ExternalFormula.Add address & "~~~" & [Sheet1].Range(address).Value, address End If Next End If End Sub
使用字典对象将大大减less该函数中的代码行数。
不要忘记在工作簿或工作表级别声明ExternalFormula
。
Private ExternalFormula As Collection ' Stores all external forumulas.