My vb.net program for Excel won't run on different computer - vb.net

I wrote a vb.net program using Visual Studio 2010 Express to open and manipulate an Excel workbook. I have MS Office 2010 and my program works fine on my computer. When I try to run it on my wife's computer... nothing. I get no error messages... nothing. She has the same version of Office as I do, but she has Windows XP and I have Vista and her computer is has more security protocols than mine, but my other program, which does not import any Office namespaces, runs fine on her computer.
When I look at the task manager on her computer there is nothing under the Applications tab, but under the Processes tab I see an instance of Excel.exe, and if I try to run the program again, still nothing under applications, but yet another instance of Excel.exe under processes.
I have tried to install my program using the Click-Once technology and just the Release folder after a Rebuild... nothing.
I have also tried to compile it under versions 2.0, 3.0, etc.... nothing.
Here is some of the relevant code:
Public Class CleanUpDataForm
Dim m_objExcel As New Excel.Application
Dim m_rngRange, m_rngEnd As Excel.Range
Dim m_blnEntireRow, m_blnCancel As Boolean
Dim m_strRange, m_strSearch, m_strLogFrameCode As String
Const c_strCode As String = "log"
Friend Const c_intScrollBarWidth As Integer = 30
Private Sub CleanUpDataForm_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
m_objExcel = Nothing
Dispose()
End Sub
Private Sub tsbOpen_Click(sender As System.Object, e As System.EventArgs) Handles tsbOpen.Click
ofdGetWorksheet.Title = "Select Worksheet"
ofdGetWorksheet.Filter = "All Excel Files (*.xl*)|*.xl*|(*.xlsx)|*.xlsx|(*.xlsm)|*.xlsm|(*.xlsb)|*.xlsb|(*.xlam)|*.xlam|(*.xltx)|*.xltx|(*.xltm)|*.xltm|(*.xls)|*.xls|(*.xla)|*.xla|(*.xlt)|*.xlt|(*.xlm)|*.xlm|(*.xlw)|*.xlw"
ofdGetWorksheet.FileName = ""
If ofdGetWorksheet.ShowDialog <> System.Windows.Forms.DialogResult.Cancel Then
Me.Text = ofdGetWorksheet.FileName
m_objExcel.Workbooks.Open(Me.Text)
tsbCopySheet.Enabled = True
tsbFindRows.Enabled = True
tsbClose.Enabled = True
m_objExcel.Visible = True
Else
Me.Text = ""
End If
Me.Activate()
End Sub
Any ideas??

I believe that I was having this issue as well, but this line of code (after your m_objExcel.visible statement) was what fixed it (going from memory).
m_objExcel.Windows(1).Visible = True
One thing you may want to look at is the Marshal.BindToMoniker method in the InteropServices library. I found this incredibly useful. If the file is not open, then it opens it. If it is open already, then it will use that instance. Like this...
wb = System.Runtime.InteropServices.Marshal.BindToMoniker(fileName) 'open the file. If the file is already open, then this uses the open file instead of trying to open again
exApp = wb.Parent
wb is my workbook variable, exApp is my Excel variable.
One other thing; to make sure Excel is closed and to remove those pesky processes from Task Manager
Private Sub KillExcel()
For Each RunningProcess In Process.GetProcessesByName("Excel")
RunningProcess.Kill()
Next
End Sub

Related

VB.Net - Program can't Edit HKEY_Local_Machine registry entry

I have a similar problem, VB.Net - Program can't Edit HKEY_Local_Machine registry entry, that was listed, but the fix did not work for me. I am using Visual Studio 2017. I am trying to create a portable app that will work in Windows 7 Professional and Windows 10 Professional. The idea is to reset the last logged on person to either Blank or a different user. My colleagues and I have to logged into member computers with an elevated account to work on them, but the member does not pay attention and causes our account to get locked out. we are not allowed to use group policy to correct this problem, so I am trying to do it with my app. I can make changes via regedit, vbs and batch files, but I cannot seem to get my program in VB2017 to work. I took off the preferred 32bit checkbox and tried running it as an administrator or a different user with administrative rights. I get the same error . . . cannot write to the registry (HKEY_Local_Machine registry). Below is my code. Any help would be appreciated.
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
Dim regVersion64 As Microsoft.Win32.RegistryKey = Microsoft.Win32.RegistryKey.OpenBaseKey _
(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry64).
OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI")
If chkbClearEverything.Checked = True Then
regVersion64.SetValue("LastLoggedOnDisplayName", "")
regVersion64.SetValue("LastLoggedOnSAMUser", "")
regVersion64.SetValue("LastLoggedOnUser", "")
Else
tbd1 = TBLogon.Text
tbs1 = TBsam.Text
tbu1 = TBllu.Text
regVersion64.SetValue("LastLoggedOnDisplayName", tbd1)
regVersion64.SetValue("LastLoggedOnSAMUser", tbs1)
regVersion64.SetValue("LastLoggedOnUser", tbu1)
End If
Dim rvLastLoggedOnDisplayName As String = regVersion64.GetValue("LastLoggedOnDisplayName")
Dim rvLastLoggedOnSANuser As String = regVersion64.GetValue("LastLoggedOnSAMUser")
Dim rvLastLoggedOnUser As String = regVersion64.GetValue("LastLoggedOnUser")
If Not rvLastLoggedOnDisplayName = "" Then
TBLogon.Text = rvLastLoggedOnDisplayName
tbd1 = rvLastLoggedOnDisplayName
End If
If Not rvLastLoggedOnSANuser = "" Then
TBsam.Text = rvLastLoggedOnSANuser
tbs1 = rvLastLoggedOnSANuser
End If
If Not rvLastLoggedOnUser = "" Then
TBllu.Text = rvLastLoggedOnUser
tbu1 = rvLastLoggedOnUser
End If
regVersion64.Close()
End Sub

Close Excel Workbook If Test for Open Returns False

I've constructed a VB.Net application which loads data into an Excel spreadsheet. The application works fine, but I've added a functionality to test whether the workbook is Open, and if so, the application terminates. Otherwise, if the workbook Is Not Open, then the user can proceed to fill information in the application. My issue is that when is when the worksheet is not open, my code blows up due to the workbook being "somehow opened." I need to close any processes, then proceed. Here's my code for checking if the workbook is open or not:
1st, my module, which sets up the a Boolean check:
Public Module ExcelCheck
Public Function Test(ByRef sName As String) As Boolean
Dim fs As FileStream
Try
fs = File.Open(sName, FileMode.Open, FileAccess.Read, FileShare.None)
Test = False
Catch ex As Exception
Test = True
End Try
End Function
End Module
Then my handler for a button on the form that does the check:
Private Sub btnOpenFileCheck_Click(sender As Object, e As EventArgs) Handles btnOpenFileCheck.Click
'Evaluate if the workbook is being used:
Dim bExist As Boolean
bExist = Test("\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines.xls")
If bExist = True Then
MessageBox.Show("The file is open... Please try again later.", "EXCEL FILE IN USE: Abort", MessageBoxButtons.OK)
Me.Close()
Else bExist = False
MessageBox.Show("The file is NOT open... You may proceed...", "EXCEL FILE NOT OPEN", MessageBoxButtons.OK)
Dim xlOpenItem As New Excel.Application
Dim xlOpenWB As Excel.Workbook = xlOpenItem.Workbooks.Open("\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines")
xlOpenWB.Close(SaveChanges:=False, Filename:="\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines.xls", RouteWorkbook:=False)
txtCPUSerial.Focus()
End If
End Sub
What happens when the book isn't open is the proper dialog to continue runs via the illustration:
But then an Excel dialog appears saying the following:
'\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines.xls'
is currently in use. Try again later.
Then, it finally blows up and I have the line of referenced:
Dim xlOpenWB As Excel.Workbook = xlOpenItem.Workbooks.Open("\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines")
My logic is that I need to have an open instance of an Excel object, then close that instance in order to terminate any inadvertent running process. I actually open the workbook in another submit handler, with the Excel objects and variables set well, but that's not my issue. How can I smoothly make sure the workbook object is closed here as as to not throw an exception that it isn't?
After much tinkering around, I've found out exactly what my problem was - I didn't close out the opened file stream:
Public Module ExcelCheck
Public Function Test(ByRef sName As String) As Boolean
Dim fs As FileStream
Try
fs = File.Open(sName, FileMode.Open, FileAccess.Read, FileShare.None)
Test = False
fs.Close() 'This closes out the initially opened file stream for checking.
Catch ex As Exception
Test = True
End Try
End Function
End Module
I eventually came back to the module and wondered what happens if I just close out and use fs.Close() and it did the trick. No more blow ups! Hope this helps someone else whom might struggle with a similar file stream issue.

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.

Kill Excel on Error

I am hoping you can help me here, in the past you all have been great. I have tried every variation of the kill script for killing excel from vb.net, to no avail.
First I can't post explicit code on here because it is my company's proprietary software, but I can tell you a few things. Also there are over 28,000 lines of code.
I am not using
Imports Excel = Microsoft.Office.Interop.Excel
due to the fact that we have to accommodate different variations of clients software. I am creating the new excel as an object as such
Dim XLObj As Object = CreateObject("Excel.Application")
I have seen this used on several other sites but the kill function they are using is when you save and then close it, which I'm not doing.
The error message I am getting says that "Com object that has been separated from its underlying RCW cannot be used". I'm not sure where this com object is because I have released the sheets, workbook and then the application.
Oh and I don't want to use the excel.kill() because if a client already has the excel open I don't want to kill it without saving it. I only want to kill the newly generated excel process that doesn't have a window open associated with it.
My questions are as follows
I need to be able to close the Excel application when/if the open fails. So say I am click a link and it opens the dialog box to select an Excel template to load but either the data from the database is corrupt or the sql statement is broken. The program throws and error and then Excel should close in the Task Manager. Unfortunately it doesn't close hence the problem.
is there a way to close only the newly created process id? I have tried to use the directions here but it doesn't work either. When I do that it gives me a different error "Value cannot be null Parameter name: o". The line that is throwing the error is on (from the link)
Marshal.FinalReleaseComObject(tempVar)
I only tried this because we are using the With on the XLObj. The With is in reference to the workbook itself so shouldn't it be released when I close the workbook? And being as I'm causing it to error on purpose at the moment it shouldn't reach the With statement anyway.
Is there a way to tell which com object is not closing?
Things I have tried:
This releaseObject that I found on the internet. (don't ask me where I've been through about 75 pages)
Private Sub releaseObject(ByRef obj As Object)
Try
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj)
If obj Is Nothing Then
Else
obj = Nothing
End If
Catch ex As Exception
If obj Is Nothing Then
Else
obj = Nothing
End If
Finally
GC.Collect()
GC.WaitForPendingFinalizers()
End Try
End Sub
This is used in conjunction with this function (which was pieced together from the many sites I have been on)
Public Sub CloseExcel(ByRef WorkBook As Object, ByRef Application As Object)
Dim xLSheet As Object = WorkBook.Sheets
For Each xLSheet In WorkBook.Sheets
If xLSheet IsNot Nothing Then
releaseObject(xLSheet)
End If
If xLSheet IsNot Nothing Then
Kill(xLSheet)
End If
Next
If WorkBook IsNot Nothing Then
WorkBook.Close(False)
End If
If WorkBook IsNot Nothing Then
Kill(WorkBook)
End If
releaseObject(WorkBook)
If Application IsNot Nothing Then
Application.Quit()
End If
If Application IsNot Nothing Then
Kill(Application)
End If
releaseObject(Application)
GC.Collect()
GC.WaitForPendingFinalizers()
Application.Quit()
End Sub
and because it is also referenced the Kill function
Public Sub Kill(ByRef obj As Object)
Try
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj)
Catch ex As Exception
MessageBox.Show("moduleExcel.Kill " & ex.Message)
Finally
obj = Nothing
End Try
End Sub
any help would be greatly appreciated.
Ok so for those of you having this exact same issue. I do have a solution for you. Yes the above code does work but for a few minor adjustments.
you need to take out all the code in the CloseExcel sub and place it EXACTLY where you want it to close. So if you want it to close if the program errors out, put after the catch statement. You cannot call a Sub and pass in your objects and expect it to kill the process.
you need a few bits above the opening of the new Excel process. and they are as follows.
'declare process for excel
Dim XLProc As Process
'loads the financials excel bookmarks
'this will be where you declare your new excel opbject
Dim XLObj As Object = CreateObject("Excel.Application")
'get window handle
Dim xlHWND As Integer = XLObj.hwnd
Dim ProcIDXL As Integer = 0
'get the process ID
GetWindowThreadProcessId(xlHWND, ProcIDXL)
XLProc = Process.GetProcessById(ProcIDXL)
and of course you will need the GetWindowThreadProcessId which I got from the link I included in the original question. I am posting it here so you don't have to search for it.
<System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _
Private Function GetWindowThreadProcessId(ByVal hWnd As IntPtr, ByRef lpdwProcessId As Integer) As Integer
End Function
This code will only close the single process you have it associated with, it will not close other open Excel files. Our clients sometimes will have multiple files open and we don't want to close them without telling them. This KILLS the Excel process that was created at run time when the system Errors out.

Previous Excel instance not getting through IIS

I am using VB.NET to open the Excel files but dont want to create excel object every time.
My code is working perfectly in debug mode, but after publish, it never gets the existing instances and always create new instances which we can see from Task Manager. Here is my code which always returns false in published mode.
My OS is Windows Server 2008. Please guide how to solve this.
Function IsExcelRunning() As Boolean
Dim xlApp As Excel.Application
On Error Resume Next
xlApp = GetObject(, "Excel.Application")
IsExcelRunning = (Err.Number = 0)
MyHelper.writeLog("Excel Instance found=" & IsExcelRunning)
xlApp = Nothing
Err.Clear()
End Function
Here is how I call.
If IsExcelRunning() Then
excelApp = GetObject(, "Excel.Application")
Else
excelApp = Server.CreateObject("Excel.Application")
End If
We used to use Excel Interop and I remember it always being difficult to work with (clunky.) Due to the Interop opening an Excel process and not closing it every time you use it, makes it difficult to work with.
The Interop opens Excel automatically, so all we needed to do was close it. This is what we used to use to kill the Process. Replace YourProcessName with Excel.exe.
Dim proc As System.Diagnostics.Process
Dim info As ManagementObject
Dim search As New ManagementObjectSearcher("SELECT ProcessId FROM Win32_process WHERE caption = 'YourProcessName'")
For Each info In search.Get()
Dim TheString As String = info.GetText(TextFormat.Mof).ToString
proc = System.Diagnostics.Process.GetProcessById(Mid$(TheString, _
(Len(TheString) - 8), 4))
proc.CloseMainWindow()
proc.Refresh()
If proc.HasExited Then GoTo NoKill
proc.Kill()
NoKill:
Next
You'll need to import
Imports System.Management
You'll also need to add the reference 'System.Management' to your project.
See: http://msdn.microsoft.com/en-us/library/vstudio/wkze6zky.aspx for adding a reference to a project.
If you can rather work with CSV, I would suggest you try to. If you are creating the Excel file yourself, try to find a report creator that let's you create / export to Excel. You'll save yourself a lot of time in the long run.