Writing cell in Excel from C++ - no value written, cell is blank

隐身守侯 提交于 2019-12-23 05:15:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!