我的过程包括:
我在下面发布了我的代码,但由于某种原因无法正常工作。
Sub Test1()
Dim Name As String
Dim lastrow As Long
Dim Cell As Variant
lastrow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow
Name = Cells(i, 1)
If Name <> "" Then
For Each Cell In Sheets("Sheet2").Range("C2:C4000")
If Cell.Value = Name Then
matchRow = Cell.Row
Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Sheets("Sheet3").Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
Sheets("Sheet2").Select
End If
Next
End If
Next
End Sub
答案 0 :(得分:0)
无需遍历Sheet2!C:C中的每个单元格。
Sub Test1()
Dim i As Long, c as variant
With Worksheets("Sheet1")
For i = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row
c = Application.Match(.Cells(i, "A").Value2, Worksheets("Sheet2").Columns(3), 0)
If Not IsError(c) Then
Worksheets("Sheet2").Rows(c).Copy _
Destination:=Worksheets("Sheet3").Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0)
End If
Next i
End With
End Sub
答案 1 :(得分:0)
您需要获取单元格的.Value。
Name = CStr(Cell(i, 1).Value)
此外,还有一个内置函数来确定单元格是否为空。
If Not IsEmpty(Cell(i, 1).Value) Then
另外,我建议设置对工作表的引用,而不是只说Cells()
Dim ws As Worksheet
Set ws = Excel.Application.ThisWorkbook.Worksheets("wb name here")
ws.Cells(i, 1).Value
希望这会有所帮助!
答案 2 :(得分:0)
您从哪里来的错误让您感到困惑,因为选择了哪个工作表。因此,您需要更加明确,如下所示。
Sub Test1()
Dim Name As String
Dim lastrow As Long
Dim Cell As Variant
lastrow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow
Name = Sheets("Sheet1").Cells(i, 1)
If Name <> "" Then
For Each Cell In Sheets("Sheet2").Range("C2:C4000")
If Cell.Value = Name Then
matchRow = Cell.Row
Sheets("Sheet2").Select
ActiveSheet.Rows(matchRow).Select
Selection.Copy
Sheets("Sheet3").Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
Sheets("Sheet2").Select
End If
Next
End If
Next
End Sub