简体   繁体   English

使用Select方法时将Excel.Workbook对象设置为ThisWorkbook的错误1004

[英]Error 1004 on Excel.Workbook object set as ThisWorkbook while using Select method

I can't wrap my head around this issue. 我无法解决这个问题。 I could swear I have done this countless times before but for some reason it keeps erroring out on me. 我可以发誓之前我已经做过无数次了,但是由于某种原因,它总是使我误解。

The problem goes like this: 问题是这样的:

Dim FromPath As String
Dim ToPath As String
Dim wb As Excel.Workbook
Dim curr_wb As Excel.Workbook
Dim StrFile As String

Set curr_wb = ThisWorkbook
Set wb = Workbooks.Open(FromPath & StrFile)

'grabbing some data from one file
wb.Sheets("Customer Information").Range("A2:AA2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy

'pasting it on current file
 curr_wb.Sheets("Sheet1").Range("A1").Select '<--------error 1004: select method of range failed
'''''''''' The rest of the code not relevant to problem ''''''''''''

Now I cannot for the life of me figure out why this is failing. 现在,我无法为自己的一生弄清楚为什么会失败。 I look into the locals window I can see that curr_wb is indeed set as the workbook the macro is running from. 我查看“本地”窗口,可以看到curr_wb确实设置为运行宏的工作簿。 Also "Sheet1" exists in this workbook. 此工作簿中也存在“ Sheet1”。 The curr_wb and wb variables should be the same type of datatype, how can the select method work on one while not work on the other? curr_wb和wb变量应该是相同类型的数据类型,select方法如何在一个方法上起作用而在另一方法上不起作用?

Your help is greatly appreciated, 非常感谢您的帮助,

正如SJR所评论的,如果我在进行选择之前立即设置curr_wb.Activate,则此代码有效。

You could reduce your copying/pasting code to 您可以将复制/粘贴代码减少为

With wb.Sheets("Customer Information")
    .Range("A2:AA2", .Range("A2:AA2").End(xlDown)).Copy curr_wb.Sheets("Sheet1").Range("A1")
End With

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM