我在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。
答案 0 :(得分:0)
你很接近,但你需要使用特定.Count
SubItems
的{{1}}:
Item
Me.lvlist.ListItems(i - 1).SubItems.Count
答案 1 :(得分:0)
我解决了我的问题。下面是以下代码,它使用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的支持和努力!