I want below code to open a closed workbook and copy the values from the range StartRow and EndRow to active workbook.
I get
error 1004 "No such interface supported".
on line "xlBook.Sheets(ShName).Range(Cells(StartRow, 1), Cells(EndRow, 1)).Select"
When I run this code directly in the workbook I want to copy the data from, it works.
Sub GetDataFromClosedBook()
'copy data from closed workbook to active workbook
Dim xlApp As Application
Dim xlBook As Workbook
Dim sh As Object
Set xlApp = CreateObject("Excel.Application")
'Path source Wokrbook
Set xlBook = xlApp.Workbooks.Open("C:\Users\name\Desktop\EXCEL USEFUL DOSC\Missing Data Check New Process\Missing Data Reports\" & Sheets("Data Check").Range("C3").Value & ".xlsx")
xlApp.Visible = True
ShName = Sheets("Data Check").Range("C3").Value
With xlBook.Sheets(ShName)
StartRow = .Range("E:E").Find(what:="January-2020", after:=.Range("E1")).Row
EndRow = .Range("E:E").Find(what:="January-2020", after:=.Range("E1"), searchdirection:=xlPrevious).Row
'ThisWorkbook.Activate
xlBook.Sheets(ShName).Range("A2").Value = ShName
xlBook.Sheets(ShName).Range(Cells(StartRow, 1), Cells(EndRow, 1)).Select
'Sheets(ShName).Range(Cells(StartRow, 1), Cells(EndRow, 1)).Select
End With
xlApp.DisplayAlerts = False
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
Set xlBook = ActiveWorkbook
Set sh = Sheets("Dealer_ID Check")
sh.Activate
Range("A1").Select
sh.Paste
End Sub
xlBook.Sheets(ShName)
is the active sheet. YourCells
references are not qualified, so they assumeActiveSheet
and if you try to use them inside of a range that refers to a different sheet, you will get an error. They do not automatically assume you are referring to the same sheet as you probably think they should. – braXSheets("Data Check").Range("C3").Value
as both File name and Sheet name. Is that deliberate? You don'tCopy
anything, so there's nothing to paste. WithFind
you need to specify several other parameters. Don't rely onSelect
, use references. Beware implicit ActiveSheet references. Handle the case ofFind
returningNothing
. Handle File Not Found error. Is this code in Excel? If so, why create another instance? – chris neilsenxlBook.Sheets(ShName).Activate
before referencing the firs and last row? Sorry I cannot check this right now. I will look into this tomorrow. – MichalSelect
to check if I referencing the right range and I know i do not copy paste as the code is not 100% finished because I stuck on this error, and when I sued copy it gives me the same error. NOt sure what other parameters I would have to use, the ``.Find``` is working as expected in this instance. Yes it is in EXCEL. and I anm not sure what you mean by "Handle the case of Find returning Nothing. Handle File Not Found error. Is this code in Excel? If so, why create another instance?" – Michal