2012-02-06 82 views
0

我做了一個程序來讀取一個excel文檔並將其顯示在一個messageBox上。但是,事情是,我想要廢棄所有的顯示器到messageBox而不知道要選擇哪一行或哪一列。我寫了這樣的代碼:如何刮顯示vb6中的Excel文檔的所有內容

Private Sub Command1_Click() 
    On Error GoTo Err 

    StartExcel 

    Set ExcelWBk = Excel.Workbooks.Open(App.Path & "\Dataku.xls") 
    Set ExcelWS = ExcelWBk.Worksheets(1) 
    With ExcelWS 

    Dim i As Integer 
    Dim strData As String 

    For i = 1 To 5 

     strData = strData & .Cells(i, 1) & vbCrLf 
    Next i 
    End With 

    MsgBox strData 
    CloseWorkSheet 
    ClearExcelMemory 
    Exit Sub 
Err: 
    ClearExcelMemory 
End Sub 

但它只返回到該列(第1列)的數據。我需要讀取整個excel文件。

回答

0

像這樣的東西(在PowerPoint測試因爲我不具備VB6)將電池拿到第一片電池的UsedRange(使用效率數組)

PLS改變,以適應您的文件路徑。

第一個版本 - 在PowerPoint測試

Sub GetData() 
Dim objExcel As Object 
Dim objWB As Object 
Dim objws As Object 
Dim X As Variant 
Dim lngCol As Long 
Dim lngRow As Long 
Dim strOut As String 


Set objExcel = CreateObject("Excel.Application") 
On Error Resume Next 
Set objWB = objExcel.Workbooks.Open("c:\temp\test.xlsx") 
Set objws = objWB.Sheets(1) 
On Error GoTo 0 
If objws Is Nothing Then Exit Sub 

'recalc usedrange 
objws.usedrange 
X = objws.usedrange 
For lngRow = 1 To UBound(X, 1) 
    For lngCol = 1 To UBound(X, 2) 
     strOut = strOut & (X(lngRow, lngCol) & vbNewLine) 
    Next 
Next 

objWB.Close False 
objExcel.Quit 
Set objExcel = Nothing 
If Len(strOut) > 0 Then MsgBox strOut 
End Sub 

VBS版本

Dim objExcel 
Dim objWB 
Dim objws 
Dim X 
Dim lngCol 
Dim lngRow 
Dim strOut 

Set objExcel = CreateObject("Excel.Application") 
On Error Resume Next 
Set objWB = objExcel.Workbooks.Open("c:\temp\test.xlsx") 
Set objws = objWB.Sheets(1) 
On Error GoTo 0 
If IsEmpty(objws) Then Stop 

'recalc usedrange 
objws.usedrange 
X = objws.usedrange 
For lngRow = 1 To UBound(X, 1) 
    For lngCol = 1 To UBound(X, 2) 
     strOut = strOut & (X(lngRow, lngCol) & vbNewLine) 
    Next 
Next 

objWB.Close False 
objExcel.Quit 
Set objExcel = Nothing 
If Len(strOut) > 0 Then MsgBox strOut 
+0

它只是閃爍並沒有發生 – user1072976 2012-02-06 07:11:53

+0

你更新你的文件的路徑? – brettdj 2012-02-06 08:33:35

相關問題