以下代码将生成一个 x(,) 矩阵,其中包含从 Excel 传输的数组元素,当使用 QuickWatch 查看时,将指示从零开始的数组。但是,该数组将从 1 开始,并且 QuickWatch 中显示的 (0,0) 元素将不可访问。
我认为这种行为是一个错误,因为 QuickWatch 显示存在 (0,0) 元素,但实际上并不存在 - 因为它不可访问。
以下代码将生成有问题的 x(,) 数组,当使用 QuickWatch 查看时将显示 (0,0) 元素。
要实现代码,请将 OperFileDialog1 添加到您的表单中,然后将以下代码粘贴到例如按钮中。您需要确保打开的 Excel 中有有效的字符串或数值单元格 A1、A2、B1、B2。在运行时,由于某种原因,元素 x(0,0) 是不可读的,即使使用 QuickWatch 查看时 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