简体   繁体   中英

Exporting excel file to HTML via VBA causes trouble - neverending “Want to save?” pop-up

I am trying to export current workbook to HTML site with current timestamp using this code

Private Sub btnSave_Click()
ActiveWorkbook.Save  'Save current file

Dim ActSheet As Worksheet
Dim ActBook As Workbook
Dim CurrentFile As String
Dim NewFileType As String
Dim NewFile As String

Application.ScreenUpdating = False    ' Prevents screen refreshing.

CurrentFile = ThisWorkbook.FullName     ' Remeber location of original file
NewFileType = "Web files File (*.HTML), *.html"   'Set file type
Newfilename = "Shed9-" & Format(CStr(Now), "yyyy-mm-dd_hh-mm") 'Save as timestamp

NewFile = Application.GetSaveAsFilename( _
    InitialFileName:=Newfilename, _
    fileFilter:=NewFileType)

If NewFile <> "" And NewFile <> "False" Then
    ActiveWorkbook.SaveAs Filename:=NewFile, _
        FileFormat:=xlHtml


    Set ActBook = ActiveWorkbook
    Workbooks.Open CurrentFile
    ActBook.Close
End If

Application.ScreenUpdating = True

End Sub

In theory this procedure should save current file, save copy (with a time stamp, ignoring VBA) as a web page, close the web page (which to be honest I don't even want to open) and get back to the original spreadsheet. Unfortunately the problem is with the closing part: Excel opens the web page (!) and then I have never-ending pop-up question "Do you want to save the file "Shed-9 .html?"

So how can I remove that pop-up and simply export without opening?

EDIT I've tried to force-save the HTML copy before closing by putting the

ActBook.Save
ActBook.Close

But that leads to an error:

"An item with the same key has already been added". If thats important the workbook has multiple sheets and data taken through PowerQuery

EDIT (The original code came from here) - the original author should receive his/her credit

Try:

ActBook.Close False

If you save a workbook in a non-excel format it will ask you if you want to save the file again anyway, without fail. Using the optional "False" parameter tells excel that you want to close without saving.

You could safely skip these lines, where you actually ask Excel to do just that (open the file):

   Set ActBook = ActiveWorkbook
   Workbooks.Open CurrentFile
   ActBook.Close

I think what might confuse you is that have turned off screen updating, which hides what happens to you (behind the scenes).

   Application.ScreenUpdating = False 

This is all good if you really want to hide what's going on, but I imagine it might confuse you as long you have the Workbooks.Open code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM