如何使用粘贴值将其复制并粘贴到下一个可用行?

时间:2019-07-15 10:10:41

标签: excel vba

新手问题!如果这是一个很明显的答案,我很抱歉,只是学习如何有效地编码。我一直在尝试使用不同的代码将数据复制并粘贴到另一张已转置的excel工作簿中,该工作簿正在运行。但是,它似乎没有粘贴值,也无法将其粘贴到下一个可用行。我已经找到了命令,但是不确定按什么顺序插入命令,似乎出错了。

这是我当前的工作代码,减去粘贴到下一个可用行的命令:

Dim lastRow As Long
Workbooks("CSA V0.3.xlsx").Worksheets("CSA - TL").Range("B2:B5").SpecialCells(xlCellTypeVisible).Copy
Workbooks("TL CSA Master.xlsx").Worksheets("Master").Range("A3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

Workbooks("CSA V0.3.xlsx").Worksheets("CSA - TL").Range("G9:G28").SpecialCells(xlCellTypeVisible).Copy
Workbooks("TL CSA Master.xlsx").Worksheets("Master").Range("E3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

我在哪里插入代码,以便每次运行代码时,它将值粘贴到下一个可用行上?预先感谢!

1 个答案:

答案 0 :(得分:0)

您需要先找到最后使用的行:

Dim LastRow As Long
With Workbooks("TL CSA Master.xlsx").Worksheets("Master")
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'find last used row in Column A

    Workbooks("CSA V0.3.xlsx").Worksheets("CSA - TL").Range("B2:B5").SpecialCells(xlCellTypeVisible).Copy
    .Cells(LastRow + 1, "A").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

    Workbooks("CSA V0.3.xlsx").Worksheets("CSA - TL").Range("G9:G28").SpecialCells(xlCellTypeVisible).Copy
    .Cells(LastRow + 1, "E").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End With

甚至更好:

Dim wsDest As Worksheet
Set wsDest = Workbooks("TL CSA Master.xlsx").Worksheets("Master")

Dim wsSrc As Worksheet
Set wsSrc = Workbooks("CSA V0.3.xlsx").Worksheets("CSA - TL")

Dim NextFreeRow As Long
NextFreeRow = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Row + 1 'find next free row in Column A

wsSrc.Range("B2:B5").SpecialCells(xlCellTypeVisible).Copy
wsDest.Cells(NextFreeRow, "A").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

wsSrc.Range("G9:G28").SpecialCells(xlCellTypeVisible).Copy
wsDest.Cells(NextFreeRow, "E").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True