我有一个vba代码,可以将工作表上的行复制到另一个工作表,具体取决于A = 1列是否完美。我试图将其粘贴到下一个可用行,而不是覆盖已存在的数据以生成日志。这是我已有的代码,但我似乎无法弄清楚如何将其粘贴到下一个可用行。任何帮助将不胜感激!提前谢谢!
Sub Log()
Dim rng As Range
Dim lastRow As Long
Dim cell As Variant
Dim count As Long
count = 0
With ActiveSheet
lastRow = .Range("A" & .Rows.count).End(xlUp).Row
Set rng = .Range("A3:A" & lastRow)
For Each cell In rng
If cell.Value = "1" Then
Range(cell.Offset(0, 1), cell.Offset(0, 6)).Copy
Range("'Log'!B3").Offset(count, 0).PasteSpecial xlPasteValues
count = count + 1
End If
Next
End With
End Sub
答案 0 :(得分:0)
您只需要遍历源表。
尝试使用.Cells(row,col)而不是Range ..
这个例子很重要,有助于理解循环过程。
您需要使用其他一些函数才能使用此代码。
LastRow功能
Function lastRow(sheet As String) As Long
lastRow = Sheets(sheet).Cells(Rows.Count, "A").End(xlUp).Row 'Using Cells()
End Function
LastCol功能
Function lastCol(sheet As String) As Long
lastCol = Sheets(sheet).Cells(2, Columns.Count).End(xlToLeft).Column
End Function
解决方案代码:假设您已设置目标工作表的标题,并且目标和源表共享相同的格式。
Sub Log()
Dim source As String, target As String
Dim sRow As Long, col As Long, tRow As Long
'Declare Sheets
source = "Sheet1"
target = "Sheet2"
'Loop through rows of source sheet
For sRow = 2 To lastRow(source)
'Get current last row of Target Sheet
tRow = lastRow(target) + 1
'Meet criteria for Column A to = 1 on Source
If Sheets(source).Cells(sRow, 1) = "1" Then
'Copy each column of source sheet to target sheet in same order
For col = 1 To lastCol(source)
Sheets(target).Cells(tRow, col) = Sheets(source).Cells(sRow, col)
Next col
End If
Next sRow
End Sub