Interop: Cannot call get_Range, and cannot use two-dimensional object array returned by Range().Value2?
Trying to replace Cells(RowIndex,ColumnIndex).Value() calls by row-wise references for performance, I permanently fail at referencing the result.
Starting with Excel Interop - Efficiency and performance, which contains the tip to use get_range
, i.e.
//get values
object[,] objectArray = shtName.get_Range("A1:Z100").Value2;
iFace = Convert.ToInt32(objectArray[1,1]);
//set values
object[,] objectArray = new object[3,1] {{"A"}{"B"}{"C"}};
rngName.Value2 = objectArray;
I figured I cannot use get_Range
since that method is not callable for me, says VB at run-time (not a visible member).
Now I came up with stuff like:
Dim Values As Object(,)
Values = Sheet.Range(Sheet.Cells(RowIndex, 1), Sheet.Cells(2, 17)).Value2
For Index As Integer = 0 To 16
MsgBox(Values(0, Index))
Next
However, referencing Values
with two dimension indices always returns an "index was outside the bounds of the array" exception. Inspecting the array with the debugger shows a nice 2-dimensional array which should has 17 elements on the second dimension, so Value (0,0)
should indeed be a valid reference -- but it isn't:
The debugger lets me inspect Value, I can also drill down to Value(0,0)
and see the correct value, but re-evaluating开发者_如何学C just that element, i.e. inspecting "Value (0,0)
" returns above message.
How can I reference what my Value2 call returns?
Perhaps something like this? Note that if you want the array to have the column as the first element you'd use change the line below as noted:
Imports Microsoft.Office.Interop
Module Module1
Sub main()
Dim appExcel As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim values As Object
appExcel = GetObject(, "Excel.Application")
wb = appExcel.Workbooks(1)
ws = wb.Worksheets(1)
With ws
values = .Range(.Cells(1, 1), .Cells(2, 5)).Value2
'if column is first element use appExcel.Worksheetfunction.Transpose(.Range(.Cells(1, 1), .Cells(2, 5)).Value2)
For i As Int32 = LBound(values, 1) To UBound(values, 1)
For j As Int32 = LBound(values, 2) To UBound(values, 2)
System.Windows.Forms.MessageBox.Show(values(i, j))
Next j
Next
End With
End Sub
End Module
Try
Dim Values As Variant
Dim shtName as Worksheet
Set shtName = <your sheet>
Values = shtName.Range("A1:Z100")
精彩评论