usmanharoon
usmanharoon

Reputation: 195

Add excel sheet at end or specific location in excel with Visual C++(COM)

I've been trying to add new excel sheet at end of the excel book using C++. But it's returning error saying "Member not found".

AutoWrap function code can be found here: https://learn.microsoft.com/en-us/previous-versions/office/troubleshoot/office-developer/automate-excel-from-c#references

Below is the code:

IDispatch* pSheets = NULL;
VARIANT result;
VariantInit(&result);
hr = AutoWrap(DISPATCH_PROPERTYGET, &result, _pExcelBook, L"Sheets", 0); //Able to get the excel workbook pointer
if (FAILED(hr))
{
    return hr;
}
result.pdispVal->QueryInterface(&pSheets);

IDispatch* pNewSheet = NULL;
if (NULL != pSheets)
{        
    int curBookSheetCount = GetTotalSheetCount(pSheets); //returns the sheet count properly      
    {
        VARIANT result, vParm;
        vParm.vt = VT_I4;
        vParm.lVal = curBookSheetCount;

        hr = AutoWrap(DISPATCH_METHOD, &result, pSheets, L"Item", 1, vParm); // Failed here
        if (FAILED(hr))
        {
            VariantClear(&vParm);
            return hr;
        }

        result.pdispVal->QueryInterface(&pAftrSheet);                
    }

    VARIANT result, var1, var2;
    VariantInit(&result);

    var1.pdispVal = NULL;
    var1.vt = VT_NULL;

    var2.pdispVal = pAftrSheet;
    var2.vt = VT_DISPATCH;

    AutoWrap(DISPATCH_METHOD, &result, pSheets, L"Add", 2, var2, var1);
    result.pdispVal->QueryInterface(&pNewSheet);
}

Why it's failing here? Please suggest your answers.

Also, what's the c++ equivalent for below vb code?

XLSheet.Range("A3", "H3").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter

what should be the parameter for AutoWrap function to set the above property in C++?

Upvotes: 0

Views: 85

Answers (2)

Artem
Artem

Reputation: 1

Compiler gives error "GetTotalSheetCount(pSheets)" is undefined. Would you be so kind to give the implementation of this function, please

Upvotes: 0

usmanharoon
usmanharoon

Reputation: 195

Able to solve the first error. I made a mistake. It should be PROPERTY_GET not METHOD.

hr = AutoWrap(DISPATCH_PROPERTYGET, &result, pSheets, L"Item", 1, vParm);

Kindly suggest your answers for second question.

Upvotes: -1

Related Questions