从录制的macros创build一个循环

我有两组数据,这两组数据必须根据一个标识符(它们都有相同的标识符)进行匹配(范围1在Sheet1上,并且从列A运行:F,范围2在Sheet3上并从列A:M运行)。 这两个范围的匹配值将出现在Sheet1的列E和Sheet3的列C中。 我试图logging一个macros,看看我是否可以创build一个简单的循环来重复我在做的事情,直到遇到任何不规则的数据,但是我遇到了如何循环我正在做的动作的问题。 这是我的代码:

Sub Record_And_Destroy() 'first issue is writing a loop that will cycle through all rows in column E 'starting in row 18 in this example Range("E18").Select Selection.Copy Sheets("Sheet3").Select 'Sheet3 contains the second table of data 'I want to search based on the copied value from Sheet1... *Cells.Find(What:="03885740-131601", After:=ActiveCell, LookIn:=xlFormulas _ , LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False).Activate* 'The data that is being matched is in column C of Sheet3 but I need all columns A:M that 'are associated with the found match Range("A10:M10").Select Application.CutCopyMode = False Selection.Cut Sheets("Sheet1").Select Range("G18").Select 'Column G is the next available column when matching to Sheet1 so every other selection 'would be placed in Column G but the row would differ based upon 'which row was being searched ActiveSheet.Paste Sheets("Sheet3").Select Selection.Delete Shift:=xlUp 'this way I clean up the data base to only contain the "problem" cases End Sub 

问题1:有没有办法使用Cells.Find来searchselect而不是值?

问题2:如果循环找不到匹配,是否有办法在Sheet1上格式化G:S行来显示一个红色的背景,这样我就知道一旦循环结束就返回并检查这些值。

据我所知,你想沿着E列(从第18行开始)往下search每个值,看它是否存在于Sheet3的列C中。如果它存在,那么将该行从Sheet3复制到A列到M列从当前正在检查的同一行的G列开始。

 Sub Record_And_Destroy() Dim rw As Long, mrw As Long, ws3 As Worksheet Set ws3 = Sheets("Sheet3") With Sheets("Sheet1") For rw = 18 To .Cells(Rows.Count, "E").End(xlUp).Row If CBool(Application.CountIf(ws3.Columns(3), .Cells(rw, "E").Value)) Then mrw = Application.Match(.Cells(rw, "E"), ws3.Columns(3), 0) ws3.Cells(mrw, "A").Resize(1, 13).Copy _ Destination:=.Cells(rw, "G") ws3.Rows(mrw).EntireRow.Delete End If Next rw End With Set ws3 = Nothing End Sub 

请注意,我已经完全避免使用。select赞成直接工作表和单元格寻址。 请参阅如何避免使用在Excel VBAmacros中select更多的方法来摆脱依靠select和激活来实现您的目标。