我想向您寻求帮助。我有生成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
您能建议我,如何更好地定义范围?
非常感谢!
答案 0 :(得分:1)
您不能像这样使用Range。它可以是单个单元格,也可以是范围,例如:“ D1:D5” 因此,您最好一一检查一下这些单元格,然后检测其中一个单元格是否为空。
答案 1 :(得分:1)
您可以像这样创建另一个子。
Sub check_range_blanks()
If IsEmpty(Range("D15").Value) Or IsEmpty(Range("D17").Value) Or IsEmpty(Range("D19").Value) Or IsEmpty(Range("D21").Value) Then
MsgBox "Range Should not be Blank"
Exit Sub
Else
Call CBSaveasPDF_Click
End If
End Sub
答案 2 :(得分:0)
根据@Rocoders的建议,我已经更正了rane,编辑了条件,并且效果很好。
Private Sub CBSaveasPDF_Click()
Dim sPath As String
Dim sFile As Variant
Dim ws As Worksheet
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim rng4 As Range
With Worksheets("Dashboard")
Set rng1 = .Range("D15")
Set rng2 = .Range("D17")
Set rng3 = .Range("D19")
Set rng4 = .Range("D21")
End With
On Error GoTo ErrHandle
If IsEmpty(rng1) Or IsEmpty(rng2) Or IsEmpty(rng3) Or IsEmpty(rng4) 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