首页 > 解决方案 > VBA - 检查范围是否已填充,然后生成 PDF

问题描述

我想请你帮忙。我有生成 PDF 并且工作正常的代码,但我想添加条件。用户应填写单元格 D15、D17、D19 和 D21,如果它们为空白,则应通过 MsgBox 通知用户。如果它们被填满,那么它应该继续生成 PDF 文件。

我试图提出条件,但它给了我一个错误消息错误的参数数量或无效的属性分配在线Set rng = .Range("D15", "D17", "D19", "D21")

完整的代码是:

Private Sub CBSaveasPDF_Click()
    Dim sPath As String
    Dim sFile As Variant
    Dim ws As Worksheet
    Dim rng As Range

    With Worksheets("Dashboard")
    Set rng = .Range("D15", "D17", "D19", "D21")
    End With

    On Error GoTo ErrHandle

    If IsEmpty(rng) Then
                        MsgBox ("Please fill the yellow cells")
                    Exit Sub
    Else

    sPath = ThisWorkbook.Path & "\" & Me.Range("D9") & " -" & Me.Range("D8") & " -" & Me.Range("J8") & " " & Me.Range("B4")

    sFile = Application.GetSaveAsFilename _
                (InitialFileName:=sPath, _
            FileFilter:="PDF Files (*.pdf), *.pdf", _
            Title:="Select Folder and FileName to save")
        If sFile = "False" Then
            MsgBox ("Document not saved")
            Exit Sub
        End If

        Me.ExportAsFixedFormat _
            Type:=xlTypePDF, _
            Filename:=sFile, _
            Quality:=xlQualityStandard, _
            IncludeDocProperties:=True, _
            IgnorePrintAreas:=False, _
            OpenAfterPublish:=True
    End If

        Exit Sub
ErrHandle:
    MsgBox ("Document Not Saved")
End Sub

你能告诉我,我应该如何更好地定义范围?

非常感谢!

标签: excelvbaif-statement

解决方案


你不能像这样使用 Range。它要么是单个单元格,要么是一个范围,例如:“D1:D5”所以你最好一个一个地检查单元格并检测一个是否为空。


推荐阅读