循环读取excel数据

时间:2012-12-03 02:12:26

标签: excel vba vb.net excel-interop

我需要将读取数据从excel循环到vb.net,当我到达最后一行/列“!@#$%^& *()”时,excel数据将停止读取。我怎样才能做到这一点?

Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
    Dim xlApp As Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkSheet As Excel.Worksheet
    Dim xRange As Excel.Range
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    End Sub
    Private Sub cmdGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGenerate.Click
        'Dim row As String
        Dim empty_cell_ctr As Integer = 0 '5
        Dim end_of_xlsheet As Boolean = False
        Dim sRow As Integer 'start row
        Dim col_end As Integer 'col W
        '
        'loading excel(open and read)
        xlApp = New Excel.ApplicationClass
        xlWorkBook = xlApp.Workbooks.Open("c:\sample.xls")
        xlWorkSheet = xlWorkBook.Worksheets("Timesheet")
        xlApp.Visible = True

        While Not end_of_xlsheet

           If sRow = "'!@#$%^&*()_+" Then
                xRange = xRange.Cells(sRow, col_end)
                end_of_xlsheet = False 'end of sheet
                Continue While
           End If

           sRow += 1

        End While

        MessageBox.Show(sRow)
    End Sub
End Class

2 个答案:

答案 0 :(得分:5)

您好像是在思考这个问题,您可以通过访问 UsedRange 属性获取电子表格中的所有数据,然后通过访问 Value2 <将其加载到2D数组变量中/ strong>此对象的属性如下:

Dim application = New Excel.Application()
Dim workbook As Excel.Workbook = application.Workbooks.Open("C:\aaa\bbb.xlsx")
Dim worksheet As Excel.Worksheet = workbook.Sheets(1)

Dim usedRange = worksheet.UsedRange
Dim usedRangeAs2DArray As Object(,) = usedRange.Value2

workbook.Save()
workbook.Close()
application.Quit()

Marshal.ReleaseComObject(application)

答案 1 :(得分:2)

您可以使用LIKE运算符:)

'Not sure why you are trying to check Row number for set of characters...

Excel.Range range = sheet.UsedRange;
Int rows_count = range.Rows.Count;

For (int sRow = 1; sRow <= rows_count; sRow++)               
    If (sheet.Cells[sRow, col_end].value Like "*'!@#$%^&*") Then
        '-- input the data to where ever you want. It is best to store it into an array first..
        xRange = sheet.Cells[i, col_end].value; 
        Break;
    Else 
        sRow++;           
    End If

请查看以下参考资料,以便更好地了解您的选择。