简体   繁体   English

更改单元格时,excel VBA自动运行宏

[英]excel VBA run macro automatically when a cell is changed

I found a lot of answers to my question following this link: automatically execute an Excel macro on a cell change 通过此链接,我在问题中找到了很多答案: 在单元格更改时自动执行Excel宏

The reason I'm opening a new question is because I don't have enough reputation to comment on that thread and I'm having difficulty connecting my linked cell to the macro I want to run. 我要提出一个新问题的原因是因为我没有足够的声誉来对该线程发表评论,而且我很难将链接的单元格连接到要运行的宏。

So the cells that are linked contains a formula causing it to change value only when I change other cells. 因此,链接的单元格包含一个公式,该公式仅在我更改其他单元格时才使值更改。 The problem I'm having is that my macro only runs if I change the value of the cell and not the value of the formula. 我遇到的问题是,仅当我更改单元格的值而不是公式的值时,我的宏才会运行。 I'm looking for a way to activate the macro when the value that the formula returns changes. 我正在寻找一种当公式返回的值更改时激活宏的方法。

This is my code so far: 到目前为止,这是我的代码:

My range of cells is named "Values" and I want to hide the label "Refresh" 我的单元格区域名为“值”,我想隐藏标签“刷新”

Private Sub Worksheet_Change(ByVal Target As Range)

    If Intersect(Target, Me.Range("Values")) Is Nothing Then Exit Sub
        Application.EnableEvents = False 'to prevent endless loop

        Sheet1.Refresh.Visible = False

        Application.EnableEvents = True
End Sub

Sorry again for opening another question but as I said I couldn't comment on the other thread. 很抱歉再次提出另一个问题,但是正如我所说,我无法在其他主题上发表评论。

Use this code. 使用此代码。 It stores the values into a cell on the worksheet that is the last row\\column. 它将值存储到工作表中最后一行\\列的单元格中。 You'll need to store the value there manually once, but after that it will store it for you each time there's a change so it can check the next time the sheet is calculated (and the formula result is potentially changed). 您需要将值手动存储一次,但是此后它将在每次更改时为您存储该值,以便它可以检查下一次计算工作表的时间(并且公式结果可能会更改)。

Private Sub Worksheet_Calculate()

Dim bOld as Byte
bOld = Me.Cells(Me.Rows.Count,Me.Columns.Count)

If Me.Range("Values") <> bOld Then 

    Application.EnableEvents = False 'to prevent endless loop
    Me.Cells(Me.Rows.Count,Me.Columns.Count).Value = Me.Range("Values").Value 'store new value
    Sheet1.Refresh.Visible = False
    Application.EnableEvents = True

End If

End Sub  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM