【问题标题】:Export contents of listbox to pdf将列表框的内容导出为pdf
【发布时间】:2018-12-27 20:22:16
【问题描述】:

我有一个包含列表框的用户表单。我的工作簿有 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

【问题讨论】:

  • 您期望您的最终结果是什么样的?一页上只有几个字?为什么需要导出列表框的内容?您可以将这些内容写入新工作表然后进行转换吗?
  • @dwirony 我的最终结果将是从列表框内容中获取的报告。不想在工作簿中插入另一张工作表,因为用户无法使用该工作簿,并且不想在每次用户想要生成报告时都继续添加工作表

标签: excel vba listbox userform


【解决方案1】:

谢谢你,我设法想出了另一个更简单的解决方案。只需将列表框内容导出到 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

【讨论】:

  • 通过 VBA 循环遍历一个范围和每个单元格非常耗时;将整个 .List 属性写回一行中的范围,例如通过xlSh.Range("A1").Resize(ListBox1.ListCount, ListBox1.ColumnCount) = ListBox1.List。 (顺便说一句,行/列计数器应声明为As Long,因为范围行/列很容易超过整数限制)
猜你喜欢
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 2014-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多