venerdì 2 agosto 2013

Caricamento dati da MS Excel in Visual Basic 6

Con queste poche righe di codice è possibile leggere dei dati su di un file MS Excel e portarli in un oggetto list di Visual Basic.
Si crea una form tramite progetto "Exe" con un oggetto list chiamato List1, nel menu a tendina del progetto si fa riferimento all'oggetto MS Excel, e si integrano queste righe al caricamento della form.
Di seguito il sorgente e screenshot:

Private Sub Form_Load()
Dim objXls As Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
Dim varValue As Variant
Dim i As Integer

Set objXls = New Excel.Application
Set wb = objXls.Workbooks.Open("C:\Documents and Settings\admin\Desktop\car\car.xls")
Set ws = wb.Worksheets("CAR")

For i = 2 To 11
varValue = ws.Cells(i, 1) & " " & ws.Cells(i, 2)
List1.AddItem (varValue)
Next

wb.Close
objXls.Quit
Set ws = Nothing
Set wb = Nothing
Set objXls = Nothing
End Sub

Form di esempio con una lista


Riferimento dell'oggetto Excel


Dati su foglio Excel


Record sulla lista