开发者

Loop through excel workbooks in vb.net

开发者 https://www.devze.com 2023-03-22 11:09 出处:网络
I am working with a folder of xls files that are all in identical f开发者_开发知识库ormat (automatically generated by entering numbers into a pricing app). I need to pull the data that is in cell D54

I am working with a folder of xls files that are all in identical f开发者_开发知识库ormat (automatically generated by entering numbers into a pricing app). I need to pull the data that is in cell D54 on the worksheet of the same name in every file. Can't seem to get anything to work to make it loop.

Any ideas how this can be done?


If you can have the files generated in XLSX format then this is what I would do.

http://epplus.codeplex.com/

This is an amazing component library for dealing with Excel XLSX sheets.

Example...

Sub temp()
    Dim out As New List(Of String)
    Using pac As New ExcelPackage(New IO.FileInfo("c:\temp.xlsx"))
        For Each wb As ExcelWorksheet In pac.Workbook.Worksheets
            out.Add(wb.Cells("D54").Value.ToString)
        Next
    End Using
End Sub

Otherwise the option is to reference the Excel Com+ Library from office to open an XLS sheet with what should be similar code as below.

Sub temp2()
    Dim out As New List(Of String)
    Dim app As New Microsoft.Office.Interop.Excel.Application
    app.DisplayAlerts = False
    Dim wb As Microsoft.Office.Interop.Excel.Workbook = app.Workbooks.Open("c:\temp.xls")
    For Each ws As Microsoft.Office.Interop.Excel.Worksheet In wb.Worksheets
        Dim r As Microsoft.Office.Interop.Excel.Range = ws.Cells(54, 4)
        out.Add(r.Value.ToString)
    Next
    app.close()
End Sub
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号