使用vb.net从excel读取数据

时间:2015-06-23 08:01:23

标签: vb.net excel

我有一个vb.net控制台应用程序,我正在尝试从文件夹中的所有excel文件中读取数据。在第二个循环中,我得到了这些错误。

Microsoft.VisualBasic.dll中出现未处理的“System.ArgumentException”类型异常

附加信息:参数'Prompt'无法转换为'String'类型。

感谢您的帮助。

这是我的代码......

    Sub Main()
    Dim objFSO, objStartFolder, objFolder, colFiles, Path, a

    objFSO = CreateObject("Scripting.FileSystemObject")
    objStartFolder = "C:\Users\Administrator\Desktop\Excel Files"
    objFolder = objFSO.GetFolder(objStartFolder)
    colFiles = objFolder.Files

    For Each objFile In colFiles
        Path = objStartFolder + "\" + objFile.Name
        Dim objexcel, objWorkbook, ex
        objexcel = CreateObject("Excel.Application")
        objexcel.Application.Visible = True
        objWorkbook = objexcel.Workbooks.Open(Path)
        ex = objWorkbook.Worksheets(1)
        For i As Integer = 1 To 50
            a = ex.Cells(i, 5)
            MsgBox(a)
        Next
        objexcel.Quit()
    Next

End Sub

1 个答案:

答案 0 :(得分:1)

SELECT S.*, GROUP_CONCAT(DISTINCT B.bname SEPARATOR ',') AS buildings, GROUP_CONCAT(DISTINCT F.fname SEPARATOR ',') AS faculties FROM school S INNER JOIN school_building B1 INNER JOIN school_faculty F1 LEFT OUTER JOIN school_building B ON S.schoolId = B.schoolId LEFT OUTER JOIN school_faculty F ON S.schoolId = F.schoolId WHERE B1.schoolId = S.schoolId AND B1.bname IN ('hospital','restaurant') OR F1.schoolID = S.schoolId AND F1.fname IN ('medicine','engineering') GROUP BY S.schoolId 不返回字符串,而是表示您指定的Range的对象。因此,要访问您需要更改类型

的值
ex.Cells(i, 5)

您需要在项目中添加对Microsoft.Office.Interop.Excel的引用。如果需要,您还可以强烈键入Excel对象,即:

MessageBox.Show(CType(ex.Cells(i, 5), Microsoft.Office.Interop.Excel.Range).Value.ToString())

另外在旁注中你应该停止使用COM对象(Dim objExcel As New Microsoft.Office.Interop.Excel.Application() )并使用本机托管的.Net代码。只需使用以下代码即可获得与上述相同的功能

Scripting.FileSystemObject