【问题标题】:VBA Error: "Compile error: Expected End Sub"VBA 错误:“编译错误:预期结束子”
【发布时间】:2010-12-17 15:40:36
【问题描述】:

试图将“GetFullNamePDF()”传递给 Filename 属性,但得到以下错误:“编译错误:预期的结束子”

Sub PrintPDF()

    Function GetFullNamePDF() As String
        GetFullNameCSV = Replace(ThisWorkbook.FullName, ".xlsm", ".pdf")
    End Function

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "GetFullNamePDF()", Quality:=xlQualityStandard, IncludeDocProperties _
        :=True, IgnorePrintAreas:=False, OpenAfterPublish:=False

End Sub

我对VBA一无所知,从question I asked yesterday得到了上面的代码,但当时无法测试。猜测错误与函数有关,因为代码在没有添加函数且文件路径/名称硬编码的情况下工作。

代码的想法是动态使用自身的文件名来命名PDF的路径和文件。如果您有任何问题,请发表评论——谢谢!

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您不能将函数嵌套在过程中。你需要把它移到上面:

    Function GetFullNamePDF() As String
        GetFullNameCSV = Replace(ThisWorkbook.FullName, ".xlsm", ".pdf")
        'This should be
        GetFullNamePDF = Replace(ThisWorkbook.FullName, ".xlsm", ".pdf")
    End Function
    
    Sub PrintPDF()
    
         'Remove the quotes from GetFullNamePDF
         ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
            GetFullNamePDF(), Quality:=xlQualityStandard, IncludeDocProperties _
            :=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
    
    End Sub
    

    【讨论】:

    • 感谢您花时间阅读代码并确保一切正常;明智的我代码说我的代码更好,但从未使用过 Excel 的 VBA。
    【解决方案2】:

    在 sub 中声明函数是非法的。 它应该是这样的:

    Function GetFullNamePDF() As String 
        GetFullNamePDF = Replace(ThisWorkbook.FullName, ".xlsm", ".pdf") 
    End Function 
    
    
    Sub PrintPDF() 
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ 
            "GetFullNamePDF()", Quality:=xlQualityStandard, IncludeDocProperties _ 
            :=True, IgnorePrintAreas:=False, OpenAfterPublish:=False 
    End Sub 
    

    【讨论】:

      【解决方案3】:

      像这样:

      Function GetFullNamePDF() As String
          GetFullNamePDF = Replace(ThisWorkbook.FullName, ".xlsm", ".pdf")
      End Function
      
      Sub PrintPDF()
          Dim sFileName As Variable
      
          sFileName=GetFullNamePDF()
      
          ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
              sFilename, Quality:=xlQualityStandard, IncludeDocProperties _
              :=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
      
      End Sub
      

      【讨论】:

      • @Remou:代码中没有提到“sFilename”,不要认为那行得通。
      • @Blunder 你忘了我写了这个函数吗?我对 VBA 非常非常熟悉(检查 VBA 标签上的用户)。将变量设置为函数的结果并不罕见,它使调试变得更加容易。你重写函数有错误,我会更正的。
      • @Remou:你说得对,它会起作用——将变量设置为函数结果的原因是什么?
      • 正如我所说,它使调试更容易,它也可以使代码更易于阅读。
      • @RolandTumble 如果您遇到该级别的编码问题,请考虑 ActiveSheet,它可能会或可能不会返回对象。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-28
      • 1970-01-01
      • 2013-06-19
      相关资源
      最近更新 更多