我有一个代码,该代码从工作表中获取数据并填充表格。数据中有重复的条目。 [请参阅数据img。]
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
如您所见
FileName:=FolderPath & thisFile2.Value & ".pdf"
文件以A列中的值命名。但是,对于重复的条目,excel将用第二个覆盖第一个文件。我现在想做的是创建一个名称,该名称结合了A列中的值的名称和B列中的到达日期的值。像这样...
FileName:=FolderPath & thisFile2.Value & thisFile.Value & ".pdf"
这虽然使我出错。有人可以帮我吗?
答案 0 :(得分: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