c++excelole

c++ ole automation how to clear excel cell contents


I am using the following function call of IDispatch interface to successfully write Hello World! to a cell in excel sheet excel.

  LPOLESTR ptName = L"Value";    //What is the key for clearing the cell contents?
  DISPID dispID;
  xlCell->GetIDsOfNames(IID_NULL, &ptName, 1, LOCALE_USER_DEFAULT, &dispID);

  LCID lcid = GetUserDefaultLCID();

  std::wstring cellVal = L"Hello World!";
  VARIANT vArgArray[1];
  vArgArray[0].vt = VT_BSTR,
  vArgArray[0].bstrVal = SysAllocString(cellVal.c_str());

  DISPID dispidNamed = DISPID_PROPERTYPUT;
  DISPPARAMS dp = {NULL, NULL, 0, 0};
  dp.cArgs = 1;
  dp.rgvarg = vArgArray;
  dp.cNamedArgs = 1;
  dp.rgdispidNamedArgs = &dispidNamed;

  xlCell->Invoke(
      dispID,
      IID_NULL,
      lcid,
      DISPATCH_PROPERTYPUT,
      &dp,
      NULL,
      NULL,
      NULL);

Now I need to clear a cell using the same IDispatch interface (xlCell)

What value should I use for the LPOLESTR type variable (2nd parameter in GetIDsOfNames function) to initialize the dispID to successfully clear the cell by calling Invoke?


Solution

  • While I could not find the unique DISPID for clearing a cell/cell range, the thing that did work was to modify the VARIANT passed to the Invoke().

    All I did was to change the VARIANT from this

    vArgArray[0].vt = VT_BSTR,
    vArgArray[0].bstrVal = SysAllocString(cellVal.c_str());
    

    to this

    vArgArray[0].vt = VT_EMPTY;
    

    Hope it helps someone.