当细胞变化时,会自动运行VBA



我有此代码,该代码使用按钮将3列数据打印到文本文件。我希望代码在任何时间单元格通过D2更改时运行,而不是每次使用该按钮。有办法这样做吗?

Public Sub Print_File()
    Dim c As Range, r As Range
    Dim PageName As String
    Dim burntime As Double
    Dim last_data_row, numpoints, n As Integer
    burntime = Range("BurnTime_1").Value
    last_data_row = Columns(Range("Time_1").Column).Find("", Cells(Range("Time_1").Row, Range("Time_1").Column), LookIn:=xlValues, LookAt:=xlWhole).Row - 1
    numpoints = last_data_row - Range("Time_1").Row + 1
    Range("Time_1").Resize(numpoints, 1).Name = "Time_1"
    Range("Thrust_1").Resize(numpoints, 1).Name = "Thrust_1"
    Range("MDot_1").Resize(numpoints, 1).Name = "MDot_1"
    PageName = Left(ThisWorkbook.Path, Len(ThisWorkbook.Path)) & "Stg1F.dat" 'places file in same location as excel workbook
    Open PageName For Output As #1  'creating tab-delimited text file
    For n = 1 To numpoints
        Print #1, Cells(Range("Time_1").Row + n - 1, Range("Time_1").Column).Value & Chr(9) & _
            Cells(Range("Thrust_1").Row + n - 1, Range("Thrust_1").Column).Value & Chr(9) & _
            Cells(Range("MDot_1").Row + n - 1, Range("MDot_1").Column).Value
    Next
    Close #1
End Sub

在工作表模块中放置此代码

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("A2:D2")) Is Nothing Then
    Print_File
End If
End Sub

最新更新