How to obtain 2 dimensional arrays of Single in VB.NET exactly like in VBA? - arrays

I have some code written in VBA that uses a function of the particular environment I programmed in, which given some empty, not fixed-dimensional Single arrays, gives them back 2 dimensional and filled with data. It also produces a Variant as output.
The VBA code is:
Dim vDummy As Variant
Dim RealLev1() As Single, ImagLev1() As Single
vDummy = FFPOL1Array(RealLev1, ImagLev1)
Now, I know for sure that FFPOL1Arrayis a routine written in FORTRAN, but I cannot access to its code by any means.
I successfully managed to address the same routine in a VB.NET piece of code by writing a workaround that "links" my code to the environment mentioned above and uses its own scripting routines.
My VB.NET code would be:
Dim vDummy As Object
Dim RealLev1(,) As Single, ImagLev1(,) As Single
vDummy = NSI.FFPOL1Array(RealLev1, ImagLev1)
NSI is the "scripting routines object", which is working with many other functions and subroutines.
Sadly the code above does not work because (according to the debugger) of a type conflict. So I checked the Classes-Explorer and found out that the FFPol1Array class is defined as:
get_FFPOL1Array(ByRef System.Array, ByRef System.Array) As Object
set_FFPOL1Array(ByRef System.Array, ByRef System.Array, ByRef Object)
Thus I tried to Dim my arrays as System.Array instad of Single but this failed too always because of a type conflict. What am I doing wrong?

OK this was a little ridiculous but I managed to understand that I eventually had to initialize the Arrays, because the FORTRAN function did not do that:
Dim RealLev1 As Array = Array.CreateInstance(GetType(Single), 1, 1)
Dim ImagLev1 As Array = Array.CreateInstance(GetType(Single), 1, 1)
This did the job. Even better was:
Dim RealLev1(,) As Single = Array.CreateInstance(GetType(Single), 1, 1)
Dim ImagLev1(,) As Single = Array.CreateInstance(GetType(Single), 1, 1)

As #Nathan_Sav suggested, get_FFPOL1Array is returning an Object so you need to use Set.
Set vDummy = NSI.FFPOL1Array(RealLev1, ImagLev1)

Related

Can't copy a value from one worksheet over to an array in another worksheet

In the same workbook, I've got two worksheets: Model and Results.
My goal is to copy the value of a cell in Model (for e.g., F8) over to a cell in an array (c4 to I23) in Results called ResultsArray (see code below).
When I run my module, no error appears, but the code doesnt seem to work either (the value of F8 doesnt get copied over to the specified cell in ResultsArray).
Appreciate any help.
Tried running different variations of the code below
Sub CopyTest()
Dim ResultsArray As Variant
ResultsArray = Worksheets("Results").Range("C4:I23")
ResultsArray(1, 1) = Worksheets("Model").Range("F8").Value
End Sub
I'm using ResultsArray(1,1) because I am hoping to introduce a loop into the code to populate cells in the array based on the loop counter, e.g., ResultsArray(loopcounter,1)
So turns out I just needed to add "Set" in the 2nd line before "ResultsArray" when assigning the range from the worksheet "Model" to it:
Sub CopyTest()
Dim ResultsArray As Variant
Set ResultsArray = Worksheets("Results").Range("C4:I23")
ResultsArray(1, 1) = Worksheets("Model").Range("F8").Value
End Sub
I've tested this addition and it works

Syntax check fails on array as parameter to sub

I have two related problems. It seems like I don't have a library attached. I have searched and cannot find what I am missing. This is a call to a sub from a function that is called(referenced) in an Excel cell.
The syntax checker fails when I put an array in as a parameter like this which is taken from this VB Page
Sub EmptyValid210917 _
(RefData As String, RefRow As Integer, PhraseArray As String(,), _
DayIndex As Integer, EmptyCol As Boolean, ValidCol As Boolean)
The second related issue is the syntax check fails when I try to dim an array like this:
Dim ColOffset(,) As Integer
It will accept this:
Dim ColOffset(2, 2) As Integer
But does not accept loading as below which is taken from this VB Guide How To
Dim ColOffset(2, 2) As Integer = {{1,2},{3,4}}
Perhaps this is also related. When I call the max function. I get: Compile Error - Method or data member not found
FirstValidDay = Math.Max(1, 2)
Thank you for your help.

Populating 2D-Arrays from CSV (without m*n-Loops)

while migrating an Excel-VBA project to Visual Basic 2010, I came across a problem when populating arrays.
In Excel-VBA I would do something like
Function mtxCorrel() As Variant
mtxCorrel = wsCorr.UsedRange
End Function
to read an m*n-matrix (in this case n*n), that is conveniently stored in a worksheet, into an array for further use.
In VB2010 I obviously won't use an Excel-Worksheet as storage. csv-Files (see below) seem like a decent alternative.
I want to populate an 2d-array with the csv-contents without looping n*n-times. Let's assume I already know n=4 for demonstration purposes.
This suggests that what I want to do cant be done.
Nevertheless I still hope something like the following could work:
Function mtxCorrel() As Object
Dim array1(4, 4) As String
Using ioReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\cm_KoMa.csv")
With ioReader
.TextFieldType = FileIO.FieldType.Delimited
.SetDelimiters(";")
' Here I want to...
' A) ...either populate the whole 2d-array with something like
array1 = .ReadToEnd()
' B) ... or populate the array by looping its 1d-"rows"
While Not .EndOfData
array1(.LineNumber, 0)= .ReadFields()
End While
End With
End Using
return array1
End Function
Notes:
I'm mainly interested in populating the array.
I'm less interested in potential errors with determining which csv-line belongs into which 1d-"row", and also not interested in checking n.
Appendix: sample csv-File:
1;0.5;0.9;0.3
0.5;1;0.6;0.2
0.9;0.6;1;0.1
0.3;0.2;0.1;1

VBA, inline array

Looking to create an inline array in Visual Basic for Applications
Something like this would be cool:
Dim a() as Integer
set a = {1,2,3}
In Java, this would be the equivalent functionality:
int a[] = {1,2,3};
Also, bonus points if you can tell me how to find its length afterwards (without needing to hard code it, as all the examples my Googling have uncovered)
(please don't tell me to Google it. I normally don't use vb, and I'm discovering that every result for a vb question on Google is answered terribly. ex, hard coding values)
Dim a() As Variant
Dim Length As Integer
a = Array(1,2,3)
Length = UBound(a,1) - LBound(a,1) + 1

How to fill-up cells within a Excel worksheet from a VBA function?

I simply want to fill-up cells in my spreadsheet from a VBA function. By example, I would like to type =FillHere() in a cell, and in result I will have a few cells filled-up with some data.
I tried with such a function:
Function FillHere()
Dim rngCaller As Range
Set rngCaller = Application.Caller
rngCaller.Cells(1, 1) = "HELLO"
rngCaller.Cells(1, 2) = "WORLD"
End Function
It breaks as soon as I try to modify the range. Then I tried this (even it's not really the behavior I'm looking for):
Function FillHere()
Dim rngCaller As Range
Cells(1, 1) = "HELLO"
Cells(1, 2) = "WORLD"
End Function
This is not working neither. But it works if I start this function from VBA using F5! It seems it's not possible to modify anything on the spreadsheet while calling a function... some libraries do that though...
I also tried (in fact it was my first idea) to return a array from the function. The problem is that I only get the first element in the array (there is a trick that implies to select a whole area with the formula at the top left corner + F2 + CTRL-SHIFT-ENTER, but that means the user needs to know by advance the size of the array).
I'm really stuck with this problem. I'm not the final end-user so I need something very easy to use, with, preferably, no argument at all.
PS: I'm sorry I asked this question already, but I wasn't registered at that time and it seems that I can't participate to the other thread anymore.
You will need to do this in two steps:
Change your module to be something like:
Dim lastCall As Variant
Dim lastOutput() As Variant
Function FillHere()
Dim outputArray() As Variant
ReDim outputArray(1 To 1, 1 To 2)
outputArray(1, 1) = "HELLO"
outputArray(1, 2) = "WORLD"
lastOutput = outputArray
Set lastCall = Application.Caller
FillHere = outputArray(1, 1)
End Function
Public Sub WriteBack()
If IsEmpty(lastCall) Then Exit Sub
If lastCall Is Nothing Then Exit Sub
For i = 1 To UBound(lastOutput, 1)
For j = 1 To UBound(lastOutput, 2)
If (i <> 1 Or j <> 1) Then
lastCall.Cells(i, j).Value = lastOutput(i, j)
End If
Next
Next
Set lastCall = Nothing
End Sub
Then in order to call the Sub go into the ThisWorkbook area in VBA and add something like:
Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
Call WriteBack
End Sub
What this does is return the value of the topleft cell and then after calculation completes populates the rest. The way I wrote this it assumes only one FillHere function will be called at a time. If you want to have multiple ones which recalculate at the same time then you will need a more complicated set of global variables.
One word of warning is that this will not care what it overwrites when it populates the other cells.
Edit:
If you want to do this on a Application wide basis in an XLA. The code for the ThisWorkbook area should be something like:
Private WithEvents App As Application
Private Sub App_SheetCalculate(ByVal Sh As Object)
Call WriteBack
End Sub
Private Sub Workbook_Open()
Set App = Application
End Sub
This will wire up the Application Level calculation.
What you're trying to do won't work in Excel - this is by design.
You can do this, though:
Function FillHere()
Redim outputArray(1 To 1, 1 To 2)
outputArray(1, 1) = "HELLO"
outputArray(1, 2) = "WORLD"
FillHere = outputArray
End Function
If you then select two adjacent cells in your worksheet, enter =FillHere() and press Control+Shift+Enter (to apply as an array formula) then you should see your desired output.
Fundamentally, a function can only affect the cell it is called from. It sounds like you may need to look at using the Worksheet_Change or Worksheet_SelectionChange events to trigger the modification of cells in the intended range.
You can do this indirectly using a 2-stage process:
Write your UDF so that it stores data in a sufficiently persistent way (for example global arrrays).
then have an Addin that contains application events that fire after each calculation event, looks at any data stored by the UDFs and then rewrites the neccessary cells (with warning messages about overwrite if appropriate) and reset the stored data.
This way the user does not need to have any code in their workbook.
I think (but do not know for sure) that this is the technique used by Bloomberg etc.

Resources