我是 VBA 的新手,并且在根据某些标准将一张表中的行复制到另一张表时遇到问题。
我曾尝试在此论坛中寻找答案,尝试修改代码以满足我的要求,但没有成功。请帮我。
- 我需要在工作表的 A 列中搜索编号。搜索应该从 1 号开始,然后是 2 号,然后是 3 号,以此类推。
- 每当找到“1”时,将整行复制到“Sheet 1”。
- 完成对“1”的搜索后,开始搜索“2”。找到匹配项后,将整行复制到“表 2”。
- 同理“3”号等。
- 重复此搜索其他编号,直到 A 列的末尾。
我尝试了以下代码: 注意:i 将在 1 到预定值之间变化。
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long '<~~ Not Integer. Might give you error in higher versions of excel
Dim strSearch As Integer
Set wb1 = ActiveWorkbook
Set ws1 = wb1.Worksheets("Burn Down")
strSearch = "1"
With ws1
'~~> Remove any filters
.AutoFilterMode = False
'~~> I am assuming that the names are in Col A
'~~> if not then change A below to whatever column letter
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
With .Range("A3:A" & lRow)
.AutoFilter Field:=1, Criteria1:="=*" & strSearch & "*"
Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
End With
'~~> Remove any filters
.AutoFilterMode = False
End With
'~~> Destination File
Set wb2 = Application.Workbooks.Open("C:\CSVimport\Sample.xlsx")
Set ws2 = wb2.Worksheets("Sheet" & i)
With ws2
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lRow = .Cells.Find(What:="*", _
After:=.Range("A3"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lRow = 1
End If
copyFrom.Copy .Rows(lRow)
End With
wb2.Save
wb2.Close