我正在使用宏来浏览工作簿中的所有工作表。
我想要实现的是将每个工作表导出为pdf,并具有基于特定单元格(C8
)命名的每个工作表的名称。
这是我到目前为止(我还是初学者):
Sub print_pdf()
Dim wb As String
Dim ws As String
Dim rng As Range
Dim I As Integer
'For Each ws In wb.Worksheets
ws = Activeworkbooks.Worksheets.Count
For I = 1 To ws
Set wb = ActiveWorkbook
Set rng = ws.Range("C8")
ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=ws.Range("C8"), Quality:=xlQualityStandard, IncludeDocProperties:=False, IgnorePrintAreas:=False, OpenAfterPublish:=True
Next ws
End Sub
答案 0 :(得分:0)
我可以看到您发布的代码存在的一些问题。这应该让你开始,它不包括错误检查(在C8中有一个有效的值,该文件尚不存在,等等。)
Sub print_pdf()
Dim wb As Workbook
Dim ws As Worksheet
Dim rngFileName As String
Dim I As Integer
Set wb = ActiveWorkbook
For I = 1 To Worksheets.Count
wb.Worksheets(I).Activate
rngFileName = "C:\Temp\" & Range("C8").Value & ".pdf"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
rngFileName, Quality:=xlQualityStandard, _
IncludeDocProperties:=False, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Next I
End Sub
我在Excel 2010上测试了代码并且工作正常。
答案 1 :(得分:0)
这样的事情包括错误处理以捕获工作表名称的任何问题
请注意:
For each ws
优于按工作表计数循环ActiveWorkbook
C8
中有重复值,则导出时将覆盖之前的值,可以使用代码对此进行测试码
Sub ToPDF()
Dim ws As Worksheet
Dim strMsg As String
If ActiveWorkbook.Path = vbNullString Then Exit Sub
For Each ws In ActiveWorkbook.Sheets
On Error Resume Next
ws.ExportAsFixedFormat xlTypePDF, ActiveWorkbook.Path & "\" & ws.[C8]
If Err.Number <> 0 Then strMsg = strMsg & ws.Name & vbNewLine
On Error GoTo 0
Next
If Len(strMsg) > 0 Then MsgBox strMsg, vbCritical, "errors"
End Sub