Set Current Directory in Excel.Application via .NET Office PIA

风流意气都作罢 提交于 2019-12-11 08:44:37

问题


I want to create an Excel spreadsheet from a .NET Application and then set the Excel.Application instance current directory to a custom folder. I want to do this so when the user clicks the save button in Excel, the Save as dialog is already located in the correct directory.

I know it's possible to change the current directory in Excel Instance with VBA.FileSystem.ChDir and doing it within the Excel.Application instance with VBA Code/Macro like this:

  1. Create an Excel Spreadsheet from C# .NET

    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
    excel.Workbooks.Add();
    excel.Visible = true;  
    
  2. When Excel spreadsheet is open, hit ALT + F11. Then create and run following macro

    Sub SetChdir()
       Call FileSystem.ChDir("C:\To\My\Custom\Directory\")
    End Sub
    
  3. When clicking Save in Excel the Current Directory is set path set with ChDir

I can't figure out, or even if it's possible, how to create this behaviour from .NET. I tired messing around with Excel.DefaultFilePath which Excel uses on startup to set the Current Directory. But it has two problems:

  • When DefaultFilePath is set to a different value, you need to restart Excel to make it effect on new or open spreadsheets
  • I really don't want to change the users current DefaultFilePath as it is a Global value for Excel and not this individual spreadsheet.

回答1:


There is another way.

excel.ExecuteExcel4Macro("DIRECTORY(\"C:\\To\\My\\Custom\\Directory\")");


来源:https://stackoverflow.com/questions/8330845/set-current-directory-in-excel-application-via-net-office-pia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!