How To Load SINGLE CELL Value as Object - In 2D Object Array - InvalidCastException

Setup: ---- VB.net - Visual Studio 2010 - Excel Version 2010 - Option Strict ON
The following WORKS FINE all day long for loading MULTIPLE range values IE: ("F2:F5") or more into a 2D Object Array... No problem... as in the following..
Dim myRangeTwo As Range = ws.Range("F2:F5")  ' MULTIPLE CELL RANGE     
Dim arr2(,) As Object = CType(myRangeTwo.Value(XlRangeValueDataType.xlRangeValueDefault), Object(,))
The ws.range("F2:F5") values are stuffed into the myRangeTwo range variable as 2D Objects and then those are easily stuffed into the 2D object array...
But this does not work for a SINGLE cell range...
Dim myRangeTwo As Range = ws.Range("F2:F2")    ' SINGLE CELL RANGE F2 ONLY            
Dim arr2(,) As Object = CType(myRangeTwo.Value(XlRangeValueDataType.xlRangeValueDefault), Object(,))
This triggers an Invalid Cast Exception error on trying to load into the arr2(,).. because the ws.range("F2:F2") is stuffed into the myRangeTwo variable as a "string"
not as an object therefore is not possible to stuff it into an Object Array and so correctly causes the Invalid Cast Error...
How do you handle this seemingly ridiculously simple problem ??
thanks... Cj

Hello,
Simply answer, you need to determine if the range is a single cell or multiple cells. So the following is geared for returning a DataTable for a start and end cell addresses that are different, granted there is no check to see if the cells are valid i.e.
end cell is before start cell i.e.
Since B1 and B10 is a valid range we are good but if we pass in F1:F1 or F10:F10 we must make a decision as per the if statement at the start of the function and if I were expecting this to happen I would have another function that returned a single value.
Option Strict On
Option Infer On
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Module ExcelDemoIteratingData_2
Public Sub DemoGettingDates()
Dim dt As DataTable = OpenExcelAndIterate(
IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"GetDatesFromB.xlsx"),
"Sheet1",
"B1",
"B10")
Dim SomeDate As Date = #12/1/2013#
Dim Results =
From T In dt
Where Not IsDBNull(T.Item("SomeDate")) AndAlso T.Field(Of Date)("SomeDate") = SomeDate
Select T
).ToList
If Results.Count > 0 Then
For Each row As DataRow In Results
Console.WriteLine("Row [{0}] Value [{1}]",
row.Field(Of Integer)("Identifier"),
row.Field(Of Date)("SomeDate").ToShortDateString)
Next
End If
End Sub
Public Function OpenExcelAndIterate(
ByVal FileName As String,
ByVal SheetName As String,
ByVal StartCell As String,
ByVal EndCell As String) As DataTable
If StartCell = EndCell Then
' Decide logically what to do or
' throw an exception
End If
Dim dt As New DataTable
If IO.File.Exists(FileName) Then
Dim Proceed As Boolean = False
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
Dim xlCells As Excel.Range = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
' For/Next finds our sheet
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
Proceed = True
Exit For
End If
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
If Proceed Then
dt.Columns.AddRange(
New DataColumn() _
New DataColumn With {.ColumnName = "Identifier", .DataType = GetType(Int32), .AutoIncrement = True, .AutoIncrementSeed = 1},
New DataColumn With {.ColumnName = "SomeDate", .DataType = GetType(Date)}
Dim xlUsedRange = xlWorkSheet.Range(StartCell, EndCell)
Try
Dim ExcelArray(,) As Object = CType(xlUsedRange.Value(Excel.XlRangeValueDataType.xlRangeValueDefault), Object(,))
If ExcelArray IsNot Nothing Then
' Get bounds of the array.
Dim bound0 As Integer = ExcelArray.GetUpperBound(0)
Dim bound1 As Integer = ExcelArray.GetUpperBound(1)
For j As Integer = 1 To bound0
If (ExcelArray(j, 1) IsNot Nothing) Then
dt.Rows.Add(New Object() {Nothing, ExcelArray(j, 1)})
Else
dt.Rows.Add(New Object() {Nothing, Nothing})
End If
Next
End If
Finally
ReleaseComObject(xlUsedRange)
End Try
Else
MessageBox.Show(SheetName & " not found.")
End If
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlCells)
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
Else
MessageBox.Show("'" & FileName & "' not located. Try one of the write examples first.")
End If
Return dt
End Function
Private Sub ReleaseComObject(ByVal sender As Object)
Try
If sender IsNot Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(sender)
sender = Nothing
End If
Catch ex As Exception
sender = Nothing
End Try
End Sub
End Module
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

Similar Messages

  • How can i get the value stored in the session object using its sessionid

    how can i get the value stored in the session object using its sessionid by running stand alone java application

    myforum wrote:
    how can i get the value stored in the session object using its sessionid by running stand alone java applicationThis does not seem to make sense! You need at least to give a lot more detail of what you are doing.

  • How to get selected Cell value in datagrid?

    Hi guys, I have a datagrid that is editable. I was wondering if it's possible to retreive the cell value after user edits the single cell.
    My datagrid will trigger griditemEditorSessionSave event if users finish the editing, but I don't know how to get the new cell value.
    //script
    protected function dg_gridItemEditorSessionSaveHandler(event:GridItemEditorEvent):void
         //I can only get the columnIndex but not the value
          Alert.show (event.columnIndex);
    //mxml
    <s:DataGrid id="dg" editable="true" x="5" y="3" width="734" height="153"
                      gridItemEditorSessionSave="dg_gridItemEditorSessionSaveHandler(event)"
    >
    </Datagrid>
    Any thoughts? Thanks a lot.

    Hi,
    Please go through following link :
    http://corlan.org/2008/08/31/retrieving-the-new-values-while-editing-data-inside-the-data- grids/
    Hope it helps you
    Thanks and Regards,
    Vibhuti Gosavi | [email protected] | www.infocepts.com

  • How to get TableView cell values

    Hi All,
    I'm new to PDK.
    I have a TableView which set to Single Selection (the table has a column of radio buttons).
    When the user selects a row I want to get the cells' values of the row from the client side.
    I can get the row's number by using the following code:
    tvModel.setOnClientRowSelection("generateNumber(htmlbevent)");
    function generateNumber(myEvent) {
    alert(myEvent.obj.clickedRow.toString());
    Is there a function like getValueAt(row,col)?
    How can I solve this?
    Thanks,
    Omri

    Hi
    There is a function getValueAt(row,col) to get a value at particular row and column.
    Please go through the followin forum thread which is related to your problem:
    Using OnCellClick with TableView to get cell value
    Hope this helps you.
    Regards
    Victoria

  • How to disable single cell in table control.

    Hi my requirement is to disable single cell in the table control. Please let me know How to do this.
    If possible please provide good module pool examples.
    Harish

    Hi,
    I´m not quite sure if this is gonna work. You have to make a loop over the screen and then you can change some characteristics of it, which includes the Input option:
      LOOP AT SCREEN.
        IF screen-group1 = 'ABC'.
          screen-input = '0'.
          MODIFY SCREEN.
        ENDIF.
      ENDLOOP.
    I´ve used this code for selection screens but could help you. Check in SE11 all options for SCREEN.

  • How to change the cell value in Excel Sheet in WD Java?

    HI,
    I have an application which is used to upload and download excel sheet.I can upload the excel sheet through Upload UI element and also able to download the same file through Download UI.But before download I want to validate the excel sheet.If data is not proper in the excel then I have to put some comment (cell comment).I am able to read each cell value,but not ble to put any comment.Once I pt commen in the cell,the download file should display the commented in the excel sheet.
    Please let me know how to update hte excel sheet.
    Sandip

    hi Sandeep,
    I'm not sure about the HSSF apis, however, i inserted the Cell Comments using jexcel apis. There is a method setComment(java.lang.String s, double width, double height) in class WritableCellFeatures using which you can insert cell comments
    For more details refer [link|http://jexcelapi.sourceforge.net/resources/javadocs/current/docs/jxl/write/WritableCellFeatures.html]
    Abhinav

  • How to make crosstab cell value become hot link which can link to other?

    Dear Gurus:
    I am using Bi beans in a project, i create a crosstab in one .jsp file,the crosstable can display data correctly,but i want to make every cell value become hot link which point to a url,this url contains measure info and all dimension info,how can i do? Thanks a lot!

    Hi Tomsong,
    We will post a BI Beans Sample that does that to OTN next week.
    In the mean time, look at the following BI Beans Help topic (under Jdeveloper BI Beans Help)
    Handling Drill-Out Events in HTML-Client Applications
    Hope this helps
    Katia

  • How to map single input value to Two columns of Database table using format file of Bulk Copy Process

    Hi All,
    Am using OPENROWSET to load the file data into table, here the problem is i need to map same input value to two different columns of table, As format file doesn't allow the duplicate numbers am unable to insert same value to two columns, please help me to
    find a solution for this. 
    i can use only OPENROWSET because i need to insert some default values also which come based on file. only the problem is how to map same input value to two different columns of table. please give me the suggestions.
    Thanks,
    Sudhakar

    From what you say:
       INSERT tbl(col1, col2)
          SELECT col1, col1
          FROM   OPENROWSET(....)
    But I guess it is more difficult. You need to give more details. What sort of data source do you have? What does your query look like? The target table?
    Erland Sommarskog, SQL Server MVP, [email protected]
    Hi Erland,
    Thanks for your response
    my source file is text file with | symbol separate for ex:
    1002|eTab |V101|eTablet|V100|Logic|LT-7|Laptops|SCM
    Database table have columns like
    column1,column2,column3...etc, now i need to insert same value from input file into two columns for ex:
    the eTab value from text file has to be insert into column2 and column3 of
    table
    we cannot change format file like below one
    for the above situation how can we insert eTab into column2 and column3
    Thanks,
    Sudhakar.

  • How to send single id value in apex url on clik of link column in report

    Hi,
    Im using the following code to generate a report, in which BP_NAME is a link coloumn ,So I want to send the id(best_attachment table column ie bpa_id) to the next page(6) when I click on the link.If I hoover my mouse on the link it is showing the url like
    ..../f?p=114:31:5954054962330632:REQ:NO:P6_BP_ID:6,12,14(for the record 30 and if it is a two name it will pass two id)
    But i need to pass only one id on click of a link ,but in the url it showing three id.
    ===code====
    select bp_id,
    (select LISTAGG(BP_NAME, ';') WITHIN GROUP (order by BP_NAME) from best_attachment bpa where bpa.bpa_bp_id = bp.bp_id ) BP_NAME
    from best_practices bp
    ===========
    Ex
         Link column<br>
    10 Whalen
    20 Hartstein
    30 Raphaely;
         Khoo;
         Tobias;
    40 Mavris
    If I click any name on 30 record that is Raphaely, Khoo,Tobias It is showing the three id in the url and passing the same. Pls tell me how to pass single id(bpa_id) on clik of a link.And how to alter the above code to achive the same.
    Regards
    Balaji

    No One :(

  • How to achieve matrix cell value of systems forms matrix ?

    Hi,
    When user types data in perticular cell of matrix in system Form , i want to achieve that data.
    How can i achieve that data ?
    Do any one have some sample code plz. fwd it.
    Regards,
    Ganesh

    Hi Makarand,
    This should do the trick.
    <b>Code (C#):</b>
    public override void Handle_ItemEvent(string FormUID, ref ItemEvent pVal, out bool BubblesEvent)
      /* Switch by eventtype */
      switch(pVal.EventType)
        case BoEventTypes.et_VALIDATE:
          /* Get a matrix object */
          Matrix oMatrix = (Matrix)SBO_Application.Forms.Item(FormUID).Items.Item("MY_MATRIX_ID").Specific;
          /* Get a EditText object for the matrix cell */
          EditText oEdit = (EditText)oMatrix.Columns.Item("COLUMN_ID").Cells.Item("ROW_NUMBER").Specific;
          /* Get the value from the object */
          string sValue = oEdit.Value;
          /* Do other things you like ;) */
          break;
    Hope it helps,
    Rowdy

  • How to load a default value in to a column when using sql loader

    Im trying to load from a flat file using sql loader.
    for 1 column i need to update using a default value
    how to go about this?

    Hi!
    try this code --
    LOAD DATA
       INFILE 'sample.dat'
       REPLACE
       INTO TABLE emp
       empno   POSITION(01:04) INTEGER EXTERNAL NULLIF empno=BLANKS,
       ename   POSITION(06:15)  CHAR,
       job         POSITION(17:25)  CHAR,
       mgr       POSITION(27:30)  INTEGER EXTERNAL NULLIF mgr=BLANKS,
       sal        POSITION(32:39)  DECIMAL EXTERNAL NULLIF sal=BLANKS,
       comm   POSITION(41:48)  DECIMAL EXTERNAL DEFAULTIF comm = 100,
       deptno  POSITION(50:51)  INTEGER EXTERNAL NULLIF deptno=BLANKS,
       hiredate POSITION(52:62) CONSTANT SYSDATE
      )-hope this will solve ur purpose.
    Regards.
    Satyaki De.

  • How do I assign the value of a Boilerplate Text Object to a Placeholder Column?

    I have a Boiler plate File Link. This references a .txt file. I want to generate XML tags for it.
    Is it possible to read the content of the file link object into a Placeholder column so that I can get a tag generated for that?

    Hi Frank,
    The key is already passed from a previous page. To set the scene a little, I have three pages:
    1. Project list, has a table listing all projects.
    2. Drill down to tasks for a project, passing the project key as a page property. This is a master/detail page. This currently works well.
    3. Create a new task for the project from page 2. I want to pass the project key obtained from page 1 to page 3 via page 2, so that the user does not have to re-select a project when creating a task.
    Here is my registrydef from page 2 (the tasks for a project):
    <bc4j:rootAppModuleDef name="ProjectModule"
    defFullName="ProjectPackage.ProjectModule"
    configName="ProjectModuleLocal"
    releaseMode="stateful">
    <bc4j:viewObjectDef name="ProjectsVO1">
    <bc4j:rowDef name="ProjectRow" autoCreate="false" usesCurrency="true">
    <bc4j:propertyKey name="key"/>
    </bc4j:rowDef>
    </bc4j:viewObjectDef>
    <bc4j:viewObjectDef name="TasksVO2" rangeSize="20"/>
    </bc4j:rootAppModuleDef>
    This works well, I can display the selected project and then list the tasks in a table.
    My problem is that in page 2 the project record is not in a table, so I cannot use a table selection mechanism to set the key value in the event which calls page 3 (see my earlier post for this code). As the key that I need is sittng there in the URL as a page property, I want to pass that instead. How to I reference it from within an event?
    Does this make sense or is there a better way of doing it? Do I actually need a new page to create a new task - I don't think I can add new records in a table!
    Thanks for the tip on ctrl: , I'm slowly getting the hang of the namespace thing.
    Steve

  • How to give single multiple values

    Hi,
      I am having one scenario like ,in one report if i had given multiple single values in select option parameter but it is taken only first value please can you suggest on this issue.
    Thanks,
    Harinath

    just click on the arrow (extension) button if you can see multiple value then it is taking correctly. other wise let us know how are you assigning the multiple single value?
    s_op-low = '1000'.
    s_op-sign = 'I'.
    s_op-option = 'EQ'.
    append s_op.
    s_op-low = '2000'.
    s_op-sign = 'I'.
    s_op-option = 'EQ'.
    append s_op.
    s_op-low = '3000'.
    s_op-sign = 'I'.
    s_op-option = 'EQ'.
    append s_op.
    like that or from selection screen?
    regards
    shiba dutta

  • How to load one filter values based on another filter selection

    Hi,
    I have a Query/Report that contains the following filters
    Product Family
    Product Line
    Product
    all the above InfoObjects are independent, now i need a functionality where in if i select a Product Family then all the Product Line belonging to that Product Family should get loaded in the filter selection, same way when a Product Line is selected the all the Products under that Product Line should get loaded ni Products filter.
    Please let me know how this functionality can be achived.
    Thanks
    Akila. R

    Hi Akila,
    I am assuming you query runs on a cube that loads data from the source system. In that case cube will contain only valid cobminations of Product Family & Product Line.
    In order to make sure that if a cetain Product Family is chosen you want to see only the relevant Product Line as available in the cube do the following:
    Go to Query Designer Filter
    Pick Product Family > Properties> Advanced. Under the Tab Filter Value Selection during Query Execution choose 'Only Values in InfoProvider'
    Do the same setting for Product Line as well.
    Hope this helps.
    Regards,
    Amrita
    Edited by: Amrita Goswami on Jun 23, 2009 7:26 AM

  • How to map single context value attribute to multiple value attributes?

    Hello,
    is there any way to map a single value attribute
    from view's context into several value attributes
    in controller's context?
    The business context of what I want to achieve
    is the following: I have a view which can be called
    in two modes: read only (RO) and read-write (RW).
    The input parameters to the view are the same for
    both modes, however when in RO mode, the view calls
    a different set of web services than when called
    in RW mode. Before calling each of the web services
    I need to populate their context value attributes
    with appropriate input values.
    I know I can do it in Java code, but is it possible
    to do it without any programming (doing it in the
    source code is prone to errors)?
    Any help highly appreciated.
    Greetings,
    Tomek.

    Hi Kishore,
    than you very much for your kind help.
    I have already created a value attribute of type
    boolean and mapped it into the read-only property
    of the UI elements. This however does not solve all
    of the problems... I will describe it with an
    example:
    Let's say the form I want to implement will be
    used to: create (read-write mode), update (read-
    write mode) or show (read-only mode) customer's
    data. The customer's data is complex (lots of
    data, including tree structures).
    The problem is that:
    - when the form is called in read-only mode,
      it should populate its fields with values
      provided by the getCustomerData web service,
    - when the form is called to create a new
      customer (in read-write) mode, it should
      not use the getCustomerData web service.
      Instead it should map the input values
      entered by the user into input parameters
      of the createNewCustomer web service,
    - when the form is called to update customer's
      data, it should first display values returned
      by the getCustomerData web service, and then
      it should map the modified values entered by
      the user into input parameters of the
      updateCustomer web service,
    In all the above cases I must map my view's
    context data to different controller's context
    elements. Doing it directly in the source code
    is not a nice solution. Is there any other
    way to achieve this? 
    Calling a form in different modes in not an
    unusual thing, so I was hoping that maybe
    there are any built-in mechanisms that would
    solve the obove problem...
    Greetings,
    Tomek.

Maybe you are looking for

  • Switching Macs, sync problem.

    *I have a 3GS 16GB iPhone which will be a year old in August. When I had it, I was syncing it on my old Macbook Pro which is about 2 and a half years old. No problems there.* I now have a 13 inch Macbook Pro 2.66GHz, only about a week old. My iPhone

  • Small Update!

     Hey guys! About a month ago I started my journey to rebuilding my credit.  Original thread was herehttp://ficoforums.myfico.com/t5/Rebuilding-Your-Credit/Help-getting-credit-back-on-track/td-p/3968053 So far I've had four baddies removed from the tr

  • How to split the Multi Provider

    HI All, Please give me the steps How to split the Multi provider and also let me know how to find the multi provider is parellal or series? Thanks Vasu.

  • Question about google maps

    when I press and hold on a place on a google map, a black popup comes up with the word "action" on it.what does this mean?

  • Workflow not proceeding, when decision workitem is executed from WEB UI

    Hi Gurus, We are using the standard user decision task(TS00008267) in a custom workflow.If we execute the Decision task workitem from the SAP Inbox(backend SAP GUI) then if  we see the workflow log the outcome of the decision task is being populated