我正在尝试从“数据库”工作簿中选择复制所有内容。并将其粘贴到当前工作簿,工作表5中。我使用的代码如下。
Sub Import()
Dim DBaseWB As Workbook
Set DBaseWB = Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False)
' set DBaseWB as the database workbook after opening it from sharepoint.
Dim DBaseSheet As Worksheet
Set DBaseSheet = DBaseWB.Sheets(1) 'DBaseSheet is referenced to sheet 1 of Database workbook.
Sheet5.Cells.Clear
DBaseSheet.UsedRange.Copy 'Copy everything from the database
Sheet5.Range("A1").PasteSpecial xlPasteAll 'Paste everything in sheet 5 of current workbook
Application.DisplayAlerts = False
DBaseWB.Close saveChanges:=False
Application.DisplayAlerts = True
End Sub
运行以下代码时收到错误。虽然,有时它不会给我一个错误。
运行时错误'1004':Range类的PasteSpecial方法失败
我想我知道为什么它会在PasteSpecial行给我一个错误。当我在表5中选择了不同的单元格时,它没有给我任何错误。但是当我重新检查时,没有选择任何其他单元格(因此它将选择粘贴范围),我收到此错误。
我尝试在copy和pastespecial之间使用以下行,
Sheet5.range("A1").select
它给了我同样的错误。
---------- ---------- UPDATE
我第一次使用DisplayName的解决方案,它一直工作到昨天。但今天早上,它造成了问题。这是另一个错误。然后我尝试了所有其他解决方案,没有运气。都给了我同样的错误。我还将workbook.worksheet添加到下面的解决方案中,但没有给我带来好运。这次错误与复制方法有关。我也注意到很多专栏都说#REF。
我试过的版本:
DisplayName的解决方案与thisworkbook.worksheet结合使用
Sheet5.UsedRange.Clear
With Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False) 'open and reference your Database workbook
.Sheets(1).UsedRange.Copy Destination:=ThisWorkbook.Sheets(5).Range("A1") ' copy referenced workbook sheet 1 content and paste it to sheet 5
.Close False
End With
Gary的学生解决方案与thisworkbook.worksheet结合使用
Dim DBaseWB As Workbook
Set DBaseWB = Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False)
' set DBaseWB as the database workbook after opening it from sharepoint.
Dim DBaseSheet As Worksheet
Set DBaseSheet = DBaseWB.Sheets(1) 'DBaseSheet is referenced to sheet 1 of Database workbook.
Dim Destination As Worksheet
Set DestinSh = ThisWorkbook.Sheets(5)
Sheet5.Cells.Clear
DBaseSheet.UsedRange.Copy DestinSh.Range("A1").PasteSpecial 'copy database info in planning tool.
Application.DisplayAlerts = False
DBaseWB.Close saveChanges:=False
Application.DisplayAlerts = True
错误:
运行时错误'1004':Range类的复制方法失败
答案 0 :(得分:0)
首先确保工作表上有没有合并的单元格,然后尝试:
DBaseSheet.UsedRange.Copy Sheet5.Range("A1")
答案 1 :(得分:0)
你可以简单地去:
Sub Import()
Sheet5.UsedRange.Clear
With Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False) 'open and reference your Database workbook
.Sheets(1).UsedRange.Copy Destination:=Sheet5.Range("A1") ' copy referenced workbook sheet 1 content and paste it to sheet 5
.Close False
End With
End Sub
答案 2 :(得分:0)
我和Bruce Wayne在一起
当您打开一个新工作簿时,现在的重点是该工作簿。
如果您尝试清除工作簿中的单元格,则在启动新工作簿并切换焦点后代码驻留在(目标)中,您需要引用原始工作簿来执行此操作,如下所示:
ThisWorkbook.Sheets(5).Cells.Clear
希望这有帮助