【问题标题】:how to get the file name to = range("b3") & now()如何获取文件名 = range("b3") & now()
【发布时间】: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


【解决方案1】:

没有解释,我不确定所有代码是如何相关的,但假设单元格 B3 仅包含文本,您的示例很接近 - 但缺少引号。

应该是:

Range("B3") & Format(Now(), "ddmmyy")

【讨论】:

  • 我正在尝试将该集作为该长字符串中的文件名。当我启动作为另存为名称的子时,它会转换为 pdf 并最后启动邮件以运行。
猜你喜欢
  • 2010-12-02
  • 2011-05-11
  • 2015-03-26
  • 2016-05-10
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多