我正在使用Excel为支持票务系统生成报表,我想使用VBA来简化更新报表数据的过程。我想要做的是将从票务系统转储的Excel文件导入到我用于报告的Excel文件中,但有一个转折点。我需要使用一列中的值来确定故障单是新的还是现有的。如果是新的,我想将其添加到报告文件中。如果它存在,我想用导入的数据覆盖匹配的行(基于匹配的列值,即票号)。所以基本过程将是:
上面的步骤4-6是我想要帮助的。我可以使用一个公式,如= NOT(ISNA(MATCH([导入的故障单ID ],[现有故障单ID 的数组],0)))如果返回TRUE,则返回TRUE票证ID存在,如果不存在,则为FALSE,但如果存在,则希望找到更优雅的解决方案。
这里有没有人有这方面的经验和/或一些VBA代码我可能会调整以适应我的目的?提前谢谢。
编辑:这是我到目前为止的代码。它并不多。
Sub UpdateTickets()
'Specify data export file
Dim fNameAndPath As Variant
fNameAndPath = Application.GetOpenFilename(Title:="Select File To Be Processed")
If fNameAndPath = False Then Exit Sub
'Open data export file
Workbooks.Open Filename:=fNameAndPath
'For each row in data export file, starting at Row 2
'Check master data file (column A) for ticket number
'If ticket number exists, update information in columns B through P
'Else add new ticket row and place information in columns A through P
'Next row
End Sub
答案 0 :(得分:2)
我刚刚写了这篇文章,并且有效:
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
我希望它有所帮助。我为第一个空白行代码引用了this page,为查找代码引用了this page。我在主票证文件的模块中编写了代码。