2016-07-22 89 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 
相關問題