首页 > 解决方案 > 如何删除 ws.name

问题描述

我尝试使用以下脚本创建 PDF 文件,它可以工作,但是当我删除时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

我怎样才能删除它ws.Name并且仍然可以工作?

标签: excelvba

解决方案


您的Range对象在此声明中不合格:

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

所以他们指的是活动工作表上的那些单元格,而不是工作表上的单元格ws

如果您想在您循环的每个工作表上引用这些单元格,请适当地限定它们:

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

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

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


推荐阅读