VB.NET one line code to create array of Excel cell values

61 Views Asked by At

I'm trying to replicate this VBA code in VB.NET

enter image description here

which gives this as result

enter image description here

how can i do this with one line of code in VB.NET?

(I already know to do this with iterations and arrays)

Thanks a lot to everyone who will reply!

1

There are 1 best solutions below

0
Ambie On

First off, don't try and reproduce that VBA code. It's bad and will give you problems - someone's used an unqualified range so there's no telling what data you're doing to get from that.

For a one-liner in VB.Net, you could just Cast the range array using the Object type and call the ToArray() method - remember that you'd need to DirectCast the range to a 2D Object array first to access the Cast method. Something like this (using a qualified range):

Dim a = DirectCast(ws.Range("A1:C1").Value, Object(,)).Cast(Of Object).ToArray()

enter image description here

In VBA, if only one cell is defined in the range (eg "A1") then the value type is a Variant rather than an array of Variants, so any attempt to reference it as an array will throw an error. The same would occur in this VB code if you only referenced one cell.