【发布时间】:2018-07-29 21:49:56
【问题描述】:
因此,在这串代码中,除了正确命名之外,它可以完成我需要的所有操作。它会弹出一个框,询问我在哪里保存,但不是名称选项,我希望它另存为..
range("b3") & format(now(), ddmmyy)
我怎样才能让它适应这个并正确格式化?
Private Sub CommandButton1_Click()
Dim xSht As Worksheet
Dim xFileDlg As FileDialog
Dim xFolder As String
Dim xYesorNo As Integer
Dim xOutlookObj As Object
Dim xEmailObj As Object
Dim xUsedRng As Range
Set xSht = ActiveSheet
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
If xFileDlg.Show = True Then
xFolder = xFileDlg.SelectedItems(1)
Else
MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf
& "Press OK to exit this macro.", vbCritical, "Must Specify Destination
Folder"
Exit Sub
End If
xFolder = xFolder + "\" + xSht.Name + ".pdf"
'Check if file already exist
If Len(Dir(xFolder)) > 0 Then
xYesorNo = MsgBox(xFolder & " already exists." & vbCrLf & vbCrLf & "Do
you want to overwrite it?", _
vbYesNo + vbQuestion, "File Exists")
On Error Resume Next
If xYesorNo = vbYes Then
Kill xFolder
Else
MsgBox "if you don't overwrite the existing PDF, I can't continue." _
& vbCrLf & vbCrLf & "Press OK to exit this macro.",
vbCritical, "Exiting Macro"
Exit Sub
End If
If Err.Number <> 0 Then
MsgBox "Unable to delete existing file. Please make sure the file is
not open or write protected." _
& vbCrLf & vbCrLf & "Press OK to exit this macro.",
vbCritical, "Unable to Delete File"
Exit Sub
End If
End If
Set xUsedRng = xSht.UsedRange
If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then
'Save as PDF file
xSht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xFolder,
Quality:=xlQualityStandard
'Create Outlook email
Set xOutlookObj = CreateObject("Outlook.Application")
Set xEmailObj = xOutlookObj.CreateItem(0)
With xEmailObj
.Display
.To = ""
.CC = ""
.Subject = xSht.Name + ".pdf"
.Attachments.Add xFolder
If DisplayEmail = False Then
'.Send
End If
End With
Else
MsgBox "The active worksheet cannot be blank"
Exit Sub
End If
Unload Me
CLOSE1.Show
End Sub
我只是不确定如何按照我需要的方式设置它。就像我说的其他一切都有效,我只需要将它保存为我的范围和日期。
【问题讨论】:
-
您的问题是您的行
xSht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xFolder,文件名正在激活FileDialog(msoFileDialogFolderPicker),您需要创建一个变量,例如"SaveFileName" 并替换Filename中的xfolder。查看this SO question,它应该对您有所帮助。您也可以在 Google 上搜索“excel vba 使用单元格值作为 exportasfixedformat 中的文件名”,它会显示许多链接。
标签: excel vba export-to-pdf