Excel VB.Net-将数组转换为范围并将值设置为工作表

时间:2018-07-02 15:32:01

标签: excel vb.net excel-dna

几个小时以来,我一直在寻找解决此错误的方法,我发现所有解决方法都无法解决我在设置Range.Value2 = Value时遇到的错误。 同时尝试将数组填充到Excel电子表格中。 当前数组的长度只有1个长度,我已经尝试过使用更大的数组了,到目前为止,它只是在代码的最后一行抛出了这个异常:

System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800A03EC'

代码:

Imports ExcelDna.Integration
Imports Excel = Microsoft.Office.Interop.Excel

Public Function TestFunction()

    'Dim data = New Object(1, 2) {{1, 2, 3}, {2, 3, 4}}
    Dim app As Excel.Application = CType(ExcelDnaUtil.Application, Excel.Application)
    Dim worksheet As Excel.Worksheet = CType(app.ActiveWorkbook.ActiveSheet, Excel.Worksheet)
    Dim rng As Excel.Range = CType(worksheet.Cells(2, 1), Excel.Range)

    Dim arr() As String = New String() {"hello world"}

    'Tried this rng.Value2 = arr as well
    rng.Resize(1, arr.Length).Value2 = arr
End Function

我的目标是能够将矩阵复制到Excel电子表格,但到目前为止 仅需要帮助解决代码随数组引发的错误。 谢谢您以后的回复!

1 个答案:

答案 0 :(得分:0)

Range.Value2是二维数组/矩阵,您也必须使用这样的数组。

Dim arrLine1() As String = {"Hello World!", "red", "green"}

' convert to 2-dimensional array
Dim arr(,) As String
Redim arr(1, arrLine1.Length)
For i = 0 To arrline1.Length - 1
    arr(0, i) = arrLine1(i)
Next

rng.Resize(1, arr.GetUpperBound(1)).Value2 = arr