如何在每次更改时自动运行Microsoft Excel宏?

时间:2014-03-21 08:52:22

标签: excel vba excel-vba

我想知道在更改文档内容时是否有办法运行宏。谢谢!

宏:

Sub Test()
    Const QT = """"
    Dim a(), i As Long, r As Long, v As String
    With Range("B1", Cells(Rows.Count, "B").End(xlUp))
        If .Count = 1 Then
            ReDim a(1 To 1, 1 To 1)
            a(1, 1) = .Value
        Else
            a() = .Value
        End If
        For r = 1 To UBound(a)
            v = Trim(a(r, 1))
            If Len(v) Then
                If Right(v, 1) = QT Then v = Left(v, Len(v) - 1)
                i = InStrRev(v, QT)
                If i Then v = Mid(v, i + 1)
                a(r, 1) = Trim(v)
            End If
        Next
        .Value = a()
    End With
End Sub

1 个答案:

答案 0 :(得分:1)

您可以按如下方式向工作簿添加事件处理程序

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    MsgBox ("changed")
End Sub

要添加此宏,请转到vb视图 - 在左侧的“项目”面板中选择工作簿以打开与工作簿关联的代码并粘贴上面的代码。每次更改工作簿中的单元格时,您都会收到通知。