工作簿应自动保存为用户定义文件夹中的.xlsx文件,并关闭宏书而不保存

时间:2015-07-30 18:46:29

标签: vba excel-vba excel-2010 excel

我录制了vba代码来做一些条件格式化。结果存储在工作簿本身中。现在我想强制用户不要保存工作簿,而是在代码运行之后,它应该使用“{1}}”这样的唯一标识符使用“另存为”自动将工作簿保存到非宏文件中还应该询问用户保存的位置。

此外,它应关闭工作簿而不保存它,并打开上次保存的。"yyyymmmdd, hhmm.xlsx文件。我发现了一些代码,但它们并不是我想要的。请帮忙。

2 个答案:

答案 0 :(得分:2)

这个怎么样

Option Explicit
Sub SaveAs()
    Dim sDate As String
    Dim FileName As String

    '// format Date
    sDate = Format(Now, "YYYYMMDD HHMM")

    '// Save As Name
    FileName = sDate

    '// Save path
    Application.Dialogs(xlDialogSaveAs).Show FileName
End Sub

在代码下方添加此代码

每个OP评论

应该这样做 - 在 Excel 2010

上进行测试
Option Explicit
Sub SaveAs()
    Dim xlSaveAs As String
    Dim xlPath As Variant

    Application.ScreenUpdating = False

    '// Save As Name
    xlSaveAs = "Weekly Report - " & Format(Now, "YYYYMMDD HHMM") & ".xlsx"

    '// Save path
    Application.DisplayAlerts = False

    xlPath = Application.GetSaveAsFilename( _
        InitialFileName:=xlSaveAs, _
        FileFilter:="Excel Files (*.xlsx), *.xlsx", _
        Title:="My Save Dialog")
        If xlPath <> False Then
            ThisWorkbook.SaveAs xlPath, xlOpenXMLWorkbook
        Else
            MsgBox "Not Valid Path" '// Cancel
        End If

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

最后,您可能会发现MSDN中的Getting Started with VBA in Office 2010文章很有用。

答案 1 :(得分:0)

编辑:我重写代码以执行您想要的操作

Public Sub SaveNewFile()
    ' Create a new file basing the name of the current file (without extension if it's an xlsm) and the creation time
    Dim filename As String
    filename = ThisWorkbook.Path & "\" & CreateObject("scripting.filesystemobject").getbasename(ThisWorkbook.Name) & Format(Now, "yyyyMMdd hhmm") & ".xlsx"

    ' Save the file under the new name in xlsx format
    ' This action close the file and reopen it with the new name
    Application.DisplayAlerts = False
    ThisWorkbook.SaveAs filename:=filename, FileFormat:=xlOpenXMLWorkbook
    Application.DisplayAlerts = True
End Sub