我试图将一系列数据从一个工作表复制到另一个工作表

时间:2014-09-29 19:32:12

标签: excel vba excel-vba copy excel-2013

当我尝试将workbook1的sheet1复制到workbook2的sheet2时,除了复制选择框之外,它不会在sheet2上显示任何内容。如果我评论出Activeworkbook.Close。工作簿1是开放的,也是适当的工作表。但不仅不是复制,而且当我按下控制粘贴时,它实际上将sheet2粘贴到自身。所以我尝试了Range(单元格(2,1),单元格(lastrow,lastcolumn))。选择不关闭我想要复制的工作簿来验证它是否至少会选择所需的范围,但它会返回一个欠幅错误时间错误'1004 '。如果有人看到我的错误,请帮助。谢谢

Dim directory As String, FileName As String
Dim lastrow As Long, lastcolumn As Long
Dim erow As Long

Application.ScreenUpdating = False
'Application.DisplayAlerts = False

directory = "C:\Users\Documents\file1\"
FileName = Dir(directory & "*.xl??")

'Open the Excel file
Workbooks.Open (directory & FileName)

'Select the worksheet and range of the worksheet to be copied
Worksheets("Luminaire Summary").Select
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
lastcolumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Range(Cells(2, 1), Cells(lastrow, lastcolumn)).Copy
'ActiveWorkbook.Close
erow = Sheet7.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Sheet2").Range(Cells(2, 1), Cells(lastrow, lastcolumn))

我尝试在一些建议后写一个较短的代码,但我仍然没有从workbook1 sheet1到workbook2 sheet2获取任何复制的信息。这是我最后一次没有成功的尝试

Private Sub CommandButton1_Click()
Dim directory As String, FileName As String, total As Integer
Dim lastrow As Long, lastcolumn As Long  
directory = "C:\Users\Documents\"
FileName = Dir(directory & "*.xl??")       
Workbooks.Open (directory & FileName)    
Worksheets("Luminaire Summary").Select
UsedRange.Copy
ActiveWorkbook.Close
Sheets("Sheet2").Range("A1").PasteSpecial

1 个答案:

答案 0 :(得分:0)

您可以使用UsedRange

进行简化
Worksheets("Luminaire Summary").Select
UsedRange.Copy
Sheets("Sheet2").Range("A1").PasteSpecial <-- 'or however you're determiing which cell to paste to