Operating on excel sheet in Visual Basic - vb.net

I'm trying to edit an excel sheet to remove some duplicate data. My macro works fine in Excel.
When I try to do the same in visual studio 2008, Im facing an issue:
The code is :
' Microsoft SQL Server Integration Services Script Task
' Write scripts using Microsoft Visual Basic 2008.
' The ScriptMain is the entry point class of the script.
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports Microsoft.Office.Interop
<System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
<System.CLSCompliantAttribute(False)> Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum
' The execution engine calls this method when the task executes.
' To access the object model, use the Dts property. Connections, variables, events,
' and logging features are available as members of the Dts property as shown in the following examples.
'
' To reference a variable, call Dts.Variables("MyCaseSensitiveVariableName").Value
' To post a log entry, call Dts.Log("This is my log text", 999, Nothing)
' To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, True)
'
' To use the connections collection use something like the following:
' ConnectionManager cm = Dts.Connections.Add("OLEDB")
' cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;"
'
' Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
'
' To open Help, press F1.
Public Sub Main()
Dim oExcel As Excel.ApplicationClass
Dim oBook As Excel.WorkbookClass
Dim oBooks As Excel.Workbooks
Dim i As Long
Dim Col As Long
Dim setErrorFilePath As String
Dim setErrorFileName As String
' Dim xlTmp As Excel.Application
'Set(xlTmp = New Excel.Application)
' xlTmp.Workbooks.Open("C:\Book1.xls")
setErrorFilePath = Dts.Variables("ErrorFilePath").Value.ToString
setErrorFileName = Dts.Variables("ErrorFileName").Value.ToString
'Start Excel and open the workbook.
oExcel = CreateObject("Excel.Application")
oExcel.Visible = True
oBooks = oExcel.Workbooks
oBook = oBooks.Open(setErrorFilePath + setErrorFileName) ' Change your variable name here.
'Macro to format Excel
'Deleting the first four rows
oExcel.Rows("1:6").EntireRow.Delete()
'Unmerging The Cells
oExcel.Cells.UnMerge()
'Deleting Empy Columns after unmerging
With oExcel.ActiveSheet.UsedRange
Col = .Columns(.Columns.Count).Column
End With
For i = Col To 1 Step -1
If oExcel.Application.CountA(oExcel.Columns(i)) = 0 Then
oExcel.Columns(i).Delete()
End If
Next
'Run the macros.
'Clean-up: Close the workbook and quit Excel.
oBook.Save()
oExcel.Quit()
Dts.TaskResult = ScriptResults.Success
End Sub
End Class
Im getting the following error:
Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at Microsoft.Office.Interop.Excel.Range.set__Default(Object RowIndex, Object ColumnIndex, Object )
at ST_7bdc1448ef3b4c8db7fb8d5574f78c18.vbproj.ScriptMain.Main()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
I searched other places and the solution mentioned was to create a folder in c->windows->system32->config etc..
however I don't have the admin access and I can't get it.
How can I solve this ? Please Help

Related

How to resolve Sequence contains more than one matching element issue in CLOSEDXML?

What I am doing is just saving an excel template without inserting any data...
This is my code below.
Dim wb As XLWorkbook
wb = New XLWorkbook(rawfilelocation)
wb.SaveAs(filelocation, True) '---- I even tried false
This error I am getting every time.
System.InvalidOperationException: Sequence contains more than one matching element
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at ClosedXML.Excel.XLDataValidations.ProcessRangeRemoved(IXLRange range)
at ClosedXML.Excel.XLDataValidations.Delete(IXLDataValidation dataValidation)
at System.Collections.Generic.List`1.ForEach(Action`1 action)
at ClosedXML.Excel.XLDataValidations.Consolidate()
at ClosedXML.Excel.XLWorkbook.GenerateWorksheetPartContent(WorksheetPart worksheetPart, XLWorksheet xlWorksheet, SaveOptions options, SaveContext context)
at ClosedXML.Excel.XLWorkbook.CreateParts(SpreadsheetDocument document, SaveOptions options)
at ClosedXML.Excel.XLWorkbook.CreatePackage(String filePath, SpreadsheetDocumentType spreadsheetDocumentType, SaveOptions options)
at ClosedXML.Excel.XLWorkbook.SaveAs(String file, SaveOptions options)
at ClosedXML.Excel.XLWorkbook.SaveAs(String file, Boolean validate, Boolean evaluateFormulae)
at nproject.frmReportPreview.ExcelSave(String ExcelFile, String Excelext) in D:\MainProject\nproject\nproject\frmReportPreview.vb:line 1312
I am even posting an excel template Dropbox link here
Excel Template

error BC30560: 'XlDirection' is ambiguous in the namespace 'Microsoft.Office.Interop.Excel

I have a strange problem with Excel automation in VSTO. The below code works well with English but not with German language. The error is coming from first line of the code below. I get the following error when I watch the execution. Can someone tell me what's going wrong with the language setting.
error BC30560: 'XlDirection' is ambiguous in the namespace 'Microsoft.Office.Interop.Excel'.
{System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --->
System.Runtime.InteropServices.COMException: Old format or invalid type library. (Exception from HRESULT: 0x80028018
(TYPE_E_INVDATAREAD))
--- End of inner exception stack trace ---
at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[]
byrefModifiers, Int32 culture, String[] namedParameters)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs,
ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Dynamic.IDispatchComObject.GetMembers(IEnumerable`1 names)}
wrkSheet.Range(wrkSheet.Range(IDTable), _
wrkSheet.Range(IDTable).End(Excel.XlDirection.xlToRight) _
.End(Excel.XlDirection.xlDown)).Select()
Dim rngData As Excel.Range = Globals.ThisAddIn.Application.Selection
With rngData
StartRng = .Find(FormulaString, LookIn:=Excel.XlFindLookIn.xlFormulas)
If Not StartRng Is Nothing Then
EndRng = StartRng
StartAddress = StartRng.Address
Do
EndAddress = EndRng.Address
EndRng = .FindNext(EndRng)
Loop While Not EndRng Is Nothing And EndRng.Address <> StartAddress
End If
End With
It looks like you're using the End property incorrectly. Try removing the references to Excel.XlDirection.
For example, change:
End(Excel.XlDirection.xlDown)
...to:
End(xlDown)
See the documentation for the property:
MSDN : Range.End Property (Excel)
If Excel's constants are not recognized, you can either declare them yourself or else substitute the actual values in your code:
XlDirection Enumeration (Excel)

form.Invoke(delegate) Cannot access a disposed object. .net

Enviroment: vb.net visual studio 10 - win forms
The Error:
{"Cannot access a disposed object. Object name:'frmInfo'."}
StackTrace:
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at HorizonRealTime.UI.frmInfo.UpdateGUI(cHorizonColoredString strdata) in R:\csavb2010dlls\Test\TestSoloutions\StoreAutoStuff\HorizonRealTimeVB10\CommanderRealTime.UI\frmInfo.vb:line 93
at HorizonRealTime.UI.frmInfo.DoWork() in R:\csavb2010dlls\Test\TestSoloutions\StoreAutoStuff\HorizonRealTimeVB10\CommanderRealTime.UI\frmInfo.vb:line 75
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Simple Explanation:
I have 1 main form with many child mdi forms.
One form(frminfo) manages all the status/error messages that server processes generate.
These messages get placed on a
Imports System.Collections.Concurrent
Public oStatusMsgs As BlockingCollection(Of String) = New BlockingCollection(Of String) 'thread safe collection
The problem occurs very rarely(usually just on application startup) when it enters the if me.invokerequired { me.Invoke(delegate)} I get a object disposed error when it tries to invoke itself.
even in debug the object is not flagged as disposed after the error occurs.
if I wrap the me.invoke in a try/catch... it procedes to process the following messages just fine.
Output in textbox ends up looking like this:
---Refreshing Data---
#Items Data Refreshed#
#Deps Data Refreshed#
Real-Time Info - Error Displaying GUI Info - #Units Data Refreshed# - Cannot access a disposed object. Object name: 'frmInfo'.
#Retail Data Refreshed#
#Tax Data Refreshed#
---Exiting Data Refresh---
Whats funny is that this textbox is on frminfo that im copying the text out of.
Whats even stranger is. It is actually processing messages prior to getting this error. So the disposed error exception seems to be a false reading, and something else is actually occurring.
On frminfo is a low-priority thread that loops infinitely basically like this
Private sub DoStuff() 'this is kicked off from the frminfo.onload event as a new thread that is referenced by frminfo
dim strdata as string = nothing
do while active
If Me.frmparent.oStatusMsgs.Count > 0 Then
Me.frmparent.oStatusMsgs.TryTake(strdata, 300)
If Not strdata Is Nothing Then
Call me.UpdateGUI(strdata)
End If
strdata = Nothing
End If
thread.sleep(50)
loop
End sub
Private Sub UpdateGUI(ByVal strdata As string)
If Me.InvokeRequired Then
Try
Me.Invoke(New UpdateGUIDelegate(AddressOf UpdateGUI), New Object() {strdata})
Catch ex As Exception
Me.frmparent.oErrorMsgs.Add(Me.Text & " - Error Displaying GUI Info - " & strdata & " - " & ex.Message)
End Try
Else
'this is where it would append the strdata to some kind of textbox or other form level control
end if
end sub
On the main UI thread I do create addition references to this mdi child form.
The first is a collection I add every mdi child form to. I let the GC handle this entirely other then the add.(I do this to ensure my forms are not disposed of)
There is also a collection of forms that I use to sort the mdi childs. The
in some cases i do like
dim otmpinfofrm as form = frmcollection(i)
frmcollection(i) = nothing 'where this is where frminfo currently resides in the collection
frmcollection(i) = frmcollection(i+1)
I loop through the collection and at the end i put back in the reference to
frmcollection(lastindex) = otmpinfofrm
I dont think this sorting could impact the thread calling me.invoke to update a local control. Since Im just sorting references?
Any help would be appreciated regarding better use of the me.invoke to avoid this error from happening at all.

VB.NET--NullReferenceException on secondary form load

Background
I have a Winform application (VB.NET framework 4.0). Within the application are two forms: frmHome (startup form) and frmdePDF (secondary form with an Adobe PDF Reader COM control). frmHome grabs a PDF pathway from DFS, checks if the pathway actually exists, and if so, loads the file into my PDF control and shows frmdePDF. Now, this works 100% of the time on my local machine. However, the initial load on any other machine throws a NullReferenceException. Other events (e.g. my datagridview CellContentClick) that call the SAME code works fine on all machines. I understand (I hope correctly) that the issue is initializing that frmdePDF the first time.
Code
The code that loads the datagridview (dgDE) and pulls the PDF pathway:
Private Sub btnDELegalLOMCState_Click(sender As Object, e As EventArgs) Handles btnDELegalLOMCState.Click
loadStatus = "State"
Dim deState As String = Nothing
''Validate and set state
If Me.cbDEState.SelectedIndex = 0 Then
MessageBox.Show("Please select a state.")
Exit Sub
Else
deState = Me.cbDEState.Text
End If
''Populate dgDE/set data bindings
Try
Me.cbDERegion.ComboBox.SelectedIndex = -1
Me.dgDE.DataSource = Nothing
Me.SpSelectLOMAbyStateTableAdapter.Fill(Me.DevGISDataSet.spSelectLOMAbyState, 4, deState)
Me.dgDE.DataSource = Me.SpSelectLOMAbyStateBindingSource
Me.bnDE.BindingSource = Me.SpSelectLOMAbyStateBindingSource
Me.txtDEIssueDte.DataBindings.Clear()
Me.txtDECaseNum.DataBindings.Clear()
Me.txtDECommNum.DataBindings.Clear()
Me.txtDEIssueDte.DataBindings.Add(New System.Windows.Forms.Binding("Text", Me.SpSelectLOMAbyStateBindingSource, "IssueDte", True))
Me.txtDECaseNum.DataBindings.Add(New System.Windows.Forms.Binding("Text", Me.SpSelectLOMAbyStateBindingSource, "CaseNum", True))
Me.txtDECommNum.DataBindings.Add(New System.Windows.Forms.Binding("Text", Me.SpSelectLOMAbyStateBindingSource, "CommNum", True))
Catch ex As Exception
MessageBox.Show("Error loading LOMAs: " & ex.Message.ToString)
End Try
''Load PDF
If Me.dgDE.RowCount <> 0 Then
Dim i As Integer = Me.dgDE.CurrentRow.Index
Dim pathdePDF As String = Me.dgDE.Rows.Item(i).Cells(5).Value.ToString
LoaddePDF(pathdePDF)
End If
End Sub
The Public Sub that contains code to load the file and show frmdePDF:
Public Sub LoaddePDT(ByVal pathdePDF As String)
If System.IO.File.Exists(pathdePDF) Then
frmdePDF.pdfLOMC.LoadFile(pathdePDF)
frmdePDF.Show()
Else
MessageBox.Show("Image not available. Please check FEMA and CAMSIS.")
frmdePDF.Hide()
End If
End Sub
Other things I have tried
Creating a new instance of the form each time:
Public Sub LoadPDF_test(ByVal pathdePDF As String)
Dim openForms = Application.OpenForms.OfType(Of frmdePDF)()
While openForms.Any
openForms.First.Close()
End While
If System.IO.File.Exists(pathdePDF) Then
Dim newfrmdePDF As New frmdePDF
newfrmdePDF.pdfLOMC.LoadFile(pathdePDF)
newfrmdePDF.Show()
Else
MessageBox.Show("Image not available. Please check FEMA and CAMSIS.")
End If
End Sub
This code works on my machine 100%. It behaves the same way as the first load code on any other machine (throws the NullReferenceException).
Exception Text
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.NullReferenceException: Object reference not set to an instance of an object.
at SaveLOMC.frmHome.LoadPDF_test(String testPath) in C:\Data\Alycia\Development\LOMC\Projects\TFS_test\SaveLOMC\SaveLOMC\frmHome.vb:l ine 46
at SaveLOMC.frmHome.btnDENewLOMCState_Click(Object sender, EventArgs e) in C:\Data\Alycia\Development\LOMC\Projects\TFS_test\SaveLOMC\SaveLOMC\frmHome.vb:l ine 440
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
I have tried stepping through the debugger on my local machine. But again, I can't recreate the error on it so the objects all have assigned values.
I know this question has been asked endlessly. I have read through all of these (plus MORE!):
What is a NullReferenceException, and how do I fix it?
"Object reference not set to an instance of an object?"
Object reference not set to an instance of an object. vb.net looking up a string
visual basic: object reference not set to an instance of an object
Visual Basic - Object reference not set to an instance of an object
VB.Net How to set an object reference to an instance of an object?
object reference not set to an instance of an object. vb.net for some but not all code
Object reference not set to an instance of an object.
specific error on :"Object reference not set to an instance of an object."
Object reference not set to an instance of an object
"Object reference not set to an instance of an object" message
object reference not set to an instance of an object error showing
Additional information: my local machine is 64 bit, the other machines are 32 bit. The associated .dll files for the Adobe component are 32 bit. My Target CPU in the Application Properties is x86.
Any advice is appreciated, I wouldn't ask this broad question if I hadn't exhausted my options.
Solution
There was nothing wrong with the form load event--I was trying to manually set the location/bounds of the form on load. Set the bounds to a non-existent screen (my computer has three screens--everyone else has 2). Learning experience?

IndexOutOfRangeException in VB.NET

Picked up a legacy VB.NET project originally written for version 1.1 of the .NET framework. I'm running Vista with .NET 3.5. I have cleared out all the original error and the project will build; it just wont run.
As far as I can tell, it is trying to run 'LoginForm' but putting breakpoints in doesn't work because the error is thrown before the breakpoints are reached, regardless of where in the file they are placed.
Really can't work out what to do! Any help appreciated.
StackTrace:
System.IndexOutOfRangeException was unhandled
Message="Index was outside the bounds of the array."
Source="FirstLine"
StackTrace:
at FirstLine.LoginForm.main()
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
EDIT: Terribly sorry, didn't appreciate the code would be of much use because the issue is more that I can't get to it. However, here's the main function:
Shared Sub main()
Dim p As Process() = Process.GetProcessesByName("FirstLine")
If p.Length = 1 Then
'START COPYMINDER
'Dim expirydate As Date = CDate("01/01/1970")
'Dim expiry As Integer
'Try
' GetCopyMinderExpiryDate(expiry)
' If Not expiry = 0 And Not expiry = 1 Then
' expirydate = expirydate.AddSeconds(expiry)
' Dim diff As Integer = DateDiff(DateInterval.Day, Date.Now, expirydate)
' If diff >= 0 And diff 0 Then
' DisplayError((ret_code))
' End
'End If
'Dim did As String
'GetCopyMinderDeveloperID(did)
'If did "IT" Then
' MessageBox.Show("Invalid Developer ID " & did & ". Firstline will now shutdown", "Firstline", MessageBoxButtons.OK, MessageBoxIcon.Error)
' End
'End If
'END COPYMINDER
Dim lf As New LoginForm
If LoginSettings.setting("loginShowErrorOnLine") = "TRUE" Then
lf.ShowDialog()
Else
Try
lf.ShowDialog()
Catch ex As Exception
MsgBox(ex.Message)
Config.UnlockByUser(Config.currentUser.username)
Config.currentUser.UserLoggedOff()
End Try
End If
Else
Dim prc As Process = p(0)
SwitchToThisWindow(prc.MainWindowHandle, True)
End If
End Sub
Thanks for your responses so far. It's encouraging to see such a helpful community!
Dim prc As Process = p(0) is your problem as it is in the else statements where the the array length can be anything but 1 (0 for instance).
when the length is 0 it will give you the IndexOutOfRange when you try to access the first element.
Try turning on debug build; this will give you the possibility to add breakpoints and will also give you some row numbers at the stack trace.
Your problem is that you are not handling the case where p.Length = 0. This occurs if there is no process with the name "FirstLine".
Have you also renamed your process / application ?