2012-05-02 35 views

回答

7

这应该从Excel导入数据文件到一个ListView:

Dim ExcelObj As Object 
    Dim ExcelBook As Object 
    Dim ExcelSheet As Object 
    Dim i As Integer 

    Set ExcelObj = CreateObject("Excel.Application") 
    Set ExcelSheet = CreateObject("Excel.Sheet") 

    ExcelObj.WorkBooks.Open App.Path & "\ExcelFile.xls" 

    Set ExcelBook = ExcelObj.WorkBooks(1) 
    Set ExcelSheet = ExcelBook.WorkSheets(1) 

    Dim l As ListItem 
    lvwList.ListItems.Clear 
    With ExcelSheet 
    i = 1 
    Do Until .cells(i, 1) & "" = "" 
     Set l = lvwList.ListItems.Add(, , .cells(i, 1)) 
     l.SubItems(1) = .cells(i, 2) 
     l.SubItems(2) = .cells(i, 3) 
     l.SubItems(3) = .cells(i, 4) 
     i = i + 1 
    Loop 

    End With 

    ExcelObj.WorkBooks.Close 

    Set ExcelSheet = Nothing 
    Set ExcelBook = Nothing 
    Set ExcelObj = Nothing 
+0

l.SubItems(1)= .cells(1,2)在这行我得到无效的属性错误 – karthik

+0

尝试增加列标题。 – Xaisoft

+0

谢谢,我试图给不存在的列添加一个值。 – karthik

2

我会多出很多可能使用的一些网格控件的排序,而不是一个ListView这一点,但...

既然你只是带来价值没有元数据(格式),可以使用Jet的Excel的IISAMs的一个做到这一点,它甚至还可以在未安装Excel的机器!

Dim SheetName As String 
Dim RS As ADODB.Recordset 
Dim LI As ListItem 
Dim I As Integer 

'Look up 1st Worksheet (or just hardcode its Name). 
' 
'Notes: 
' o Can use Excel 8.0 or Excel 5.0 to read most Excel 7.0/97 
' Workbooks, but there is no IISAM specifically for Excel 7.0. 
' o Use HDR=Yes if your Worksheet has a header row. 
With CreateObject("ADOX.Catalog") 
    .ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" _ 
         & App.Path & "\sample.xls';" _ 
         & "Extended Properties='Excel 5.0;HDR=No'" 
    SheetName = .Tables(0).Name 
    Set RS = New ADODB.Recordset 
    Set RS.ActiveConnection = .ActiveConnection 
End With 
'The "Table" name can be a range too, e.g. [Sheet1$A1C7] 
With RS 
    .Open "[" & SheetName & "]", _ 
      , _ 
      adOpenForwardOnly, _ 
      adLockReadOnly, _ 
      adCmdTable 
    ListView.ListItems.Clear 
    ListView.View = lvwReport 
    For I = 0 To .Fields.Count - 1 
     ListView.ColumnHeaders.Add , , .Fields(I).Name 
    Next 
    Do Until .EOF 
     Set LI = ListView.ListItems.Add(, , CStr(.Fields(0).Value)) 
     For I = 1 To .Fields.Count - 1 
      LI.SubItems(I) = CStr(.Fields(I).Value) 
     Next 
     .MoveNext 
    Loop 
    .Close 
End With