将粘贴自动范围从一个工作簿复制到另一个工作簿

时间:2018-06-13 13:01:44

标签: excel vba excel-vba

所以我试图从一本书到另一本书进行复制。我在网上到处搜索但是,我必须管理员,我不是那样进入VBA所以要正确理解人们提供的解决方案。我写的代码就是这个。 一步步: 我定义变量。定义从哪里获取与我想要打开的文件对应的年,月和日的范围。我打开文件。我将目的地书籍设置为我当前的书(我把按钮放在哪里)。然后我想找到我的标签的自动范围(因为每天的变化),我执行列的计数(-5,因为我不需要最后5列)和各种课程中讨论的行。但是......打开书本后,代码停止了(wkbk)。这是为什么?出现的错误是:应用程序定义或对象定义错误。

    Sub Opentrading()

Dim FolderPath As String
Dim Path As String
Dim nyear As String
Dim nmont As String
Dim nday As String
Dim wkbk As Workbook
Dim mybook As Workbook
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Dim sht As Worksheet

FolderPath = "F:\FICM\Trading Runs\Daily Trading Runs"
nyear = Sheet6.Range("J3")
nmont = Sheet6.Range("J5")
nday = Sheet6.Range("J7")
Path = FolderPath & "\" & nyear & "-" & nmont & "-" & nday & " Trading - Southern_Europe" & ".xlsx"
Set mybook = ThisWorkbook
Set wkbk = Workbooks.Open(Path)
Set sht = wkbk.Sheets("Southern_Europe")

'Find Last Row and Column
Set StartCell = Range("D1")
  LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
  LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

'Select Range
 wkbk.Worksheets("Southern_Europe").Range(StartCell, sht.Cells(LastRow, LastColumn - 5)).Copy mybook.Worksheets("Prova").Range("Z1")

  wkbk.Close
End Sub

1 个答案:

答案 0 :(得分:0)

变化:

Set StartCell = Range("D1")

要:

Set StartCell = sht.Range("D1")

您正在使用StartCell

wkbk.Worksheets("Southern_Europe").Range(StartCell, sht.Cells(LastRow, LastColumn - 5)).Copy

如果StartCell未正确声明,则它不属于工作表“Southern_Europe”。相反,它需要ActiveSheet或当前的工作表。