[英]creating multiple files from a same worksheet VBA
在一个名为FILE
我有以下代码,除其他外,该代码为工作表中定义的每个零件填写表格,然后将名称中包含该零件的pdf文件保存为FILEPART.pdf
。
'parts
lastRow = Sheets("overview").Range("G1000").End(xlUp).Row
lastRowHere = Sheets("Source").Range("A13:A1000").End(xlUp).Row
'count of parts
Count = lastRowHere + 2
For m = 1 To Count
For n = 14 To lastRow
Partname = Sheets("overview").Range("C" & n) &
_" of " & Sheets("overview").Range("A" & n)
[...]
Next n
'creates the PDF file for mapping on each part
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = ThisWorkbook.FullName
If FSO.FileExists(s(0)) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), Partname & ".pdf")
'//Export to PDF with new File Path
lastPart = Sheets("table").Cells(1000, m * 5 + 1).End(xlUp).Row
Sheets("table").Range(Cells(1, m * 5 + 1), Cells(lastPart, m * 5 + 5)).
_ExportAsFixedFormat Type:=xlTypePDF, FileName:=sNewFilePath,
_Quality:=xlQualityStandard, IncludeDocProperties:=True,
_IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
Next m
我的问题是我只有一个文件,而没有多个具有不同名称的文件。 循序渐进,我首先看到它创建了FILEPART1.pdf
,然后将其替换为FILEPART2.pdf
,仅以FILEPARTLAST.pdf
此版本的代码(在SJR评论之后)解决了该问题
'parts
lastRow = Sheets("overview").Range("G1000").End(xlUp).Row
lastRowHere = Sheets("Source").Range("A13:A1000").End(xlUp).Row
'count of parts
Count = lastRowHere + 2
s(0) = ThisWorkbook.FullName
For m = 1 To Count
PartNameSource = Sheets("Source").Range("A" & m + 13)
For n = 14 To lastRow
PartnameLine = Sheets("overview").Range("C" & n) &
_" of " & Sheets("overview").Range("A" & n)
[...]
Next n
'creates the PDF file for mapping on each part
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(s(0)) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), PartnameSource & ".pdf")
'//Export to PDF with new File Path
lastPart = Sheets("table").Cells(1000, m * 5 + 1).End(xlUp).Row
Sheets("table").Range(Cells(1, m * 5 + 1), Cells(lastPart, m * 5 + 5)).
_ExportAsFixedFormat Type:=xlTypePDF, FileName:=sNewFilePath,
_Quality:=xlQualityStandard, IncludeDocProperties:=True,
_IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
Next m
备注
如果PartNameSource
包含使文件名无效的字符(如/
),则会出现run-time error 1004 Document not saved. The document may be open, or an error may have been encountered when saving
run-time error 1004 Document not saved. The document may be open, or an error may have been encountered when saving
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.