以下代碼將導致包含從Excel傳輸的數組元素的x(,)矩陣,當使用QuickWatch進行查看時,將指示從零開始的數組。但是,該數組將基於一個數組,並且QuickWatch中顯示的(0,0)元素將不可訪問。爲什麼在我用Excel中的數據填充數據後,VB.NET顯示數組中的(0,0)元素?
我相信這種行爲是一個錯誤,因爲QuickWatch顯示存在一個(0,0)元素,這實際上不存在 - 因爲它不可訪問。
以下代碼將生成有問題的x(,)數組,並且在使用QuickWatch查看時將顯示(0,0)元素。
要實現該代碼,請在表單中添加一個OperFileDialog1,然後將以下代碼粘貼到一個按鈕。您需要確保打開的Excel中存在有效的字符串或數值單元格A1,A2,B1,B2。在運行時,由於某種原因,該元素X(0,0)是不可讀的,即使有快速監視觀看時會有在x(0,0)元素顯示的數據:
Dim i, j As Integer
Dim filename As String
Dim x(,) As Object
Dim myx(,) As Object
With OpenFileDialog1
.FileName = "*.*"
.CheckFileExists = True
.ShowReadOnly = True
.Filter = "Excel 2010 *.xlxs|*.xlxs|Excel 2003-2007 *.xls|*.xls"
If .ShowDialog = Windows.Forms.DialogResult.OK Then
'Load file
filename = .FileName
End If
End With
' Create new Application.
Dim rXL As New Excel.Application
Dim rWB As Excel.Workbook
Dim rSheet As Excel.Worksheet
Dim rRng As Excel.Range
rWB = rXL.Workbooks.Open(filename)
For i = 1 To 1 ' rWB.Sheets.Count To 1 Step -1
Dim sheet As Excel.Worksheet = rWB.Sheets(i)
Dim r As Excel.Range = sheet.UsedRange
If r.Rows.Count = 0 Then Exit For
Dim eCellArray As System.Array = r.Value
ReDim x(r.Rows.Count, r.Columns.Count)
x = r.Value
rRng = Nothing
Next
ReDim myx(x.GetLength(0) + 1, x.GetLength(1) + 1)
For i = 0 To x.GetLength(0)
For j = 0 To x.GetLength(1)
myx(i + 1, j + 1) = x(i, j)
Next
Next
您可以添加一個簡短但完整的示例代碼來說明這個問題嗎? – svick
這是什麼問題? –