单元格更改时自动运行VBA

时间:2018-02-19 21:58:36

标签: excel-vba vba excel

我有这个代码,它使用一个按钮将3列数据打印到文本文件中。我希望代码在A2到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

1 个答案:

答案 0 :(得分:0)

在工作表模块中输入此代码

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