且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

VBA导入Excel工作表,追加新行并更新现有行

更新时间:2023-12-01 08:42:40

我刚刚写了这个,它起作用了:

I just wrote this, and it worked:

    Sub import_tickets()
        'run this when the active file is the main ticket list and the active sheet is the ticket list
        'exported file must be open already, and the ticket list must be the active sheet
        Dim exported_file As String
        exported_file = "exported file.xlsx"
        header_exists = True 'if exported file doesn't have a header, set this to false!
        starting_row = 1
        If header_exists Then starting_row = 2

        Dim first_blank_row As Long
        first_blank_row = Cells.SpecialCells(xlCellTypeLastCell).Offset(1, 0).Row

        Dim r As Long
        r = starting_row
        Dim found As Range
        cur_ticket_num = Workbooks(exported_file).ActiveSheet.Range("a" & r).Value
        Do While Not cur_ticket_num = ""
            'look for current ticket number in main file
            Set found = Columns("a:a").Find(what:=cur_ticket_num, LookIn:=xlValues, lookat:=xlWhole)
            If found Is Nothing Then
                'add info to end of main file
                write_line_from_export exported_file, r, first_blank_row
                first_blank_row = first_blank_row + 1
            Else
                'overwrite existing line of main file
                write_line_from_export exported_file, r, found.Row
            End If
            r = r + 1
            cur_ticket_num = Workbooks(exported_file).ActiveSheet.Range("a" & r).Value
        Loop
    End Sub

    Sub write_line_from_export(src_filename As String, src_r As Long, dest_r As Long)
        For c = 1 To 24
            Cells(dest_r, c).Value = Workbooks(src_filename).ActiveSheet.Cells(src_r, c).Value
        Next c
    End Sub

我希望它有所帮助。我引用了此页面的第一个空行代码和此页面查找代码。我在主票证文件的模块中写了代码。

I hope it helps. I referenced this page for the first blank row code and this page for the find code. I wrote the code in the main ticket file's module.