说明 - 使用PasteSpecial复制数据VBA代码

时间:2017-06-05 06:01:58

标签: excel vba excel-vba runtime

我有这两本工作簿。

我想将第一个工作簿中某些列的数据传输到工作簿2中的给定工作表。

我收到运行时错误(1004)。 方法'对象范围'工作表失败

我在代码中的这一行收到错误

 SummarySheet.Range(columnaddress & "8:" & columnaddress & lastrow).Copy 

这是完整的代码。

Sub RectangleRoundedCorners1_Click()

  Application.ScreenUpdating = False

  Dim MacroBook As Workbook, SummaryBook As Workbook, BSSBook As Workbook, _
    SummarySheet As Worksheet, TwoGonlyER As Worksheet, threeGswapRoll As Worksheet, _
    threeGswapER As Worksheet, fourGprData As Worksheet, threeGpRData As Worksheet
  Dim onlyER As Range, rolloutER As Range, swapER As Range, prData As Range, _
    gPRdata As Range, FolderPathForSummary As String, lastrow As Integer

  Set MacroBook = ThisWorkbook

  'Summary Book Open
  FolderPathForSummary = MacroBook.Worksheets("Tool").Range("D8")

  FolderPath = MacroBook.Worksheets("Tool").Range("D11")

  If Dir(FolderPath, vbDirectory) = "" Then
    MsgBox "Please enter a valid folder path to save the file!"
    Exit Sub
  End If

  If Not Dir(FolderPathForSummary) <> "" Then
    MsgBox " Summary file doesn't exist in your mentioned address. Please   check again!  "
    Exit Sub
  End If

  Set SummaryBook = Workbooks.Open(FolderPathForSummary)
  Set SummarySheet = SummaryBook.Worksheets("Summary Data")

  lastrow = SummarySheet.Cells(Rows.Count, "A").End(xlUp).Row

  'BSS Tracker Open
  Set BSSBook = Workbooks.Add
  BSSBook.SaveAs (FolderPath & "BSS Tracker " & Format(CStr(Now), "ddmmmyyyyhhmmss") & ".xlsx")

  MacroBook.Worksheets("2G Only ER").Copy before:=BSSBook.Sheets(1)
  Set TwoGonlyER = BSSBook.Worksheets("2G Only ER")

  MacroBook.Worksheets("3G Swap & 4G ROllout ER").Copy before:=BSSBook.Sheets(1)
  Set threeGswapRoll = BSSBook.Worksheets("3G Swap & 4G ROllout ER")

  MacroBook.Worksheets("3G & 4G Swap ER").Copy before:=BSSBook.Sheets(1)
  Set threeGswapER = BSSBook.Worksheets("3G & 4G Swap ER")

  MacroBook.Worksheets("4G PR Data").Copy before:=BSSBook.Sheets(1)
  Set fourGprData = BSSBook.Worksheets("4G PR Data")

  MacroBook.Worksheets("3G PR Data").Copy before:=BSSBook.Sheets(1)

  Set threeGpRData = BSSBook.Worksheets("3G PR Data")
  Set swapER = threeGswapER.Range("A3:P3")

  For Each entry In swapER

    columnaddress = entry.Value

    SummarySheet.Range(columnaddress & "8:" & columnaddress & lastrow).Copy
    entry.PasteSpecial

  Next entry

  BSSBook.Save
  BSSBook.Close

  SummaryBook.Save
  SummaryBook.Close

  MsgBox "BSS Tracker successfully generated!"

End Sub

1 个答案:

答案 0 :(得分:0)

根据您的代码,columnaddress应该是字符串变量,它应该包含列字母。像

Dim columnaddress As String
columnaddress = "A"

还有其他变量,例如SummarySheet,它引用了源表和引用目标表的条目表。

变量lastrow应该是一个长变量,它指的是带数据的最后一行。

因此,如果lastrow是25并且columnaddress是“A”,则按照以下行

SummarySheet.Range(columnaddress & "8:" & columnaddress & lastrow).Copy

然后复制摘要表格中的范围A8:A25并粘贴在条目表上。