且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用自定义名称创建工作簿而不将其保存到磁盘

更新时间:2022-11-18 21:38:15

仅创建工作簿并且不保存它,因此当用户尝试保存工作簿时,用户将收到另存为"提示.而且,如果用户尝试关闭它,则用户将收到提示,提示用户是否要在关闭之前保存(另存为对话框)文件.现在,此提示的出现将取决于您对新创建的工作簿进行了一些更改的事实.

Simply create the workbook and don't save it so when the user tries to save it, the user will get a "Save As" Prompt. And if the user tries to close it, then the user will get a prompt whether the users want to save (Again a Save As dialog) the file before closing. Now the appearance of this prompt will depend on the fact that you have made some changes to the newly created workbook.

例如

Sub Sample()
    Dim wb As Workbook

    Set wb = Workbooks.Add
End Sub

默认情况下,工作簿将被命名为"Book *",但这并不重要,因为用户将有机会进行另存为"

By default the workbook will be named as "Book*" but that really shouldn't matter as the user will get a chance to do do a "Save As"

关注

通过按Ctrl +S.它将显示另存为..."对话框,就像从未保存过工作簿一样.

By pressing Ctrl + S. It would show the Save As... dialog just as if the workbook had never been saved.

尽管我提到了只有一种方法可以想到,但是在编写代码时,我想到了2种选择:)

Though I mentioned that there is only one way that I can think of but while working on the code, I came up with 2 options :)

方法1

a)创建一个新工作簿

a) Create a new workbook

b)以JAN 2012.XLSM的名称保存到用户的Temp目录中

b) Save it as say, JAN 2012.XLSM, to user's Temp directory

c)将文件属性更改为只读

c) Change the file properties to Readonly

d)现在,当用户按CTRL + S时,Excel将提示另存为

d) Now when the user presses CTRL+S, Excel will prompt a Save As

Option Explicit

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long

Private Const MAX_PATH As Long = 260

Sub Sample()
    Dim wb As Workbook

    Set wb = Workbooks.Add

    With wb
        .SaveAs Filename:=TempPath & "JAN 2012.xlsm" _
        , FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

       '.SaveAs Filename:=TempPath & "JAN 2012.xlsx" _
       , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

        .ChangeFileAccess Mode:=xlReadOnly, WritePassword:="admin"
    End With
End Sub

Function TempPath() As String
    TempPath = String$(MAX_PATH, Chr$(0))
    GetTempPath MAX_PATH, TempPath
    TempPath = Replace(TempPath, Chr$(0), "")
End Function

方法2(复杂的方法)

a)创建一个新工作簿

a) Create a new workbook

b)以JAN 2012.XLSM的名称保存到用户的Temp目录中

b) Save it as say, JAN 2012.XLSM, to user's Temp directory

c)注入代码以禁用Ctrl + S并仅允​​许另存为

c) Inject a code to disable Ctrl + S and only allow Save As