我是VBA的新手。我正在尝试在Sheet1中找到一些数据并将其复制到Sheet2。当我从Sheet1中选择数据时,我需要将它附加到Sheet2中的数据。
我可以使用以下代码查找并粘贴数据,但我无法附加它。我在代码中做错了什么?
Sub Copy_To_Another_Sheet_1()
Dim FirstAddress As String
Dim MyArr As Variant
Dim Rng As Range
Dim Rcount As Long
Dim i As Long
Dim NewSh As Worksheet
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
MyArr = Array("37", "283", "300", "112", "1100", "336", "98")
Set NewSh = Sheets("Sheet2")
With Sheets("Sheet1").Range("B5:B500")
Rcount = 0
For i = LBound(MyArr) To UBound(MyArr)
Set Rng = .Find(What:=MyArr(i), _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
FirstAddress = Rng.Address
Do
Rcount = Rcount + 1
Rng.EntireRow.Copy NewSh.Range("A" & Rcount)
Set Rng = .FindNext(Rng)
Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
End If
Next i
End With
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
答案 0 :(得分:1)
我猜'追加'意味着在您反复运行宏时添加数据。下次运行时这种情况将覆盖sheet2中的内容。您需要将Rcount变量更改为:
Rcount = NewSh.Cells(NewSh.Rows.Count,1).End(xlUp).Row+1
在A列的Sheet2中找到第一个空单元格。
如果您是第一次运行代码,则需要进行一些其他更改(如果您确实需要在第1行中运行结果)。还要检查Rcount
增量线的放置位置 - 而不应在.copy
行