2012-07-09 42 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