复制和过去转置范围

时间:2019-01-04 23:47:19

标签: excel vba copy paste

Sub CommandButton2_Click()

    Dim Report As Workbook
    Dim book As Workbook: Set book = ThisWorkbook
    Dim myfilename As String
    Dim lRow As Long

    Set Report = Workbooks.Open("S:\HR Compensation\Christapher Martin\Tellurian 
    Inc Job Pricing\Job Families and Competencies - Report.xlsm")

    lRow = book.Sheets(2).Cells(Rows.Count, 3).End(xlUp).Row

    book.Sheets(2).Range(Cells(8, 3), Cells(lRow, 3)).Copy
    Report.Sheets(1).Range("B2").PasteSpecial Transpose:=True

End Sub

我正在尝试使其工作,因此它将复制和粘贴输入的数据,而不必每次添加新信息时都手动更改代码,因为这最终会将大量信息本身加载到“报告”中,因此无法手动复制粘贴数据或更改代码。我知道问题出在代码的“复制”行中的lRow上,我只是不确定它是什么。

1 个答案:

答案 0 :(得分:1)

使用

  • 简化后,所有以(“ ”)开头的内容均指 With语句中的对象
  • 在您的没有With语句的版本中,以 (“ ”)之前应加book.Sheets(2)
  • 不确定“ Tellurian Inc”是否带有SPACE。正确 如有必要。

代码

Sub CommandButton2_Click()

    Dim Report As Workbook
    Dim lRow As Long

    Set Report = Workbooks.Open("S:\HR Compensation\Christapher Martin\" _
            & "Tellurian Inc Job Pricing\Job Families and Competencies " _
            & "- Report.xlsm")

    With ThisWorkbook.Sheets(2)
        lRow = .Cells(.Rows.Count, 3).End(xlUp).Row
        .Range(.Cells(8, 3), .Cells(lRow, 3)).Copy
    End With

    Report.Sheets(1).Range("B2").PasteSpecial Transpose:=True

    Application.CutCopyMode = False

End Sub

编辑:

  • 您可以在其他工作表上执行相同的操作。
  • .Parent中,您指的是更高级别的对象,例如你要 保存更改并关闭工作簿,但您指的是 现在Sheets(1),您无法关闭,因此在.Parent中,您指的是工作簿(Report)。出于安全原因,我对此发表了评论。

Sub CommandButton2_Click()

    Dim Report As Workbook
    Dim lRow As Long

    Set Report = Workbooks.Open("S:\HR Compensation\Christapher Martin\" _
            & "Tellurian Inc Job Pricing\Job Families and Competencies " _
            & "- Report.xlsm")

    With ThisWorkbook.Sheets(2)
        lRow = .Cells(.Rows.Count, 3).End(xlUp).Row
        .Range(.Cells(8, 3), .Cells(lRow, 3)).Copy
    End With

    With Report.Sheets(1)
        .Range("B2").PasteSpecial Transpose:=True
        '.Parent.Close True ' Save changes and close workbook.
    End With

    Application.CutCopyMode = False

End Sub