如何保留宏的使用日志

时间:2012-07-09 13:20:59

标签: excel vba logging

我有一个相当愚蠢的问题。我有一个宏(链接到一个按钮),它将单元格A1:A2从一个工作表(namedFP)复制到另一个工作表(日志)。我打算每次按下宏按钮时在日志表上复制这两个单元格。我现在面临的问题是,当我多次使用按钮时,这些单元格会相互复制而不是使用下一个可用行来粘贴单元格。

这就是我现在所拥有的,我尝试将'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

2 个答案:

答案 0 :(得分: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”有任何问题或疑问,请与我们联系。代码。

答案 1 :(得分: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