简体   繁体   中英

Force Save As, MS Excel VBA

I'm a bit of a newby with VBA in MS Office products. I've been searching for some code that will force a user to "Save As' a .xls file I use as a template (but it's not an actual template file type)

Basically, I have this:

  1. User opens .xls, enters some data into some field and then File-->Save As to their own location
  2. Sometimes user clicks save instead, therefore overwriting the .xls which I don't want to happen.

I've been looking into some ideas, but I'm not sure how to implement it the best. I think a prompt when the user first opens the .xls to save to a new location is the best approach, but thinking forward, if they have already saved the file to a new location and decide to edit the new one, I want them to be able to 'Save' at that point because now it is their own file, not the original.

If someone can point me in the right direction or find flaws in my logic, I'd love to hear it.

Thanks, Mike

I use as a template (but it's not an actual template file type)

The most simplest way is to save the file with Read-Only Recommended set to true. See the snapshot

在此输入图像描述

That ways even if the user tries to do a Save , Excel will automatically prompt for a Save As

在此输入图像描述

HTH

I agree with the others that templates and read-only are better options, but if you're set on rolling your own, here's an example to get you started. It goes in the ThisWorkbook module

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    Dim sNewName As String

    Cancel = True 'Cancel the save operation

    sNewName = Application.GetSaveAsFilename(Replace(Me.Name, ".xls", "1.xls"))

    If sNewName <> Me.FullName And sNewName <> "False" Then
        Application.EnableEvents = False
            Me.SaveAs sNewName
        Application.EnableEvents = True
    End If

End Sub

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