如何将数据从ListView导出到Excel和PDF(VBA)
我有一个ListView中的数据,并希望将这些数据与列标题导出到一个新的Excel文件和一个PDF文件。
LV的定义如下:
'listview: | # | Col1 | Col2 | Col3 | ... ================================== | 1 | Val1 | Val2 | Val3 | ...
我从这个代码开始:
Dim objExcel As Excel.Application Dim objWb As Excel.Workbook Dim objWs As Excel.Worksheet Dim objRange As Excel.Range Dim i%, j% On Error GoTo errMsg Set objExcel = New Excel.Application objExcel.Visible = False Set objWb = objExcel.Workbooks.Add Set objWs = objWb.Sheets("Sheet1") With objWs For i = 1 To Me.lvlist.ListItems.Count .Cells(i, 1) = Me.lvlist.ListItems(i).Text For j = 1 To Me.lvlist.ListItems(i).ListSubItems.Count .Cells(i, j + 1) = Me.lvlist.ListItems(i).SubItems(j) Next j Next i End With objExcel.Visible = True objWs = Nothing objWb = Nothing objExcel = Nothing
但是我得到一个错误。 我怎样才能达到我的意图? 谢谢你的帮助。
编辑:我编辑上面的代码,现在我得到error 438: Object doesn't support this property or method
。 并且列标题不会导出为excel。
您已经很近了,但是您需要使用特定Item
的.Count
:
Me.lvlist.ListItems(i - 1).SubItems.Count
Dim objExcel As Excel.Application Dim objWb As Excel.Workbook Dim objWs As Excel.Worksheet Dim objRange As Excel.Range Dim SubItmCount As Long Dim i%, j% On Error GoTo errMsg Set objExcel = New Excel.Application objExcel.Visible = False Set objWb = objExcel.Workbooks.Add Set objWs = objWb.Sheets("Sheet1") With objWs For i = 1 To Me.lvlist.ListItems.Count .Cells(i, 1) = Me.lvlist.ListItems(i - 1).Text SubItmCount = Me.lvlist.ListItems(i - 1).SubItems.Count - 1 '<== argument is not optional .SubItems(..) For j = 1 To SubItmCount .Cells(i, j + 1) = Me.lvlist.ListItems(i - 1).SubItems(j).Text Next Next End With objExcel.Visible = True objWs = Nothing objWb = Nothing objExcel = Nothing
我解决了我的问题。 这里是下面的代码,导出Excel中的数据的列头:
With Me.lvlist For k = 1 To .ColumnHeaders.Count objWs.Cells(1, k) = .ColumnHeaders.item(k).Text objWs.Cells(1, k).Font.Bold = True objWs.Cells(1, k).Font.Size = 12 objWs.Cells(1, k).Interior.Color = vbYellow Next For i = 2 To .ListItems.Count + 1 objWs.Cells(i, 1) = .ListItems(i - 1).Text For j = 1 To .ListItems(i - 1).ListSubItems.Count objWs.Cells(i, j + 1) = .ListItems(i - 1).SubItems(j) Next Next End With
它工作得很好:)但是,感谢R3UK的支持和努力!