Search code examples
c++excelcomsafearrayvba

SafeArray of SafeArrays? Help to transfer VBA code to C++


FieldInfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 2), Array(5, 2))

such code from above I have at VBA macros. Now the same thing I should create in a C++ code. As far as I could understand till now - I should use SAFEARRAY type. But I still do not understand how correctly I should do that. Main problem - I have practically pure C++ code. No MSVC extensions like COleSafeArray, no ATL support. The only thing which I can use - STLSoft which is a 100% header-only library which significantly simplifies the creation of such elements like SAFEARRAY.

But in any way - which structure it should be? 1D SafeArray of 1D SafeArrays of two VT_I4 type elements?

P.S. I should use MinGW + gcc 4.x environment.


Solution

  • // Create a 5x2 safearray of integer arrays with VT_I4 fields...
    comstl::variant fieldInfo;
    fieldInfo.vt = VT_ARRAY | VT_VARIANT;
    {
        SAFEARRAYBOUND sab[2];
        sab[0].lLbound = 1; sab[0].cElements = 5; // i
        sab[1].lLbound = 1; sab[1].cElements = 2;  // j
        fieldInfo.parray = SafeArrayCreate(VT_VARIANT, 2, sab);
    }
    
    // Fill safearray with values like:
    /*
       FieldInfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 2), Array(5, 2))
     */
    // first of all fill the first column with data...
    for(int i=1; i<=5; i++) {
        VARIANT tmp;
        tmp.vt = VT_I4;
        tmp.lVal = i;
        // Add to safearray...
        long indices[] = {i,1};
        SafeArrayPutElement(fieldInfo.parray, indices, (void *)&tmp);
    }
    // ...after that - fill the second column.
    for(int i=1; i<=5; i++) {
        VARIANT tmp;
        tmp.vt = VT_I4;
        tmp.lVal = 2;
        // Add to safearray...
        long indices[] = {i,2};
        SafeArrayPutElement(fieldInfo.parray, indices, (void *)&tmp);
    }
    

    And this code allowed to me achieve my Goal!