简体   繁体   中英

Running a VBA code whenever you change the row you're editing

I need to run a code in excel VBA whenever you change the row you're working on.

My code updates other Workbooks whenever you edit something, but since all the information in a row is supposed to update 1 Workbook, I want it to open and update that other Workbook only when you stop working in a row (any row)

Right now I have a code that updates the other workbook when I change a cell, so this is what I have.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Set KeyCells = Range("A1:C10")
    Dim WB As Workbook
    Dim dirFile As String
    Dim strFile As String
    Dim Actual As Workbook
    Static lngRow As Long
    Dim linea
    Set Actual = ActiveWorkbook
    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then
        MsgBox "Cell " & Target.Address & " has changed."
        dirFile = "N:\Otros\sebastian\TEST 2\"
        strFile = Trim(Cells(Target.Row, 1).Value)
        If Len(Dir(dirFile & strFile & ".xlsx")) = 0 Then
            Application.Visible = False

            linea = Target.Row
            Set WB = Workbooks.Add
            ' ESTILO
            ' __________________________
            WB.Worksheets(1).Columns("A").ColumnWidth = 28
            ' ___________________________
            'DATOS
            '____________________________

            WB.Worksheets(1).Cells(1, 1).Value = "Titulo de Proyecto"
            WB.Worksheets(1).Cells(1, 2).Value = Actual.Worksheets(1).Cells(linea, 2)
            WB.SaveAs (dirFile & strFile & ".xlsx")
            WB.Close
            Application.Visible = True


        End If



    End If
End Sub

Use a global variable in the worksheet module to accomplish this. The currRow variable is set to 0 when the sheet is activated (in case you switch to another sheet). Then check the row of the target vs. the row previously on.

Private currRow As Long

Private Sub Worksheet_Activate()

    currRow = 0

End Sub

Private Sub Worksheet_Change(ByVal Target As Range)

    If currRow = Target.Row Then
       'Do Nothing
    Else
       If currRow <> 0 Then
                 'Do Rest of code then set the target to the new row
       End If
       currRow = Target.Row
    End If

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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