How to properly write and save a new Excel file?

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-06 16:02:54

问题


An application (a SCADA program) has an event that trigers every day and run a script that writes an Excel file (one for each day). The file could contain multiple sheets.

On Windows 7, with Office 2007 installed, I can write, but I can't save and neither quit the Excel.Application.

Dim objExcel as Object
Set objExcel = CreateObject("Excel.Application")
objExcel.WorkBooks.Add  'I think I shouldn't do this, but if not it doesn't work

Set sheet = objExcel.ActiveWorkBook.Worksheets.Add
'writing to the actual sheet...

objExcel.ActiveWorkBook.SaveAs path$
objExcel.Workbooks.Close
objExcel.Quit   

If I run the script manually (from the script editor):

  • it saves
  • the Excel process still runing
  • When I open the Excel file (not from script), this has 2 workbooks, the actual and the last one from the last execution.

If I try trigger the event:

  • error occurs on the line when it saves

回答1:


Solved.

Dim objExcel as Object
Dim sheet as Object
Set objExcel = CreateObject("Excel.Application")
objExcel.WorkBooks.Add

Set sheet = objExcel.ActiveWorkBook.Worksheets.Add
'writing to the actual sheet...

path$ = "path/must/use/slash/insteed/of/backslash"

objExcel.ActiveWorkBook.SaveAs path$
objExcel.ActiveWorkBook.Close
objExcel.Quit  
Set objExcel = Nothing    

So the problem was the path$ and I forgot to put Set objExcel = Nothing. Thats all.



来源:https://stackoverflow.com/questions/35010126/how-to-properly-write-and-save-a-new-excel-file

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