将“2维数组”局部变量传递给类级变量

时间:2015-03-04 22:42:12

标签: arrays vb.net class

我有一个子读取Excel文件(X行乘5列)并将其数据复制到名为' matrix'的字符串数组中。在VB.NET中。但是,我确实需要在其他一些潜艇中访问这个数组。我希望将数组传递给类级数组变量,然后从该数组中检索信息。但我不知道如何实现这一目标。

Public Sub ReadFromExcel()
        Dim excel As Application = New Application
        Try
            Dim wrkbook As Workbook = excel.Workbooks.Open(IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location) & _
        "EXCELFILE.xls")
        Dim sheet As Worksheet = wrkbook.Sheets(1)
        Dim cell As Range = sheet.UsedRange
        Dim LastRow As Long = 0
        sheet.Activate()
        With sheet
            LastRow = .Cells(.Rows.Count, 1).End(XlDirection.xlUp).Row
        End With
        Dim matrix(LastRow - 1, 4) As String
        For i As Integer = 2 To LastRow
            For j As Integer = 1 To 5
                matrix(i - 1, j - 1) = cell(i, j).VALUE
            Next
        Next (i)
        wrkbook.Close()
        excel.Quit()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

Public Class Sample
    Private xlsFileContents(0,0) as String

    Public Sub ReadFromExel()
        Dim excel As Application = New Application

        Try
            'all of your code here up to "excel.quit"

            'now redim the class array to match your matrix array
            '<array>.GetUpperBound gets the integer value of the highest index in that dimension of your array.
            'It accepts a zero-bound integer to determine which dimension you are referring to.
            ReDim xlsFileContents(matrix.GetUpperBound(0), matrix.GetUpperBound(1))

            xlsFileContents = matrix

        Catch
            'your code here
        End Try
End Class

我在一个简单的控制台应用程序中尝试了这个,我将数据手动输入matrix数组,这对我有用。