2016-07-22 144 views
0

我有一个vba代码,可以将工作表上的行复制到另一个工作表,具体取决于列A = 1并且工作完美。我正在尝试将其粘贴到下一个可用行,而不是覆盖已经存在的数据以创建日志。这里是我已经的代码,但我似乎无法弄清楚如何将它粘贴到下一个可用的行。任何帮助将不胜感激!提前致谢!VBA-如何将值复制并粘贴到从下一个可用行开始的另一个工作表

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

您是否熟悉使用.Cells(row#,col#)而不是Range(A1)? – peege

+1

'Range(“'Log'!B3”)。Offset(count,0).PasteSpecial xlPasteValues'语法不正确。尝试'表格(“Log!B3”)。范围(“A1”)。偏移量(count,0).PasteSpecial xlPasteValues' –

+0

@peege提供的答案就像一个魅力。谢谢!我刚刚开始学习编程,这对我有很大帮助! –

回答

0

你只需要遍历源表单。

尝试使用.Cells(行,列),而不是范围..

这个例子上的评论沉重帮助理解循环过程。

您将需要一些额外的功能使这个代码工作。

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 
相关问题