T. Moser
T. Moser

Reputation: 111

Save Excel Workbook in VSTO Addin C#

I've coded an Excel Addin which, when a button is pressed, changes the content of some cells. Now I wanted to add the functionality to save the workbook to a new file after these replacements took place.

Here is my go at it and somehow this doesn't quite work like I imagined.

This is the code to save the file in my ThisAddIn.cs:

public static void saveasnewfile()
        {
            Globals.ThisAddIn.Application.ActiveWorkbook.SaveCopyAs(@"C:\XXXX.XLS");
        }

And this is how I call this function (say when a button is pressed):

//...
ThisAddIn.saveasnewfile();
//...

Now when I press said button I get this error message:

Microsoft Excel cannot access the file 'C:\XXXX.XLS'. There are several possible reasons:

• The file name or path does not exist. • The file is being used by another program. • The workbook you are trying to save has the samename as a currently open workbook.

Which seems kind of strange to me. Of course the file does not exist, since I want to create it...

So what am I missing here?

I would like to add the functionality to prompt the user for a path with a savefiledialog later. So some tips there would help as well :)

Upvotes: 0

Views: 1407

Answers (1)

T. Moser
T. Moser

Reputation: 111

SOLUTION:

For anyone that might stumble on the same thing, here is how I implemented it with the SaveFileDialog:

var saveDialog = new SaveFileDialog() //create new instance of savefiledialog
{  
    Title = "Save As", //sets title of dialog box
    Filter = "Excel Worbook (*.xlsx)|*.xlsx", //filter for .xlsx files
    AddExtension = true, //automatically adds the .xlsx extension
    CheckPathExists = true //checks if the given path really exists
}

if (saveDialog.ShowDialog() == DialogResult.OK)
{
Globals.ThisAddIn.Application.ActiveWorkbook.SaveCopyAs(saveDialog.FileName);
}

Upvotes: 2

Related Questions