【发布时间】:2021-06-22 09:30:49
【问题描述】:
我正在使用 VBA 循环遍历两个工作表上的行,如果它们匹配,则将工作表 2 中的行复制到工作表 1。
我的代码应该是:
- 打开第二个工作簿
- 将所有信息复制到新工作表上的原始工作簿中
- 然后循环遍历原始工作表(450+行)上的 F 列并在新的“数据”工作表(9,500+行)上找到活动单元格,找到相同的值后,它会复制整行并将其粘贴到原始工作表中然后循环再次开始。
虽然这确实有效,但我发现这需要超过 20 分钟,这太长了!我是 VBA 的初学者,虽然我已经取得了不错的进步,但我仍然坚持这一点,我已经阅读了 Variants,但老实说,它们让我感到困惑!任何帮助将不胜感激:)
Sub AutoUpdate()
'Opens Enterprise Master Lead File (whichever is present) and auto updates data
' in current sheet depending on if ID ref is present
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'This opens the workbook without setting set date as long as the
'file is always in the same place
Dim Wb As Workbook
Dim Wb2 As Workbook
Dim rng As Range, Cel As Range
Dim sFind As String
Dim lastRow As Long
lastRow = Range("F" & Rows.Count).End(xlUp).Row
Set rng = Range("F2:F" & lastRow)
Set Wb = ThisWorkbook
Set Wb2 = Workbooks.Open("xxxxxxxxxxx.xlsx") 'opens secondary workbook
'Deletes unecessary columns
Range("C:C,D:D,G:G,H:H,I:I,J:J,K:K,M:M,N:N,O:O,P:P,Q:Q,S:S,U:U,V:V,W:W,Z:Z,AD:AD").Select
Selection.Delete Shift:=xlToLeft
Range("A2").Select
Cells.Select
Selection.Copy
Wb.Activate
Sheets.Add.Name = "Data"
Range("A1").Select
ActiveSheet.Paste
Wb2.Close 'closes secondary workbook to speed up process
Wb.Activate
'Loop - finds data in original sheet, finds data in secondary
'sheet, copies new data and pastes, offsets and starts again
Sheets("Corp Leads").Activate
With Wb
rng.Select
'Range("F1").Select
'ActiveCell.Offset(1, 0).Select
'Range(Selection, Selection.End(xlDown)).Select
For Each Cel In rng
If Cel.Value > 0 Then
ActiveCell.Select
sFind = ActiveCell
'Finding matching data
Sheets("Data").Activate
Range("F2").Select
Range(Selection, Selection.End(xlDown)).Select
Cells.Find(What:=sFind, After:= _
ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Select
'copying new data row
ActiveCell.EntireRow.Select
Selection.Copy
'Finding same data again in original sheet
Sheets("Corp Leads").Activate
Cells.Find(What:=sFind, After:= _
ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Select
'Pasting new data
ActiveCell.EntireRow.PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
'Finding reference again to offset for loop
Cells.Find(What:=sFind, After:= _
ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Select
ActiveCell.Offset(1, 0).Select
End If
Next Cel
End With
Sheets("Data").Delete
MsgBox ("UPDATED")
End Sub
【问题讨论】:
-
花费这么长时间的不是
.Find。就是Cells.Select: Selection.Copy之类的东西的使用和.Select/.Activate等不必要的使用。你可能想看看How to avoid using Select in Excel VBA -
我没有看到你的数据,但我有根据的猜测,如果你将工作表数据存储在一个数组中并在那里进行比较,整个操作应该不会超过一分钟......
-
谢谢!这真的很有帮助,你泄露的信息会有所帮助,只是想绞尽脑汁想出如何将我的代码转换成更“运行时”友好的东西!