2012-07-09 66 views
0

我有一個相當愚蠢的問題。我有一個宏(鏈接到一個按鈕)將單元格A1:A2從一個工作表(namedFP)複製到另一個工作表(Log)。我打算在每次點擊宏按鈕時將這2個單元複製到日誌表中。我現在面臨的問題是,當我多次使用該按鈕時,這些單元格將相互複製,而不是使用下一個可用行來粘貼單元格。如何保留宏的使用記錄

這就是我現在所擁有的,我嘗試將'Rowcount + 1'更改爲'RowCount + 2',但這並不奏效。任何幫助表示讚賞。

DHRSheet.Select 
Range("A1:A2").Select 
Selection.Copy 

LogSheet.Select 
RowCount = LogSheet.UsedRange.Rows.Count 
Dim r As Integer 
r = RowCount + 1 
Dim infocell As Range 
Set infocell = Cells(r, 1) 
infocell.Select 
ActiveSheet.Paste 
infocell.Value = DHRSheet.Name & "$" & infocell.Value 

DHRSheet.Select 
ActiveWorkbook.Save 
+0

爲了讓最後一排,看到這個鏈接:http://stackoverflow.com/questions/11169445/error-finding-last-used-cell-in-vba你也可以顯示你怎麼樣聲明LogSheet – 2012-07-09 14:28:19

+0

這是一個小問題,但你應該用單引號'''來包裝表單名稱。如果有空格,表格名稱將被相應地打包。否則,結果是不可預測的。如果工作表名稱中沒有空格,Excel將愉快地刪除單引號。 – JimmyPena 2012-07-09 18:28:35

回答

1

下面是我用的是非常可靠的,總是返回無表的最後一排的功能失效: (爲您簡單的使用可能過度,但我總是建議吧)

Public Function LastRowOfSheet(ByVal TestSheetNumber As Variant) 
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
' Input: Sheet index # or Sheet name 
' Output: Last row of sheet. 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
    Dim intNumberOfRowsInWorksheet As Long 

    intNumberOfRowsInWorksheet = Sheets(TestSheetNumber).UsedRange.Rows.Count 
    intNumberOfRowsInWorksheet = intNumberOfRowsInWorksheet +  Sheets(TestSheetNumber).UsedRange.Row - 1 

    LastRowOfSheet = intNumberOfRowsInWorksheet 
End Function 

而且我要清理上面的代碼,並使用這樣的:

Sub Move2RowsToEnd() 

    Dim iNextRowOfOutput As Long 
    Dim iRowNumber As Long 
    '- use the function to find the last row of the output sheet. we'll be pasting to the first row after. 
    iNextRowOfOutput = (LastRowOfSheet("Log") + 1) 

    '- you can adjust this for loop to loop through additional cells if you need to paste more than 2 rows in the future. 
    For iRowNumber = 1 To 2 
     '- for each row of input (2 total) set the value of the output sheet equal to it. 
     Sheets("Log").Range("A" & iNextRowOfOutput).Value = Sheets("namedFP").Range("A"  & iRowNumber).Value 
     iNextRowOfOutput = iNextRowOfOutput + 1 
    Next iRowNumber 

    '- not sure which of these you want to save (one or both) 
    Sheets("namedFP").Save 
    Sheets("Log").Save 

End Sub 

只需粘貼的上方或下方的子程序的功能,讓我知道如果喲你對'Move2RowsToEnd'代碼有任何問題或疑問。

0

這是你正在嘗試?

Sub Sample() 
    Dim LogSheet As Worksheet, DHRSheet As Worksheet 
    Dim lrow As Long 

    '~~> Change this as applicable 
    Set LogSheet = Sheets("Sheet1") 
    Set DHRSheet = Sheets("Sheet2") 

    With LogSheet 
     lrow = LogSheet.Range("A" & .Rows.Count).End(xlUp).Row + 1 

     DHRSheet.Range("A1:A2").Copy .Range("A" & lrow) 
    End With 
End Sub