[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 885
  • Last Modified:

Excel 2003 automation: setting an array as value of range-object

I have been working on a routine for saving DataTable to excel (2003), with help from :http://support.microsoft.com/kb/q302094

This procedures however fails on the line which sets the value of the excel-range to the generated array.

I was hoping to accomplish this using late binding, but this yields:
"System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC.
   at Microsoft.VisualBasic.CompilerServices.LateBinding.InternalLateSet(Object o, Type& objType, String name, Object[] args, String[] paramnames, Boolean OptimisticSet, CallType UseCallType)
   at Microsoft.VisualBasic.CompilerServices.LateBinding.LateSet(Object o, Type objType, String name, Object[] args, String[] paramnames)
   at..."

Using early binding, I get an error at the same line, that reads:
"System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC.
   at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
   at Excel.Range.set_Value(Object RangeValueDataType, Object )
   at...."

Any help would be appreciated.

Regards
Kai


Public Sub DataTableExport(ByVal myDataTable As DataTable, ByVal myWorkSheetName As String)

        Dim objSaveFileDialog As New SaveFileDialog
        Dim strFileName As String

        objSaveFileDialog.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal)
        objSaveFileDialog.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*"
        objSaveFileDialog.FilterIndex = 2
        objSaveFileDialog.RestoreDirectory = True

        If objSaveFileDialog.ShowDialog() = DialogResult.OK Then
            strFileName = objSaveFileDialog.FileName
        Else
            Exit Sub
        End If

        Application.DoEvents()

        Dim oExcel As Object
        Dim oBook As Object
        Dim oSheet As Object
        Dim oRange As Object
        Dim nCols As Integer
        Dim nRows As Integer

        oExcel = CreateObject("Excel.Application")
        oBook = oExcel.Workbooks.Add
        nCols = myDataTable.Columns.Count
        nRows = myDataTable.Rows.Count

        Dim DataArray(nRows, nCols) As Object
        Dim r As Integer
        Dim c As Integer
        For r = 0 To nRows - 1
            For c = 0 To nCols - 1
                If r = 0 Then
                    DataArray(r, c) = myDataTable.Columns(c).ColumnName
                    DataArray(r + 1, c) = myDataTable.Rows(r)(c)
                Else
                    DataArray(r + 1, c) = myDataTable.Rows(r)(c)
                End If

            Next
            RaiseEvent ConvertionInProgress(r + 1, nRows)
            Application.DoEvents()
        Next
        RaiseEvent AppendingToExcelFile()
        Application.DoEvents()
        oSheet = oBook.Worksheets(1)
        oSheet.name = myWorkSheetName

        oRange = oSheet.Range("A1", Reflection.Missing.Value)
        oRange = oRange.Resize(nRows + 1, nCols )
       
         '************************************
        oRange.Value = DataArray '' This line produces the error !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        '*************************************

        RaiseEvent SavingExcelFile()
        Application.DoEvents()

        'Save the Workbook and quit Excel.
        oBook.SaveAs(strFileName)

        oSheet = Nothing
        oBook = Nothing
        oExcel.application.Quit()
        oExcel = Nothing

        GC.Collect()
    End Sub
0
lieka
Asked:
lieka
2 Solutions
 
bruintjeCommented:
Hello lieka,

just by looking at your code did you forget to resize the column part? but this could be a copy / paste thing
oRange = oRange.Resize(nRows + 1, nCols + 1) instead of oRange = oRange.Resize(nRows + 1, nCols )

but now i look at the array and range, you subtract one of the nRows and nCols for the array so why not use
oRange = oRange.Resize(nRows, nCols)
since the range array has its base at 1,1 already so no need to correct like in the zero based array of VB

hope this helps a bit
bruintje
0
 
Bob LearnedCommented:
Here is a class that I use to access an Excel worksheet:

Imports Microsoft.Office.Interop
Imports Microsoft.Office.Core
Imports System.Runtime.InteropServices

Public Class ExcelWorksheet

  Private _app As Excel.Application
  Private _workbook As Excel.Workbook
  Private _worksheet As Excel.Worksheet

  Public Sub New()

    _app = New Excel.Application

  End Sub  'New


  Public Property ApplicationVisible() As Boolean
    Get
      Return _app.Visible
    End Get
    Set(ByVal Value As Boolean)
      _app.Visible = Value
    End Set
  End Property  'ApplicationVisible


  Public Property AssistantVisible() As Boolean
    Get
      Return _app.Assistant.Visible
    End Get
    Set(ByVal Value As Boolean)
      _app.Assistant.Visible = Value
    End Set
  End Property  'AssistantVisible


  Protected Overrides Sub Finalize()
    MyBase.Finalize()

    _workbook.Close(SaveChanges:=False)

    _app.Quit()

    Marshal.ReleaseComObject(_app)
    Marshal.ReleaseComObject(_workbook)
    Marshal.ReleaseComObject(_worksheet)

  End Sub   'Finalize


  Public Sub Save()

    _workbook.Save()

  End Sub  'Save


  Public Sub DeleteRow(ByVal row As Integer)

    If row < 1 OrElse row > _worksheet.Rows.Count Then
      Throw New ArgumentOutOfRangeException("Row must be 1.." & _worksheet.Rows.Count)
    End If

    CType(_worksheet.Rows(row), Excel.Range).Delete()

  End Sub


  Public Function GetWorksheetData(ByVal fileName As String, _
   ByVal sheetName As String, ByVal fromCell As String, ByVal toCell As String, _
   ByVal firstRowHeader As Boolean) As DataTable

    _workbook = _app.Workbooks.Open(fileName)

    _worksheet = _workbook.Worksheets(sheetName)

    Dim rangeSelect As Excel.Range = _worksheet.Range(fromCell, toCell)

    Dim rowCount As Integer = rangeSelect.Rows.Count
    Dim columnCount As Integer = rangeSelect.Columns.Count

    Dim tableNew As New System.Data.DataTable(sheetName)

    For colIndex As Integer = 1 To columnCount

      Dim colName As String = "Column" & colIndex

      If firstRowHeader Then
        colName = CType(rangeSelect.Cells(1, colIndex), Excel.Range).Value
      End If

      tableNew.Columns.Add(New DataColumn(colName, GetType(String)))

    Next colIndex

    For rowIndex As Integer = 1 To rowCount

      Dim rowNew As DataRow = tableNew.NewRow

      For colIndex As Integer = 1 To columnCount
        rowNew(colindex - 1) = CType(rangeSelect.Cells(rowIndex, colindex), Excel.Range).Value
      Next

      tableNew.Rows.Add(rowNew)

    Next

    Return tableNew

  End Function   'GetWorksheetData


  Public Property CellText(ByVal row As Integer, ByVal column As Integer) As String
    Get
      If row < 1 OrElse row > _worksheet.Rows.Count Then
        Throw New ArgumentOutOfRangeException("Row")
      End If
      If column < 1 OrElse column > _worksheet.Columns.Count Then
        Throw New ArgumentOutOfRangeException("Column")
      End If

      Dim cellRange As Excel.Range = _worksheet.Cells(row, column)
      Return cellRange.Value
    End Get
    Set(ByVal Value As String)
      If row < 1 OrElse row > _worksheet.Rows.Count Then
        Throw New ArgumentOutOfRangeException("Row")
      End If
      If column < 1 OrElse column > _worksheet.Columns.Count Then
        Throw New ArgumentOutOfRangeException("Column")
      End If

      Dim cellRange As Excel.Range = _worksheet.Cells(row, column)
      cellRange.Value = Value
    End Set
  End Property  'CellText


  Public Property CellFormula(ByVal row As Integer, ByVal column As Integer) As String
    Get
      If row < 1 OrElse row > _worksheet.Rows.Count Then
        Throw New ArgumentOutOfRangeException("Row")
      End If
      If column < 1 OrElse column > _worksheet.Columns.Count Then
        Throw New ArgumentOutOfRangeException("Column")
      End If

      Dim cellRange As Excel.Range = _worksheet.Cells(row, column)
      Return cellRange.Formula
    End Get
    Set(ByVal Value As String)
      If row < 1 OrElse row > _worksheet.Rows.Count Then
        Throw New ArgumentOutOfRangeException("Row")
      End If
      If column < 1 OrElse column > _worksheet.Columns.Count Then
        Throw New ArgumentOutOfRangeException("Column")
      End If

      Dim cellRange As Excel.Range = _worksheet.Cells(row, column)
      cellRange.Formula = Value
    End Set
  End Property  'CellFormula

End Class

Bob
0
 
liekaAuthor Commented:
Thanks, examining the Range-object and the Array-object showed that the arrayobject in fact had one column to much.
I have fixed the dimension of the array, however, the problem is the same.

When I try to set the value-property (with string values or object-values) of single cell ranges no problem is seen.

Examining the oRange-object in (before/above the error causing line)debug-mode shows <error: an exception of type: {System.Runtime.InteropServices.COMException} occurred> for quite a few members of this object!

Is it likely that this is a "references"-problem? The application is going to be used by persons having either Excel 2000 - Excel 2003, so I was hoping to do this using late binding.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now