Search code examples
stringole-automationc++builder-10.4-sydney

What is the correct text type for setting OleVariant text properties


The code below used to work when compiled on C++Builder 6.0:

    Variant xlApp, wBook, wSheet, vRange;

    String xlFile  = "C:\\Temp\\ExcelTestFile.xlsx",
           xlTitle = "Relatório de Geração";
    try{
        xlApp = CreateOleObject("Excel.Application");
        // Hide Excel
        xlApp.OlePropertySet("Visible", false);
        // Add new Workbook
        xlApp.OlePropertyGet("WorkBooks").OleFunction("Add", -4167);
        // Get WorkBook
        wBook = xlApp.OlePropertyGet("Workbooks").OlePropertyGet("Item", 1);

        // Get WorkSheet
        wSheet = wBook.OlePropertyGet("Worksheets").OlePropertyGet("Item", 1);
        wSheet.OlePropertySet("Name", xlTitle.c_str() ); // Raise Incorrect Type
    }
    catch(Exception &E){
         ShowMessage( E.Message );
         xlApp.OlePropertySet("DisplayAlerts",false);
         xlApp.OleProcedure("Quit");
    } 

What is the correct string type?

Thank you very much.


Solution

  • The correct type when passing strings through COM is WideString.

    The WideString type is actually a wrapper around the Windows BSTR type, which means behind the scenes it uses the functions:

    You don't have to use WideString; but you do have to use SysAllocString and SysFreeString. You can call them manually, or you can use WideString to do it for you.