Reputation: 2158
I'm working on converting an Excel VBA project to a VB.net Office Solution. In VBA accessing a named range within a sheet was pretty easy.
Sheet1.Range("NamedRange")
would give you the value in that cell.
In VB.net I've tried several different things, all ending in failure.
I started here. http://msdn.microsoft.com/en-us/library/aa168292(v=office.11).aspx#excelobj_link9
I'm using one of the Visual Studio Excel 2010 Document template, and I managed to set a value in a named range on a sheet. The template creates a class for each tab on the worksheet, so I was able to do this.
Me.Range("A5").Value
What I'm having trouble with is how to access a range on a worksheet, in particular I can't figure out what objects I need to create before I can access a worksheet. The following is what does not work:)
Public Sub GetInputs()
Dim XlSheet1 As Excel.Worksheets
Xlval = XlSheet1("Sheet1").Range("NamedRange").Value
This leaves me with null reference... I've tried several other things and gotten several other errors. Any push in the correct direction would be much appreciated.
Upvotes: 1
Views: 3700
Reputation: 27478
The following code compiles and runs in a separate code module. The key is using the Globals object to access the Excel application objects:
Dim xlWorksheet As Excel.Worksheet
Dim xlNamedRange As Excel.Range
Dim xlVal As Object
xlWorksheet = Globals.ThisWorkbook.Worksheets("Sheet1")
xlNamedRange = xlWorksheet.Range("NamedRange")
xlVal = xlNamedRange.Value
MessageBox.Show(xlVal)
Upvotes: 1