将列表框的内容导出到pdf

时间:2018-12-27 20:22:17

标签: excel vba listbox userform

我有一个包含列表框的用户窗体。我的工作簿有2个工作表,我的列表框从这两个表中获取数据,具体取决于我要搜索的内容。

无论工作表如何,如何将列表框的内容导出为pdf?

我发现可以在用户窗体中将其分配给命令按钮的通用宏,但它只会从活动工作表中导出内容,而不会导出列表框中的内容。

Sub PDFActiveSheet()
Dim ws As Worksheet
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
On Error GoTo errHandler

Set ws = ActiveSheet

'enter name and select folder for file
' start in current workbook folder
strFile = Format(Now(), "yyyymmdd\_hhmm") _
            & ".pdf"
strFile = ThisWorkbook.Path & "\" & strFile

myFile = Application.GetSaveAsFilename _
    (InitialFileName:=strFile, _
        FileFilter:="PDF Files (*.pdf), *.pdf", _
        Title:="Select Folder and FileName to save")

If myFile <> "False" Then

    ws.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:=myFile, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False

    With ws.PageSetup
        .CenterHeader = "Report"
        .Orientation = xlLandscape
        .Zoom = True
        .FitToPagesTail = False
        .FitToPagesWide = 1
    End With

    MsgBox "PDF file has been created."
End If

exitHandler:
    Exit Sub
errHandler:
    MsgBox "Could not create PDF file"
    Resume exitHandler
End Sub

1 个答案:

答案 0 :(得分:2)

谢谢您,我设法提出了另一个更简单的解决方案。只需将列表框内容导出到excel

Private Sub SaveListBoxContent_Click()

    Dim i As Integer
    Dim xlApp As Excel.Application
    Dim xlSh As Excel.Worksheet

    Set xlApp = New Excel.Application
    xlApp.Visible = True
    xlApp.Workbooks.Add

    Set xlSh = xlApp.Workbooks(1).Worksheets(1)
     For i = 1 To Me.ListBox1.ListCount
        xlSh.Cells(i, 1).Value = Me.ListBox1.List(i - 1, 0)
        xlSh.Cells(i, 2).Value = Me.ListBox1.List(i - 1, 1)
        xlSh.Cells(i, 3).Value = Me.ListBox1.List(i - 1, 2)
        xlSh.Cells(i, 4).Value = Me.ListBox1.List(i - 1, 3)
        xlSh.Cells(i, 5).Value = Me.ListBox1.List(i - 1, 4)
        xlSh.Cells(i, 6).Value = Me.ListBox1.List(i - 1, 5)

    Next

End Sub
相关问题