COM Error trying to create Excel.Application object - vb.net

Working from Visual Studio 2013 to create a new program involving excel. Done this before in earliere excel versions, but cannot get it to work now.
Trying to create the excel application object throws an error (however an excel process is started when I look in the task manager). We're using Office 365 with Excel 2016. I have uninstalled Office and made a complete new installation, but still having the same error.
Having a vb .net windows project. I haved added a reference by choosing COM - Type Libraries - and added Microsoft Excel 16.0 Object Library (version 1.9).
Code is like this:
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim appXL As Excel.Application
Dim wbXl As Excel.Workbook
Dim shXL As Excel.Worksheet
Dim raXL As Excel.Range
' Start Excel and get Application object.
appXL = CreateObject("Excel.Application")
appXL.Visible = True
appXL = CreateObject("Excel.Application")
throws error :
An unhandled exception of type 'System.InvalidCastException' occurred in WindowsApplication3.exe
Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: Interface not registered (Exception from HRESULT: 0x80040155).
I have checked registry editor in HKEY_CLASSES_ROOT - typelib and found the IID {000208D5-0000-0000-C000-000000000046}. It looks like this:
TypeLib (Default) REG_SZ {00020813-0000-0000-C000- 000000000046}
Version REG_SZ 1.9
Any help will be much appreciated. Thanks.

Related

Getting the count of sheets in debug mode - MS Excel PIA

I cannot access .Count property of Sheets. I'm using Excel Interop. I'm in debug mode and I'm trying this:
?xlSheets.Count
This results in:
(1) : error BC30456: 'Count' is not a member of 'Sheets'.
I have no clue on what's wrong, as I see in MSDN that there is such property!
This works well: ?xlSheets(1).Name. But Count fails... Is it possible to get the count of sheets?
These guys had a similar problem - they wanted to .Worksheets.Add(.Worksheets.Sheets.Count). Finally they did not get the count, they went for .Worksheets.Add(After:=.Worksheets(3))...
UPDATE:
To my great delight, after further trying / experimentations, it became clear that in debug modeSheets.Count does not work only when there is no such line in the code.
While debugging this code, I can access Sheets.Count, because this line exists in the code.
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkbooks As Excel.Workbooks
Dim xlSheets As Excel.Sheets
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
xlApp = New Excel.Application
xlWorkbooks = xlApp.Workbooks
xlWorkBook = xlWorkbooks.Open("C:\Temp\Template.xlsm")
xlSheets = xlWorkBook.Sheets
MessageBox.Show(xlSheets.Count)
xlWorkBook.Close()
xlApp.Quit()
'Clean Up
releaseObject(xlSheets)
releaseObject(xlWorkBook)
releaseObject(xlWorkbooks)
releaseObject(xlApp)
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
GC.WaitForPendingFinalizers()
End Try
End Sub
End Class
But when I replace MessageBox.Show(xlSheets.Count) with MessageBox.Show(xlSheets.Creator), the error appears when trying to ?xlSheets.Count. I don't yet know the reason of such behaviour (I come from VBA environment where debug mode seems to be more flexible), but at least that works during run time...
If someone knows how to fix this, please let me know, as I feel restricted while testing small things in debug mode!
Use Project > Properties > References. Locate and select the "Microsoft Excel xx.x Object Library" entry. In the Properties window, set the Embed Interop Types property to False. Use Build > Rebuild to rebuild your app. It will now work the way you expected.
Briefly, this option is a strong optimization for COM interop libraries, like Microsoft.Office.Interop.Excel, you no longer have a runtime dependency on the library. The compiler copies the interop types from the library into your program's executable, only the ones you actually need to run your program. Explains your discovery, the Count property is in fact missing when you don't use it in your program.
You don't want to leave it this way, set the property back to True after you're done testing.
Your code works fine for me. I notice the file type is a macro-enabled workbook. Have you set your macro settings properly on your dev PC? By default Excel will disable macros.
Edit: I think I get your problem now. You are getting the error when trying to print the property in debug mode. Probably you have stopped the code at a point where the variable is not set (.Count is only available while the button code is actually running). Put a breakpoint on the message box line, click the button, and try again.

Excel 15 VBA fails to sink events from IE on Windows 8.1

I'm in Excel VBA and playing with COM libraries. In the past I have sunk events thrown by HTMLDocument with VBA code (this is play for me!). This no longer seems to work. I have investigated and got plenty of detail to offer. I have drilled into the type libraries with OleView and have annotated the VBA code with what I believe is going on underneath. This might be a bug or it might be something that I've just plain messed up on. Please help.
The objective is to get the code in doc_ondblclick running, i.e. to get the event handler wired up. At the moment although I can get to one IHTMLDocument interface (thanks to StackOverflow answer to another question); I cannot successfully get to the interface that sources the events.
UPDATE:THIS CODE WORKS ON AN OLD LAPTOP RUNNING Windows XP, Excel 2007, IE8! So I think this is a bug!
**FURTHER UPDATE: I suspect this technology is too old and has now been abandoned by Microsoft in IE11 onwards http://msdn.microsoft.com/en-us/library/ie/bg182625%28v=vs.85%29.aspx#legacyAPIs. To observe a mutation Microsoft have Mutation observers http://msdn.microsoft.com/en-us/library/ie/dn265034%28v=vs.85%29.aspx
Option Explicit
'* Attribute VB_Name = "DHTMLHandler"
'* Environment:
'* Windows 8.1 64 bit;
'* Excel Microsoft Office Home and Student 2013, Version: 15.0.4551.1512
'* Tools->References indicate following libraries checked
'* VBA : Visual Basic For Applications {000204EF-0000-0000-C000-000000000046} C:\Program Files (x86)\Common Files\Microsoft Shared\VBA\VBA7.1\VBE7.DLL
'* Excel : Microsoft Excel 15.0 Object Library {00020813-0000-0000-C000-000000000046} C:\Program Files\Microsoft Office 15\Root\Office15\EXCEL.EXE
'* stdole : OLE Automation {00020430-0000-0000-C000-000000000046} C:\Windows\SysWOW64\stdole2.tlb
'* Office : Microsoft Office 15.0 Object Library {2DF8D04C-5BFA-101B-BDE5-00AA0044DE52} C:\Program Files (x86)\Common Files\Microsoft Shared\OFFICE15\MSO.DLL
'* SHDocVw: Microsoft Internet Controls {EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B} C:\Windows\SysWOW64\ieframe.dll
'* MSHTML : Microsoft HTML Object Library {3050F1C5-98B5-11CF-BB82-00AA00BDCE0B} C:\Windows\SysWOW64\mshtml.tlb
'* Based on code at http://support.microsoft.com/kb/246247
'* In the MSHTML type library we have these following lines for coclass HTMLDocument, indicating events interfaces (marked with "[source]")
'coclass HTMLDocument {
' [default] dispinterface DispHTMLDocument;
' [default, source] dispinterface HTMLDocumentEvents;
' [source] dispinterface HTMLDocumentEvents2;
' [source] dispinterface HTMLDocumentEvents3;
' [source] dispinterface HTMLDocumentEvents4;
'* I'd say the following line looks like it should start sinking events defined by HTMLDocumentEvents because in VBA we can only sink the [default] [source] interface
Dim WithEvents doc As HTMLDocument '* this is what I want
Dim docNoEvents As IHTMLDocument2 '* I know this works, it QIs successfully but it won't sink events!
Private Function doc_ondblclick() As Boolean
'* An example of an event being handled (at least that is if I could get the wiring to work)
Debug.Print "dblclick"
End Function
Public Sub Test()
'* this method is called from Module1 which simply instantiates this class : Dim handler As New DHTMLHandler: handler.Test
Dim ie As SHDocVw.InternetExplorer
Set ie = New SHDocVw.InternetExplorer
ie.Navigate "www.bbc.co.uk/weather"
ie.Visible = True
While ie.Busy
DoEvents
Wend
'* following on from example code at http://support.microsoft.com/kb/246247 it can seen the HTMLDocument object is
'* acquired from a browser level object. In the SHDocVw type library looking there is only 1 browser interface
'* defined which exports a Document method and that is IWebBrowser
'interface IWebBrowser : IDispatch { ...
' [id(0x000000cb), propget, helpstring("Returns the active Document automation object, if any.")]
' HRESULT Document([out, retval] IDispatch** ppDisp);
'...}
Dim itfWebBrowser As IWebBrowser
Set itfWebBrowser = ie '* QueryInterfaces for IWebBrowser
Set docNoEvents = itfWebBrowser.Document
Debug.Assert TypeName(ie.Document) = "HTMLDocument" 'Re G Serg
'* Following lines error for me with "Type Mismatch", if it fails for you please confirm by posting.
Set doc = docNoEvents
'Also the following (shorter, simpler version) doesn't work
'Set doc = ie.Document
End Sub

Importing data from excel sheet

Using MS VS 2013 and SQL server 2012
I am writing a console app to copy some data from excel into an SQL table. I am not getting very far. The code below opens the file then after 2-3 seconds I get an error.
There error is -
Additional information: Unable to cast COM object of type
'System.__ComObject' to interface type
'Microsoft.Office.Interop.Excel.Worksheet'. This operation failed
because the QueryInterface call on the COM component for the interface
with IID '{000208D8-0000-0000-C000-000000000046}' failed due to the
following error: No such interface supported (Exception from HRESULT:
0x80004002 (E_NOINTERFACE)).
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop
Imports System.Data.SqlClient
Imports System.IO
Module Module1
Sub Main()
Dim xlApp As Application
Dim xlWorkBookSrc As Excel.Workbook
Dim xlWorkBookDest As Excel.Workbook
Dim xlWorkSheetSrc As Excel.Worksheet
Dim xlWorkSheetDest As Excel.Worksheet
xlApp = New Excel.Application
xlApp.Visible = True
xlApp.DisplayAlerts = False
xlWorkSheetSrc = xlApp.Workbooks.Open("Folder path")
xlWorkSheetSrc = xlWorkBookSrc.Worksheets("Spectrometer")
End Sub
End Module
As the file opens ok I am not sure why I then get the error. The excel sheet is a .xls but I also tried with an .xlsx and get the same result.
Any ideas
This line:
xlWorkSheetSrc = xlApp.Workbooks.Open("Folder path")
..is failing because its defines xlWorkSheetSrc as a Worksheet and xlApp.Workbooks.Open is returning a Workbook, which is not a Worksheet. Change it to:
xlWorkBookSrc = xlApp.Workbooks.Open("Folder path")
..and it should be OK.
Refer Example given in Importing Exporting Excel Files
This Example in VB.NET and I tested and it's working fine in my PC.
I suggest to use OleDB (ADO.NET) to import excel data and export that data to SQL server (using SqlConnection (ADO.NET)).
Excel To SQL Server

VB.net Class Not Registered Error

I'm in the process of writing a VB application but whenever I run the application I get the error listed below:
"An error occurred creating the form. See Exception.InnerException for details. The error is: Retrieving the COM class factory for component with CLSID {11219420-1768-11D1-95BE-00609797EA4F} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))."
I have tried registering the shell32.dll file, I have looked in the registry for the entry {11219420-1768-11D1-95BE-00609797EA4F} but it does not exist, and I have tried compiling this application for x86.
Imports Shell32
Imports System.IO
Public Class frmIconChanger
Dim sh As ShellLinkObject = New ShellLinkObject
Private Sub btnBackupAndChange_Click(sender As Object, e As EventArgs) Handles btnBackupAndChange.Click
For Each desktopIcon In My.Computer.FileSystem.GetFiles("C:\Users\" + getUserName().ToString + "\Desktop")
Dim fileExtension As String = Path.GetExtension(desktopIcon)
If (fileExtension = ".lnk") Then
MsgBox(sh.GetIconLocation(desktopIcon).ToString)
End If
Next
End Sub
Private Function getUserName() As String
Return System.Environment.UserName.Trim
End Function
End Class
Other information: I am on a Windows 7 64-bit machine. I have .Net 4.0 and previous versions and am working in Visual Studio 2012. Also I have shell32.dll added as a reference in my project. Any help resolving this issue would be much appreciated.
Thanks.
Refer to this link Creating Links. Take a look at the "C" code and look for constants
CLSID_ShellLink
IID_IShellLink
Those are the values you need for the class and interface.
This other link is useful: IShellLink interface
This should be the GUIDs you need:
CLSID := "{00021401-0000-0000-C000-000000000046}"
IID := "{000214F9-0000-0000-C000-000000000046}"

Typecast exception from ShellBrowserWindow object to ShellFolderView object

Looking for help trying to figure out why this typecast is not working on my machine.
This code was provided as an answer to another question I had and it's not working for me. It works for the answer poster on their machine, but I'm get a an exception on the line trying to typecast from ShellBrowserWindow to ShellFolderView.
I am using Visual Studio Express 2013, running on Windows 7 Pro X64 Sp1. The target framework for the project is .Net Framework 4. I've added references to Microsoft Internet Controls and Microsoft Shell Controls and Automation and I've added the Imports statements for Shell32 and SHDocVw. DLL versions are as follows: shell32.dll = 6.1.7601.18517 and shdocvw.dll = 6.1.7601.1822 I'm not sure what I could be missing.
The code looks like this. (This code is in a form object)
Imports EdmLib
Imports Shell32
Imports SHDocVw
Public Class BlankForm
Private Sub BlankForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim bar As String() = GetExplorerSelectedFiles()
Exit Sub
'The rest of my program is below this line - I'm just trying to test this one function right now...
End Sub
'Uses the windows shell to get the files selected in explorer
Public Function GetExplorerSelectedFiles() As String()
Dim ExplorerFiles As New List(Of String)
Dim exShell As New Shell32.Shell
Dim SFV As Shell32.ShellFolderView
For Each window As SHDocVw.ShellBrowserWindow In DirectCast(exShell.Windows, SHDocVw.IShellWindows)
If (window.Document).GetType.Name <> "HTMLDocumentClass" Then
SFV = CType(window.Document, ShellFolderView) '<--This is where it fails!!
For Each fi As FolderItem In SFV.SelectedItems
ExplorerFiles.Add(fi.Path)
Next
End If
Next
Return ExplorerFiles.ToArray
End Function
End Class
The line SFV = CType(window.Document, ShellFolderView) results in the following message:
An unhandled exception of type 'System.InvalidCastException' occurred
in LaunchTemplateEPDM.exe
Additional information: Unable to cast COM object of type
'System.__ComObject' to interface type 'Shell32.ShellFolderView'. This
operation failed because the QueryInterface call on the COM component
for the interface with IID '{29EC8E6C-46D3-411F-BAAA-611A6C9CAC66}'
failed due to the following error: No such interface supported
(Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
I've taken a screenshot of a quickwatch on the window object. A quickwatch on the window.document object shows an error saying it's either undefined or inaccessible.
I ran the query Microsoft.VisualBasic.Information.TypeName(window.document) and it returns "IShellFolderViewDual3".
I fixed it.
Not sure why this happens on my system and not yours.
What I found was that GetType.Name always just returns "System.__ComObject", regardless of whether the object is of type ShellFolderView, HTMLDocumentClass or something else. So what was happening was no matter what the actual type of the object was, it was passing the <>"HTMLDocumentClass" test because it was always evaluating to "System.__ComObject". Then when we tried to run the CType function on an object that didn't implement the ShellFolderView interface, it would throw that exception.
I eventually stumbled upon this article which led me to experiment with the TypeName Function which seems to return the actual type, and so I ended up with the working code below:
Public Function GetExplorerSelectedFiles() As String()
Dim ExplorerFiles As New List(Of String)
Dim exShell As New Shell32.Shell
For Each window As SHDocVw.ShellBrowserWindow In DirectCast(exShell.Windows, SHDocVw.IShellWindows)
If TypeName(window.Document) Like "IShellFolderViewDual*" Then
For Each fi As FolderItem In DirectCast(window.Document, ShellFolderView).SelectedItems
ExplorerFiles.Add(fi.Path)
Next
End If
Next
Return ExplorerFiles.ToArray
End Function