【问题标题】:Macro doesn't run when data is refreshed?刷新数据时宏不运行?
【发布时间】:2012-06-04 19:37:42
【问题描述】:

我已经编写了以下代码来检测单元格值的变化,然后运行宏,但是由于数据连接而刷新数据时,代码不起作用。

Private Sub worksheet_change(ByVal target As Range)
If target.Address = "$A$2" Then

If target.Value = 1 Then

taskID = Shell("c:\imawesome.bat", vbNormalFocus)
    End If
    If target.Value = 0 Then

taskID = Shell("c:\Sender.bat", vbNormalFocus)
    End If
    End If
End Sub

仅当我在单元格中手动输入数据时,该代码才有效。 请建议刷新数据时运行的代码。

【问题讨论】:

  • 这篇来自 Microsoft 的知识库文章可能会有所帮助 link
  • @Ateszki +1。您应该将此作为答案发布(假设数据连接是查询表)

标签: vba excel


【解决方案1】:

按照这篇 microsoft 文章 KB213187 并假设您的数据连接是一个查询表

你可以试试这个

创建一个新模块并将此代码放入其中

Public WithEvents qt As QueryTable

Private Sub qt_BeforeRefresh(Cancel As Boolean)

  'do your stuff here

End Sub

然后在另一个模块上创建一个类

Dim X As New Class1

Sub Initialize_It()
  Set X.qt = Thisworkbook.Sheets(1).QueryTables(1)
End Sub

并确保每次打开文档时 Initialize_It 都会运行。

请注意,此代码仅适用于每个文档一个 qquerytable,如果您有更多,则需要进行修改。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    如果 worksheet_change 不会触发,请尝试使用 worksheet_calculate 事件。它在任何单元格计算时执行,因此您可以对所需的单元格和(以前的)值进行测试。

    【讨论】:

    • private Sub Worksheet_Calculate() Dim target As Range Set target = Range("A1") If Not Intersect(target, Range("A1")) Is Nothing Then If target.Value = 1 Then taskID = Shell("c:\imawesome.bat", vbNormalFocus) End If If target.Value = 0 Then taskID = Shell("c:\Sender.bat", vbNormalFocus) End If End If End Sub 它根本不工作也令人耳目一新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多