I have read a few posts on this now but none quite answer what I am after.
I am writing a C dll (not C++) to read a specific type of data file, and return the data to vba for display in excel. For speed I would like to return the data as an array, but don't know ahead of time how big that array will be.
I have come across SAFEARRAY data type in C which seems to be the way to go but I can't figure out how to redimension it. I am trying to use "SafeArrayRedim". When I run it from vba it crashes at the line where it calls the dll -> it hangs for a few seconds then excel shuts down. Any ideas what I am doing wrong? Is there a beter way to go about this?
C code:
#include <stdio.h>
#include <Windows.h>
#include "MyDll.h" // use here the name of your header file
long __declspec(dllexport) __stdcall ResizeArray(SAFEARRAY** psaArray, long newSize)
{
SAFEARRAYBOUND bound;
bound.cElements = newSize;
bound.lLbound = 0;
long* data = (*psaArray)->pvData;
SafeArrayRedim(*psaArray, &bou
for (int i = 0; i < newSize; i++)
{
data[i] = i;
}
return newSize;
}
Calling code in VBA:
Option Explicit
Private Declare PtrSafe Function ResizeArray Lib "VBA_Test.dll" (FirstElement As Long, ByVal lElements As Long) As Long
Private Sub test()
Dim ArrayOfLongs(2) As Long
Dim lSum As Long
Dim k As Long
k = ResizeArray(ArrayOfLongs(0), 100)
End Sub