用于执行打开显式VBA代码的命令按钮

时间:2017-03-10 10:53:23

标签: excel vba excel-vba

我是VBA的新手,在互联网上找到了一个代码,用于记录工作簿中所做的更改。代码正在运行,但它始终处于活动状态。我想将它连接到命令按钮以启动或停止代码。如果有任何其他方式,那么将受到欢迎。

谢谢。

Nilesh制作

Option Explicit

Public OldVal As String


Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If ActiveSheet.Name <> "LgDetails" Then
Application.EnableEvents = False
    Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Value = ActiveSheet.Name & "_" & Target.Address(0, 0)
    Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 1).Value = OldVal
    Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 2).Value = Target.Value
    Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 3).Value = Environ("username")
    Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 4).Value = Date
    Sheets("LogDetails").Columns("A:E").AutoFit
Application.EnableEvents = True
End If
End Sub


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

OldVal = ActiveCell.Value

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Static TheFormula As String
    If Target.Address = "$A$1" Then
        With Target
            TheFormula = .Formula
            .Value = .Value
        End With
    Else
        With Range("A1")
            If Not .HasFormula Then
                .Formula = TheFormula
            End If
        End With
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

我对你想要实现的目标并不感到满意,但请看下面的代码。在工作表LogDetails中添加一个复选框,并将其命名为RecordingControl。然后在代码中添加两行。

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

    If ThisWorkbook.Worksheets("LogDetails").OLEObjects("RecordingControl").Object.Value = True Then 'Add this line
        If ActiveSheet.Name <> "LogDetails" Then
        Application.EnableEvents = False
            Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Value = ActiveSheet.Name & "_" & Target.Address(0, 0)
            Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 1).Value = OldVal
            Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 2).Value = Target.Value
            Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 3).Value = Environ("username")
            Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 4).Value = Date
            Sheets("LogDetails").Columns("A:E").AutoFit
        Application.EnableEvents = True
        End If
    End If 'Add this line
End Sub