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

2019-06-14 08:46发布

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条回答
对你真心纯属浪费
2楼-- · 2019-06-14 09:27

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);
查看更多
登录 后发表回答