简体   繁体   中英

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. Also "Sheet1" exists in this workbook. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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