vb.net with excel

mymyrsx

Member
Joined
Mar 15, 2005
Messages
8
Programming Experience
Beginner
Hi
I'm trying to open a file, fill it and then save it as another name and path.
The first time I click on the button who bring the event this is working fine.

But the second time one line make me this error "Object reference not set to an instance of an object."
here is the line
ex.Workbooks.Open(FromPath & "\CoverPage.xls")

I close my application and the workbook
here is my code
VB.NET:
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] ex [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] excel.Application
[/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] wb [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] excel.Workbook
[/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] ws [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] Excel.Worksheet
[/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] Path [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]String
[/COLOR][/SIZE][COLOR=#0000ff]Dim[/COLOR][SIZE=2] FromPath [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE]
 
[SIZE=2]ex.Workbooks.Open(FromPath & [/SIZE][SIZE=2][COLOR=#800000]"\CoverPage.xls"[/COLOR][/SIZE][SIZE=2])
wb = ex.Workbooks(1)
ws = wb.Worksheets(1)
ws.Cells(10, 8) = Today
[/SIZE][SIZE=2]ex.Visible = [/SIZE][SIZE=2][COLOR=#0000ff]False
[/COLOR][/SIZE][SIZE=2]ws.SaveAs(Path & [/SIZE][SIZE=2][COLOR=#800000]"\"[/COLOR][/SIZE][SIZE=2] & [/SIZE][SIZE=2][COLOR=#800000]"CoverPage.xls"[/COLOR][/SIZE][SIZE=2])
wb.Close()
ex.Quit()
ws = [/SIZE][SIZE=2][COLOR=#0000ff]Nothing
[/COLOR][/SIZE][SIZE=2]wb = [/SIZE][SIZE=2][COLOR=#0000ff]Nothing
[/COLOR][/SIZE][SIZE=2]ex = [/SIZE][SIZE=2][COLOR=#0000ff]Nothing
[/COLOR][/SIZE]

Can somebody tell me what's wrong with my code?
 
Last edited:
Do you understand why that was a problem? If the declarations are outside a method then your Excel.Application object will be created when the class instance containing it is created. The first time you execute the method you quit the Excel application and then set the 'ex' variable to Nothing. The next time you execute the method 'ex' is still Nothing, so you cannot access an Excel.Application object using it. Generally speaking there is no point setting a variable to Nothing in VB.NET, especially if you don't understand exactly what the implications of doing so are.
 
You are right. I didn't know why it was doing this. Now I know and that make sense.
Thank you for taking time to explain me why. I really appreciate
 
Back
Top