首页 文章

VBA - 通过下拉/验证列表进行迭代,并将生成的工作表保存为一个PDF

提问于
浏览
0

我在给定单元格上遍历下拉/验证列表:

Sub SpitValues()
Dim dvCell As Range
Dim inputRange As Range
Dim c As Range
Dim i As Long

'Which cell has data validation
Set dvCell = Worksheets(3).Range("D4")
'Determine where validation comes from
Set inputRange = Worksheets(2).Range("C4:C5")

i = 1
'Begin our loop
Application.ScreenUpdating = False
For Each c In inputRange
    dvCell = c.Value

    i = i + 1
Next c
Application.ScreenUpdating = True

End Sub

在每次迭代中,我需要将整个Worksheet(3)保存到变量,最后我需要将所有已保存的工作表保存到一个PDF中,其中每个迭代数据将在单独的页面上 . 因此,如果我在下拉列表/验证列表中有五个项目,则会有五页的PDF . 可能吗?

1 回答

  • 1

    有可能吗?

    是 . 有可能的 .

    首先,一些清理 . 我已删除 i ,因为您不使用该变量 . 我没有关闭屏幕更新,因为你想提取每次迭代 . 但是,是的,关闭屏幕更新通常是一个很好的性能指标 .

    执行此操作的一般算法是:

    Identify where you are going to store the new pages
    Make the change
    Copy the page to the new store
    loop
    print
    

    你已经做了一些,现在完成这项工作 .

    Sub SpitValues()
        Dim dvCell As Range
        Dim inputRange As Range
        Dim c As Range
        Dim NewWorkbook as workbook
    
        'Which cell has data validation
        Set dvCell = ThisWorkbook.Worksheets(3).Range("D4")
        'Determine where validation comes from
        Set inputRange = ThisWorkbook.Worksheets(2).Range("C4:C5")
        Set NewWorkbook = Application.Workbooks.Add
    
        'Begin our loop
        For Each c In inputRange
            dvCell = c.Value
            ThisWorkbook.Worksheets(3).Copy Before:=NewWorkbook.Sheets(NewWorkbook.Sheets.Count)  ' should insert this before the blank sheet at the end.
        Next c
    'After this loop, print/save the new workbook. Change the file name to something suitable
        NewWorkbook.ExportAsFixedFormat _
            Type:=xlTypePDF, _
            Filename:="Whatever", _
            Quality:=xlQualityStandard, _
            IncludeDocProperties:=True, _
            IgnorePrintAreas:=False, _
            OpenAfterPublish:=False
    
    End Sub
    

    免责声明:我还没有机会测试这段代码 .

相关问题