问题
When I write a cell from C++ with OLE to a cell in Excel, I get an empty cell. Whatever value is there gets overwritten to be blank. It writes in the correct cell though, so it seems the range is correct. This is my code.
VARIANT arr;
BSTR val = SysAllocString(L"hello excel world");
_bstr_t(val, false);
arr.vt = VT_ARRAY | VT_VARIANT;
SAFEARRAYBOUND sab[1];
sab[0].lLbound = 1; sab[0].cElements = 1;
arr.parray = SafeArrayCreate(VT_VARIANT, 1, sab);
long indices[] = {1, 1};
SafeArrayPutElement(arr.parray, indices, (void*)&val);
AutoWrap(DISPATCH_PROPERTYPUT, NULL, range, L"Value", 1, arr);
回答1:
I did not understand how to correctly pass an argument to Excel. It needs to be a variant, not a naked BSTR:
VARIANT arr;
BSTR val = SysAllocString(L"hello excel world");
_bstr_t(val, false);
arr.vt = VT_ARRAY | VT_VARIANT;
SAFEARRAYBOUND sab[2];
sab[0].lLbound = 1; sab[0].cElements = 1;
sab[1].lLbound = 1; sab[1].cElements = 1;
arr.parray = SafeArrayCreate(VT_VARIANT, 2, sab);
long indices[] = {1, 1};
VARIANT valvariant;
valvariant.vt = VT_BSTR;
valvariant.bstrVal = val;
SafeArrayPutElement(arr.parray, indices, (void*)&valvariant);
AutoWrap(DISPATCH_PROPERTYPUT, NULL, range, L"Value", 1, arr);
来源:https://stackoverflow.com/questions/33149605/writing-cell-in-excel-from-c-no-value-written-cell-is-blank