如何刮别在vb6中显示excel文档的所有内容

时间:2012-02-06 04:44:08

标签: excel vb6

我制作了一个程序来读取一个excel文档并将其显示在messageBox上。但是,问题是,我想废弃aka将所有内容显示到messageBox,而不知道选择哪一行或哪一行。我写了这段代码:

  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文件。

1 个答案:

答案 0 :(得分:0)

这样的东西(在PowerPoint中测试,因为我没有VB6)将按单元格获取第一张单元格的UsedRange(使用数组提高效率)

请更改您的文件路径以适应。

第一个版本 - 在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