0

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

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

2 回答 2

0

这是我使用的一个非常可靠的函数,它总是返回工作表的最后一行而不会失败:(对于您的简单使用可能过多,但我总是推荐它)

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”代码有任何问题或疑问,请告诉我。

于 2012-07-09T13:52:27.903 回答
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
于 2012-07-09T14:36:47.273 回答