VBA-通过下拉列表/验证列表进行迭代,并将生成的图纸保存到一个PDF中

时间:2018-12-09 18:50:44

标签: excel vba

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

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)保存为变量,最后,需要将所有已保存的Worksheets保存为一个PDF,其中每个迭代数据都将位于单独的页面上。因此,例如,如果我在下拉列表/验证列表中有五个项目,那么将有五个页面的PDF。可能吗?

1 个答案:

答案 0 :(得分: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  

免责声明:我还没有机会测试此代码。