Excel Automation in WebBrowser Control - vb.net

I am using the following code to display an Excel Spreadsheet in a WebBrowser Control in VB.net 2010 Express.
Option Explicit On
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Core
Imports System.Data
Public Class CustomerService
Dim oDocument As Object
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
Private Sub CustomerService_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WebBrowser1.Navigate(quoteFile)
End Sub
Private Sub WebBrowser1_NavigateComplete2(ByVal sender As Object, ByVal e As AxSHDocVw.DWebBrowserEvents2_NavigateComplete2Event) Handles WebBrowser1.NavigateComplete2
On Error Resume Next
Dim oXL As New Excel.Application
oDocument = e.pDisp.Document
With oDocument.Application.CommandBars("Standard")
.Position = 4 '[msoBarFloating]
.Visible = True
End With
MsgBox("File opened by: " & oDocument.Application.Name)
oDocument.Range("A1") = "HEllo"
End Sub
End Class
My question is, how can I reference the opened document in the WebBrowser1_NavigateComplete2 method so I can automate excel to say display text in a specific cell.
Tried:
Option Explicit On
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Core
Imports System.Data
Public Class CustomerService
Dim oDocument As Object
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
Private Sub CustomerService_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WebBrowser1.Navigate(quoteFile)
End Sub
Private Sub WebBrowser1_NavigateComplete2(ByVal sender As Object, ByVal e As AxSHDocVw.DWebBrowserEvents2_NavigateComplete2Event) Handles WebBrowser1.NavigateComplete2
On Error Resume Next
Dim oXL As New Excel.Application
oDocument = e.pDisp.Document
objApp = oDocument
objBooks = objApp.Workbooks
objBook = objBooks.Add
objSheets = objBook.Worksheets
objSheet = objSheets(1)
oXL = oDocument(.Document) 'with or without .Document
With oDocument.Application.CommandBars("Standard")
.Position = 4 '[msoBarFloating]
.Visible = True
End With
MsgBox("File opened by: " & oDocument.Application.Name)
objSheet.Range("A1") = "HEllo"
End Sub
End Class
With no luck. If you even have an inkling of a way to take this, I am all ears.
Thanks

Does changing the last line to include the sheet solve the problem?
oDocument.worksheets(1).Range("A1") = "HEllo"
Are you getting an error or is it just not doing anything? Do you get your msgbox?

Related

declaring New Microsoft.Office.Interop.Excel.Application outside of Sub makes the VSTO COM addin to freeze during loading

I have created an Excel COM add in which opens a windows form from a ribbon button. I want to populate the combobox using data from an external excel spreadsheet as well as populate the textboxes based on the selected name.
The part of the form where this applies
when placing the block of code:
Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
Dim ClientListSheet = ClientListBook.Sheets(1)
below the Public Class Form1 as seen below:
Imports Microsoft.Office.Interop.Excel
Public Class Form1
Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
Dim ClientListSheet = ClientListBook.Sheets(1)
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbClientName.SelectedIndexChanged
End Sub
it causes the Add in to freeze
But when Placing the same block of code into the Sub Form1_Load and Sub ComboBox1 as seen below, the add in works although it is very slow and i suspect it is an incorrect implementation.
THIS IS THE WORKING FULL CODE FOR THE FORM:
Imports Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbClientName.SelectedIndexChanged
Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
Dim ClientListSheet = ClientListBook.Sheets(1)
Dim iStartedRow As Integer
Dim iTotalRows As Integer
' count the number of rows in the worksheet
iTotalRows = ExcelApp.ActiveWorkbook.Sheets(1).Range("a1").CurrentRegion.Rows.Count
' populates the textboxes using clientList data
For iStartedRow = 2 To iTotalRows
If Me.cmbClientName.Text = ClientListSheet.Cells(iStartedRow, 1).text Then
Me.txtSal.Text = ClientListSheet.Cells(iStartedRow, 4).text
Me.txtInvMan.Text = ClientListSheet.Cells(iStartedRow, 5).text
End If
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
Dim ClientListSheet = ClientListBook.Sheets(1)
Dim StartedRow As Integer
Dim TotalRows As Integer
' clear any existing data
Me.cmbClientName.Items.Clear()
' count the number of rows in the worksheet
TotalRows = ExcelApp.ActiveWorkbook.Sheets(1).Range("a1").CurrentRegion.Rows.Count
' create a loop to add data into combobox
For StartedRow = 2 To TotalRows
Me.cmbClientName.Items.Add(ClientListSheet.Cells(StartedRow, 1).Text)
Next
End Sub
End Class
Please would you let me know how i can correctly implement this and if it would be better and faster to use Microsoft Access database instead. I am new to VSTO COM add ins and VB.Net, this is my first project so i understand that my implementation may be suboptimal and will appreciate all feedback.
Thank you
If you declare and initialize these variables on the class level, they are created when the constructor runs.
There is absolutely no reason to initialize them immediately - you can declare them on the class level, but create them only when needed
Moreover, if your code is running in a VSTO addin, there is absolutely no reason to create an instance of the Excel.Application object - it is already available to you.
Hardcoding the file path is obviously also a problem...
Public Class Form1
Dim ExcelAppe
Dim ClientListBook
Dim ClientListSheet
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ExcelApp = Globals.ThisAddin.Application
ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
ClientListSheet = ClientListBook.Sheets(1)

For Next loop error: Option Strict On disallows late binding

I have the following code which produces an error:
Option Strict On
Imports Microsoft.Office.Interop
Public Class Form1
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
xlWorkBook = xlApp.Workbooks.Open("C:\Book1.xlsx")
xlApp.Visible = True
For i = 1 To xlWorkBook.Worksheets.Count
xlWorkBook.Worksheets(i).Visible = True
Next
End Sub
End Class
Thank you.
I guess what you are after is:
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
xlWorkBook = xlApp.Workbooks.Open("C:\Book1.xlsx")
xlApp.Visible = True
For i = 1 To xlWorkBook.Worksheets.Count
xlWorkSheet = CType(xlWorkBook.Worksheets(i), Excel.Worksheet)
xlWorkSheet.Visible = Excel.XlSheetVisibility.xlSheetVisible
'If you don't want to make use of xlWorkSheet you can use this:
'CType(xlWorkBook.Sheets(i), Excel.Worksheet).Visible = Excel.XlSheetVisibility.xlSheetHidden
Next
End Sub
You should always look at using the object as this will provide the correct usage of the object's properties. Note the change of Visible = True to Visible = Excel.XlSheetVisibility.xlSheetVisible

how to export all items in listbox to excel in vb

i'm using vb windows form.
I'm trying to export all items in a listbox1 to excel file using a button, but the problem that it export only the first item
i want to export all the listbox1 items
here is my code
Imports Microsoft.Office.Interop
Public Class Form1
Dim MsExcel As Excel.Application
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsExcel = CreateObject("Excel.Application")
MsExcel.Workbooks.Add()
MsExcel.Range("A1").Value = ListBox1.Items
MsExcel.Visible = True
End Sub
End Class
You'll need to loop through the item and increment the row you print in :
Imports Microsoft.Office.Interop
Public Class Form1
Dim oItem As Object
Dim OffS As Integer
Dim MsExcel As Excel.Application
Dim Wb As Excel.Workbook
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsExcel = CreateObject("Excel.Application")
Set Wb = MsExcel.Workbooks.Open("Path_of_File")
OffS = 0
For Each oItem In ListBox1.Items
Wb.Sheets(1).Range("A1").Offset(OffS, 0).Value = oItem
OffS = OffS + 1
Next oItem
Wb.SaveAs
DoEvents
Wb.Close
MsExcel.Visible = True
End Sub
End Class

file not found comException error

I am trying to save a jpg file into an excel document.
I am getting the exception System.Runtime.InteropServices.COMException{"The specified file wasn't found"}
now the file does exist and is located at C:\test\101.jpg
here is my code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
'add some text
xlWorkSheet.Cells(1, 1) = "http://vb.net-informations.com"
xlWorkSheet.Cells(2, 1) = "Adding picture in Excel File"
'the file c:\test101.jpg does exist?
xlWorkSheet.Shapes.AddPicture("C:\test\l01.jpg", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45)
xlWorkSheet.SaveAs("C:\test\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Excel file created , you can find the file c:\test\")
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()
End Try
End Sub
End Class
the file does exist so I am unsure why I am getting this error and how to correct it??
this is on a windows 8.1 visual studio 2008 3.5 sp1 platform
Any thoughts are greatly appreciated.

Can't access form1 from another class

I have a class called class1, in that class i wan;t to write something in a textbox in form1, but it won't let me access Form1.TextBox1.text, another problem is that it won't give me the save dialog in excel, but thats another problem.
How can i acces Form1 controls?
Form1 code
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call ThisDrawing.GetFilepath(True)
If Me.TextBox1.Text = "" Or Me.TextBox1.Text = "False" Then MsgBox("Er is geen geldige filenaam opgegeven")
End Sub
Class1 code
Public Shared Sub GetFilepath(ByVal hide As Boolean)
Dim Xl As New Excel.Application
Dim Filepath As String
Call ExcelKoppelen("Z:\test\test.xls")
Filepath = Xl.GetSaveAsFilename("", "Excel file", "*.xls")
Form1.TextBox1.text = Filepath
End Sub
Excelkoppelen code
Shared Sub ExcelKoppelen(ByVal Bestand As String)
Dim Xl As Excel.Application
Dim Filepath As String
Dim Workbook As Excel.Workbook
Dim Worksheet1 As Worksheet
Dim Worksheet2 As Worksheet
On Error Resume Next
Xl = GetObject(, "Excel.application")
If Err.Number Then
Information.Err.Clear()
Xl = CreateObject("Excel.application")
End If
Xl.Visible = True
Xl.ScreenUpdating = True
Workbook = Xl.Workbooks.Open(Bestand)
If Err.Number Then
Workbook = Xl.Workbooks.Open("Z:\test\test.xls")
Information.Err.Clear()
Workbook.SaveAs(Bestand)
End If
If Err.Number Then Exit Sub
On Error GoTo 0
Worksheet1 = Workbook.Worksheets.Item(1)
Worksheet2 = Workbook.Worksheets.Item(2)
Xl.Visible = False
End Sub
You can not access the controls in Form1 directly like that, create an object for Form1 as follows and get the controls by using the object.
Dim F as New Form1
F.TextBox1.text = Filepath