0
 Dim oExcel As Excel.ApplicationClass = New Excel.ApplicationClass
            Dim objWS As New Microsoft.Office.Interop.Excel.Worksheet
            Dim oBook As Excel.WorkbookClass
            Dim oBooks As Excel.WorkbookClass

            'Start Excel and open the workbook.
            oExcel = CreateObject("Excel.Application")
            oExcel.Visible = True
            oBooks = oExcel.Workbooks
            oBook = oBooks.Open("H:\Copy of Book1.xlsm")

Hi there! I have an error of Invalid Cast Exception at oExcel = CreateObject("Excel.Application")

I'm using Visual Basic and I'm trying to open my excel file which is named Copy of Book1. I'm also using Microsoft Excel 2010. Any idea how to fix that error? Thank you in advance!

Slai
  • 22,144
  • 5
  • 45
  • 53
  • Try `Set oExcel = CreateObject("Excel.Application")` – Fratyx Mar 02 '18 at 07:05
  • Nope, doesn't work :/ – Crystal Mar 02 '18 at 07:12
  • This is not Excel VBA code, it looks like Viusal Studio VBA code. What do you want to do? If you just want to start Excel and opne a file see my proposal below – Storax Mar 02 '18 at 07:56
  • I wonder, what is `Excel.ApplicationClass` exactly? Isn't it `Excel.Application`? – AntiDrondert Mar 02 '18 at 08:05
  • Starting up Excel.exe *twice* is not useful. The New Excel.ApplicationClass statement is enough, no need for CreateObject() again. Always favor using the interface instead of the fake class wrapper, important to take advantage of the highly desirable Embed Interop Types feature. [More here](https://stackoverflow.com/a/21018418/17034). Tends to be very confusing (create an interface instead of a class object??) but permitted in COM client code. – Hans Passant Mar 02 '18 at 08:18

2 Answers2

0

Try this:

Sub openExcel()
Dim objExcel As Excel.Application
Set objExcel = CreateObject("Excel.Application")
Dim ws As Worksheet
Dim wb As Workbook

objExcel.Visible = True
Set wb = objExcel.Workbooks.Open("H:\Copy of Book1.xlsm")
End Sub
Plagon
  • 2,689
  • 1
  • 11
  • 23
0

As said in the comment if you just want to start Excel and open a file change the code as follows

Dim oExcel As Excel.Application = New Excel.Application
Dim oBook As Excel.Workbook

'Start Excel and open the workbook.    
oExcel.Visible = True
oBook = oExcel.Workbooks.Open("H:\Copy of Book1.xlsm")
Storax
  • 11,158
  • 3
  • 16
  • 33
  • Thank you for the valuable answer. However, I have an error of "Type Excel.Application is not defined". Do i need to add any more references to my project? Currently I have: – Crystal Mar 05 '18 at 02:59
  • Imports Excel = Microsoft.Office.Interop.Excel and Imports Microsoft.Office.Interop – Crystal Mar 05 '18 at 02:59