如何删除ws.name

时间:2018-10-16 07:21:07

标签: excel vba excel-vba

我尝试使用以下脚本创建PDF文件,该文件可以工作,但是当我删除use existing connection时,脚本会中断。

ws.Name

如何删除此Sub createPDFfiles() Dim ws As Worksheet Dim strName As String For Each ws In ActiveWorkbook.Worksheets On Error Resume Next 'Continue if an error occurs ' Name PDF files based on the worksheet Index (e.g Annex 1.1.1, Annex 1.1.2, etc.) strName = Range("A10").Text & " " & Range("C7").Text & ws.Name ' If you want to name the PDF files differently just change the Fname variable above to ' whatever you like. For example if you changed Fname to: ' ' Fname = "C:\myFolder\pdfs\" & ActiveWorkbook.Name & "-" & ws.Name ' ' The files would be stored in C:\myFolder\pdfs, and named using the ' spreadsheet file name and the worksheet name. ' ' WARNING: Using worksheet names may cause errors if the names contain characters that Windows ' does not accept in file names. See below for a list of characters that you need to avoid. ' ws.ExportAsFixedFormat _ Type:=xlTypePDF, _ Filename:=strName, _ Quality:=xlQualityStandard, _ IncludeDocProperties:=True, _ IgnorePrintAreas:=False, _ OpenAfterPublish:=False Next ws End Sub 并仍然可以正常工作?

1 个答案:

答案 0 :(得分:1)

您的Range对象在此语句中不合格:

 strName = Range("A10").Text & " " & Range("C7").Text & ws.Name

因此,它们引用的是活动工作表上的单元格,而不是工作表ws上的单元格。

如果要引用您遍历的每个工作表上的那些单元格,请适当地对其进行限定:

 strName = ws.Range("A10").Text & " " & ws.Range("C7").Text

您可能希望在尝试保存PDF之前测试strName不为null。

我还建议丢失On Error Resume Next行,并正确处理错误。