List all opened WorkBooks in the Task Bar - vb.net

I am trying to list all the opened workbooks and their corresponding sheets in the task bar after that I should be able to select one workbook of the list and open it. My first try was to to show Excel process in Task-Manager but it only shows one open workbook without detecting the number of sheets.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim name As Process() = Process.GetProcessesByName("Excel")
For Each names In name
ListView1.Items.Add(names.MainWindowTitle)
If names.MainWindowTitle <> "" Then
ListBox1.Items.Add(names.MainWindowTitle)
End If
Next
End Sub
Next I tried to use this code but also I can only display one opened workbook, I don't know how to loop through them. I don't have problem of changing the whole code if you have any other method cause I am not sure that it's the solution.
Dim oXL As Microsoft.Office.Interop.Excel.Application
oXL = TryCast(System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"), Microsoft.Office.Interop.Excel.Application)
oXL.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlMinimized
Dim y As String
y = oXL.ActiveWorkbook.Name
ListBox1.Items.Add(y)

Dim objExcel As Excel.Application = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
Dim objWorkBook As Excel.Workbook = Nothing
Dim totalWorkBooks As Integer = objExcel.Workbooks.Count
For i As Integer = 1 To totalWorkBooks
objWorkBook = objExcel.Workbooks(i)
With objWorkBook
FullName = .FullName
OnlyName = .Name

Related

close instance of excel that does not have workbook associated with?

I have some blank instance of excel opened. I want to be able to close the instances of excel that does not have a workbook associated with it.
Public xlsApp As Excel.Application
Public xlsWB As Excel.Workbook
public openExcel()
Try
Dim path As String
path = "C:\excel.xlsm"
xlsWB = xlsApp.Workbooks.Open(path)
Catch ex As Exception
My.Application.Log.WriteException(ex, TraceEventType.Error, "Additional information or details")
Exit Sub
End Try
end sub
Public 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
====when run will open one excel, if excel window is close, the instance stays on, you will see the blank excel workbook. I want to close that instance when this sub re runs.
public doThis()
releaseObject(xlsApp)
releaseObject(xlsWB)
openExcel() <<==
end sub
For Excel to close properly you have to unload all of your COM objects
Dim xl As Excel.Application = New Excel.Application()
Dim wb As Excel.Workbook = xl.Workbooks.Add()
Dim ws As Excel.Worksheet = wb.Worksheets.Add()
wb.Close()
xl.Quit()
ReleaseComObject(ws)
ReleaseComObject(wb)
ReleaseComObject(xl)
ws = Nothing
wb = Nothing
xl = Nothing
If you aren't consuming the Excel instance and you are just displaying it then maybe try this. This will kill the process as soon as it is created so you'll want to put the p.Kill() in another place. Also note that this kills the process so no changes will be saved.
Dim p As System.Diagnostics.Process = System.Diagnostics.Process.Start(path)
p.Kill()

How to remove specific pages from word document

i am using vb.net and I have a word document that I am editing.
I want to remove the page break only from page 6 (for example ) to the end of the document and not from the entire document.
The code I have is for the entire document - How should I change it?
Dim paragraphs As Word.Paragraphs
paragraphs = doc.Paragraphs
For Each paragraph As Word.Paragraph In paragraphs
If paragraph.Range.Text.Trim() = String.Empty Then
paragraph.Range.[Select]()
wordapp.Selection.Delete()
End If
Next
This works for me. This will delete the pagebreak (if exists) from the 6th Page.
Imports Word = Microsoft.Office.Interop.Word
Public Class Form1
'~~> Define your Excel Objects
Dim wrdApp As New Word.Application
Dim wrdDoc As Word.Document
'~~> Page NO
Dim pgNo As Integer = 6
Dim i As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
wrdDoc = wrdApp.Documents.Open("C:\Users\Siddharth\Desktop\Document1.docx")
'~~> Display Word
wrdApp.Visible = True
With wrdDoc
For i = .Paragraphs.Count To 1 Step -1
If Asc(.Paragraphs(i).Range.Text) = 12 And _
.Paragraphs(i).Range.Information(Word.WdInformation.wdActiveEndPageNumber) = pgNo Then
.Paragraphs(i).Range.Delete()
Exit For
End If
Next i
End With
End Sub
End Class

Display hourglass or Please Wait message while Sub runs

I have the following sub running on my form. It can take a while for the sub to run so I want to change the cursor to an hourglass and display a Please Wait message while the code is running. Here is my procedure:
Public Sub GoToSheets(sheetName As String)
'This sub is used to open the workbook on the selected sheet.
'This checks to see if Excel workbook is opened, if not it
'opens Excel, the workbook and then the selected sheet. If the workbook is
'opened, it goes to the selected sheet.
'#param sheetName, sheet to be displayed
Try
'get an existing excel.application object
xlApp = CType(GetObject(, "Excel.Application"), Application)
Catch ex As Exception
'no existing excel.application object - create a new one
xlApp = New Excel.Application
End Try
Dim xlWBName As String = "2011.1004.Compensation Template"
Dim xlBookPath As String = Path.Combine(Directory.GetCurrentDirectory())
xlApp.Visible = True
Try
'get the opened workbook
xlBook = xlApp.Workbooks(xlWBName & ".xlsx")
Catch ex As Exception
'open it
xlBook = xlApp.Workbooks.Open(xlBookPath & "\" & xlWBName & ".xlsx")
End Try
Try
xlSheet = CType(CType(xlBook.Sheets("summarySheet"), Excel.Worksheet), Excel.Worksheet)
Dim strChckRange As String = xlSheet.Range("A2").Value
If strChckRange Is Nothing Then
Dim frmClientInfo As New frmClientInformation
frmClientInfo.ShowDialog()
closeXLApp()
Else
xlSheet = CType(CType(xlBook.Sheets(sheetName), Excel.Worksheet), Excel.Worksheet)
'close the navigation instance on the welcome page
frmNavigation.Close()
'activate requested sheet
xlSheet.Activate()
'display as dashboard
DashboardView()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
frmWelcomePage.Hide()
chkForm()
End If
Catch ex As Exception
End Try
End Sub
I have done some research on this, but so far nothing for Visual Basic.
I suggest creating a PleaseWaitForm that has the label of Please Wait... message on it and then have the form shown as mode-less, change the cursor to hourglass, do Excel work, change cursor back to default and hide the PleaseWaitForm.
Dim pleaseWait As New PleaseWaitForm
pleaseWait.Show()
' Set cursor as hourglass
Cursor.Current = Cursors.WaitCursor
Application.DoEvents
' Execute your GoToSheets method here
' Set cursor as default arrow
Cursor.Current = Cursors.Default
' Hide the please wait form
pleaseWait.Hide()

Calling Sheet from a WorkBook

I'm trying to call the 5th sheet in an open workbook. When I open the workbook from the program I seem to be able to do it:
Dim CurrentRun As New Excel.Application
Dim CurrentBook As Excel.Workbook
Dim CurrentSheet As Excel.Worksheet
Private Sub GeneralButtonOpener_Click(sender As Object, e As EventArgs) Handles GeneralButtonOpener.Click
CurrentRun.Visible = True
CurrentBook = CurrentRun.Workbooks.Add(MainTemplatePath)
CurrentSheet = CurrentBook.Worksheets(4)
CurrentSheet.Activate()
End Sub
But all my attempts at calling the sheet if the file is already open have failed:
Dim CurrentRun As Microsoft.Office.Interop.Excel.Application
Dim CurrentBook As Microsoft.Office.Interop.Excel.Workbook
Dim CurrentSheet As Microsoft.Office.Interop.Excel.Worksheet
CurrentRun = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
CurrentBook = CurrentRun.Workbooks
CurrentSheet = CurrentBook.Sheets(4)
CurrentSheet.Activate()
or
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CurrentRun As Microsoft.Office.Interop.Excel.Application
Dim CurrentBook As Excel.Workbook
Dim CurrentSheet As Excel.Worksheet
CurrentRun = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
CurrentBook = CurrentRun.ActiveWorkbook
CurrentSheet = CurrentBook.Sheets(4)
CurrentSheet.Activate()
End Sub
I've looked at several examples, but I can't figure out where I'm going wrong. Which surprises me as there seem to be a lot of questions on the subject. Ether a pointer to where this is solved/addressed or what I'm specifically doing wrong would be appreciated.
Thanks!
Much to my surprise, I found that I in fact had dozens of instances of Excel running in the background. When I am debugging, and launch the COM the first instance of Excel is started. The second is started when I open the windows form (the main part of the add-in).
What I didn't know, was that when an exception was thrown, and I stop things from within Visual Studio, only the first instance of Excel was closed. I have code that tries and clean up open applications of Excel, but of course it was not reached because an exception was thrown.
And here I had been thinking I would put Error handling a bit down the road when I had things a little more developed. Clearly I need to address some basic error handling much earlier in my build process. I'm entirely self taught, and somehow made it three years without that being an issue.
Hopefully someone else who wasn't been taught that can see this before pulling their hair out for 14 hours.
Solution
Close all other instances of Excel and the above code works. Address cleanup in error handling and earlier as addressed here: http://support.microsoft.com/kb/317109
Maybe also call the GC, though that seems controversial.
Final code:
....
Imports System.Runtime.InteropServices
....
Dim CurrentRun As New Excel.Application
Dim CurrentBook As Excel.Workbook
Dim CurrentSheet As Excel.Worksheet
....
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
On Error GoTo VortexInYourSoul
CurrentRun = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
CurrentBook = CurrentRun.Workbooks(1)
CurrentRun.Visible = True
CurrentSheet = CurrentBook.Sheets(8)
CurrentSheet.Activate()
CurrentBook.ActiveSheet.name = "LLAMA LALA LLAMALMALMAL"
....
Exit Sub
VortexInYourSoul:
CurrentSheet = Nothing
CurrentBook.Close(False)
CurrentBook = Nothing
CurrentRun.Quit()
CurrentRun = Nothing
MsgBox("Error: " & Err.Description)
End Sub

How to select a cell A3 in Excel using VB.net?

I want to select the Cell A3 using VB.net..
I tried doing this by:
sheet.Range("A3:A3").Select()
But this gives an exception = Select method of Range Class Failed !
What is the problem and how to do it ?
Please help.. I am waiting for the reply !
Assuming you meant Excel VBA try this:
sheet.Range("A3").Select
You can just specify the cell if all you want is one cell.
This program works for me in VB.NET, I agree with rajah9, check the other aspects.
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add()
oSheet = oBook.Worksheets(1)
oSheet.Range("A3").Select()
oExcel.ActiveCell.Value = "Put text here"
oBook.SaveAs("C:\Path\testinterop.xlsx")
oExcel.Quit()
End Sub
End Class
(based on, and drawn in part from, examples here)