使用Excel VBA导出后命名PDF

问题描述 投票:1回答:1

我有一个代码从表单中获取数据并填充表单。在数据中有重复的条目。 [请参阅数据图像]

Dim i As Long
Dim dataWS As Worksheet, formWS As Worksheet
Dim thisFile As Range, destRange As Range
Dim thisFile2 As Range, destRange2 As Range

FolderPath = "C:\Users\Lenovo\Documents\PAF_Output\"

MkDir FolderPath

Set dataWS = Sheets("Data")
Set formWS = Sheets("Form")
For i = 2 To 5

Set thisFile2 = dataWS.Range("A" & i) 
Set destRange2 = formWS.Range("B4:I4")
thisFile2.Copy destRange2

Set thisFile = dataWS.Range("B" & i) 
Set destRange = formWS.Range("O4:Q4")
thisFile.Copy destRange

Sheets(Array("Form")).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, FileName:=FolderPath & thisFile2.Value & ".pdf", _
openafterpublish:=False, ignoreprintareas:=False


Next i

End Sub

Data

如你所见

FileName:=FolderPath & thisFile2.Value & ".pdf"

这些文件以A列中的值命名。但是,在重复条目的情况下,excel将使用第二个文件覆盖第一个文件。我现在要做的是创建一个名称,其中包含A列中值的名称和B列中的到达日期值。这样......

FileName:=FolderPath & thisFile2.Value & thisFile.Value & ".pdf"

这引发了我一个错误。有谁可以帮助我吗?

excel vba excel-vba
1个回答
2
投票

您需要格式化日期,以便不显示斜杠(/),因为文件名不能包含这些字符,如下所示,还值得一提的是您从单个单元格复制并粘贴到范围中,我怀疑是什么想实现..:

Dim i As Long
Dim dataWS As Worksheet: Set dataWS = Sheets("Data")
Dim formWS As Worksheet: Set formWS = Sheets("Form")
Dim thisFile As Range, destRange As Range
Dim thisFile2 As Range, destRange2 As Range

FolderPath = "C:\Users\Lenovo\Documents\PAF_Output\"

MkDir FolderPath

For i = 2 To 5
    Set thisFile2 = dataWS.Range("A" & i)
    Set destRange2 = formWS.Range("B4:I4")
    thisFile2.Copy destRange2

    Set thisFile = dataWS.Range("B" & i)
    Set destRange = formWS.Range("O4:Q4")
    thisFile.Copy destRange

    formWS.ExportAsFixedFormat _
    Type:=xlTypePDF, fileName:=FolderPath & thisFile2.Value & Format(thisFile.Value, "MM-dd-yyyy") & ".pdf", openafterpublish:=False, ignoreprintareas:=False
Next i
End Sub

更新:

要稍微整理一下代码并删除不需要的语句,比如复制和粘贴,请参阅下面的内容:

Sub test()
Dim i As Long
Dim dataWS As Worksheet: Set dataWS = Sheets("Data")
Dim formWS As Worksheet: Set formWS = Sheets("Form")

FolderPath = "C:\Users\Lenovo\Documents\PAF_Output\"

If Dir(FolderPath, vbDirectory) = "" Then MkDir FolderPath
'above if the folder doesn't exist then create it

For i = 2 To 5
    formWS.Range("B4:I4") = dataWS.Range("A" & i)
    formWS.Range("O4:Q4") = dataWS.Range("B" & i)
    'above transfer the values from one range to another without copying

    formWS.ExportAsFixedFormat _
    Type:=xlTypePDF, fileName:=FolderPath & thisFile2.Value & Format(thisFile.Value, "MM-dd-yyyy") & ".pdf", openafterpublish:=False, ignoreprintareas:=False
Next i
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.