【发布时间】:2018-12-26 08:45:07
【问题描述】:
下面是分配给我的“生成报告”命令按钮的宏,用于将活动工作表保存为 pdf 文件。我正在尝试使用此宏将我的用户表单列表框的内容保存为 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 = Replace(Replace(ws.Name, " ", ""), ".", "_") _
& "_" _
& 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 = "Asset List"
.Orientation = xlPortrait
.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
下面是如何使用带有搜索按钮的 textboxsearch 填充 Userform 列表框。
Private Sub SearchButton_Click()
'ListBox1.Clear
ListBox1.RowSource = ""
ListBox1.ColumnHeads = False
'listbox column headers
Me.ListBox1.AddItem
For A = 1 To 8
Me.ListBox1.List(0, A - 1) = Sheet2.Cells(1, A)
Next A
Me.ListBox1.Selected(0) = True
'Populating listbox1 from search
Dim i As Long
Dim ws As Worksheet
Dim SheetList(0 To 1) As String
Dim k As Integer
SheetList(0) = "Sheet1"
SheetList(1) = "Sheet2"
For k = LBound(SheetList) To UBound(SheetList)
Set ws = Sheets(SheetList(k))
For i = 2 To ws.Range("A100000").End(xlUp).Offset(1, 0).Row
For j = 1 To 8
H = Application.WorksheetFunction.CountIf(ws.Range("A" & i, "H" & i), ws.Cells(i, j))
If H = 1 And LCase(ws.Cells(i, j)) = LCase(Me.SearchTextBox) Or H = 1 And _
ws.Cells(i, j) = Val(Me.SearchTextBox) Then
Me.ListBox1.AddItem
For X = 1 To 8
Me.ListBox1.List(ListBox1.ListCount - 1, X - 1) = ws.Cells(i, X)
Next X
End If
Next j
Next i
Next k
'Count the listbox rows when populated
With Me.ListBox1
For X = 0 To .ListCount - 1
Total = X
Next X
End With
End Sub
【问题讨论】:
-
简短回答:是。列表框内容的位置在哪里?如果这是 excel 中的表格,那么您可以将该表格保存为 pdf,如果它是通过代码生成的,则需要发布到可读的位置并将其保存为 pdf。
-
嗨西里尔。列表框在用户表单中。当我单击搜索框时,内容会显示在列表框中。它是通过代码生成的。
-
好吧,鉴于列表框很可能是从代码中的数组生成的,填充 userform1.listbox1,您应该能够将该数组附加到工作表,然后移动该工作表并pdf那个文件。
-
你能贴出如何填充列表框的代码吗?
-
嗨西里尔,我已经添加了我的列表框在问题中的填充方式
标签: excel vba pdf listbox report