Click here to Skip to main content
15,891,828 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have below code in vb.net

Dim xlApp As New Excel.Application()
Dim xlWorkBook As Excel.Workbook
xlWorkBook = xlApp.Workbooks.Add
xlWorkBook.SaveAs("C:\ABC.xlsx")

When the file already exists at "C:\ABC.xlsx" then it prompts "file already exists. Do you want to replace it ?" When I clicked on Yes then it works fine. But when i clicked on NO button then it throws error "Exception from HRESULT: 0x800A03EC".
I don't want to set DisplayAlerts property to False, as i want the user to aware that file already exists.
How to handle the error ??

What I have tried:

It works only when I set DisplayAlerts = False. But I don't want to do it.
Posted
Updated 2-May-16 1:45am

1 solution

That error is unfortunately quite common when using Excel - you get the same error if you try to Cancel as well. Other people have had the same (unhelpful) error message doing other things with Excel interop.

Rather than trying to fix Excel I suggest that you do your own check for the file and display your own error message. For example
C#
Dim xlApp As New Excel.Application()
Dim xlWorkBook As Excel.Workbook
xlWorkBook = xlApp.Workbooks.Add

Dim fileName As String = "C:\Temp\ABC.xlsx"
Dim vRes As DialogResult = DialogResult.Yes

If File.Exists(fileName) Then
    vRes = MessageBox.Show(String.Format("A file named '{0}' already exists in this location. Do you want to replace it?", fileName), _
                           "Microsoft Excel", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2)
    xlApp.DisplayAlerts = False
End If

If vRes = DialogResult.Yes Then
    xlWorkBook.SaveAs(fileName)
End If
xlWorkBook.Close()
xlApp.Quit()

Note that I only turn off DisplayAlerts if the file already exists.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900