隐藏的工作簿应用程序中的Excel vba selection.copy不起作用

时间:2017-08-03 09:39:04

标签: excel vba excel-vba

我有一个主工作簿,其中包含宏和隐藏的工作簿,其中包含以下打开的数据:

Dim ExcelApp As Object
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.Visible = False
ExcelApp.ScreenUpdating =  False
ExcelApp.DisplayAlerts = False
ExcelApp.EnableEvents = False
Dim creditsWorkbook As Workbook
Set creditsWorkbook = ExcelApp.Application.Workbooks.Open("P:\2017\" & DATA & ".xlsx")

稍后在代码中我选择该数据工作簿中的一个范围并将其复制,然后将其粘贴到主工作簿中:

creditsWorkbook.Worksheets("List1").Range(creditsWorkbook.Worksheets("List1").Cells(5, 1), creditsWorkbook.Worksheets("List1").Cells(lastStr3, lastStb3)).Select
creditsWorkbook.Worksheets("List1").Activate
'creditsWorkbook.Worksheets("List1").Selection.Copy   '<--- error
Selection.Copy  <--- works, but copies from the Main workbook wrong stuff
Windows("Main.xlsm").Activate
Sheets("Credit portfolio").Select
Range("a4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

lastStr3lastStb3只是包含要从creditsWorkbook中选择的行数和列数的整数。选择工作正常(我可以在打开可见性时看到它),但复制方法变得混乱。

我首先尝试激活creditWorkbook,尝试指定要复制的内容creditsWorkbook.Worksheets("List1").Selection.Copy,但它只是错误object doesn't support this property or method。我不知道如何才能获得所需的结果。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

尽可能避免使用Select

With creditsWorkbook.Worksheets("List1")
    .Range(.Cells(5, 1), .Cells(lastStr3, lastStb3)).Copy
End With
Windows("Main.xlsm").Sheets("Credit portfolio").Range("A4").PasteSpecial_ 
    Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False