在C ++中将值设置为Excel单元格抛出exception0x800A03EC

我正在写一个Excel地址。 插件中的UDF之一是通过在C ++中使用Excel自动化来为所选单元格设置值。 在我的代码中,我没有问题来获取范围,从选定的单元格中读取值,但是当我尝试将值设置为单元格时,如果值是一个string,代码将抛出exception(0x80020005types不匹配),否则,例外与HResult 0x800A03EC。 以下是一段代码片段:

有任何想法吗?

void SetValue() { Excel::SheetsPtr pSheets = GetExcelApplicationObj()->GetWorksheets(); Excel::_WorksheetPtr pSheet = GetExcelApplicationObj()->GetActiveSheet(); _variant_t text = pSheet->Range["A2"]->Text; //Read value from selected cell works fine pSheet->Range["C2"]->Value = "Hello"; // throw 0x80020005 Type mismatch pSheet->Range["B2"]->Value = 5.0; //Set value throw Exception with HRESULT 0x800A03EC } Excel::_Application* GetExcelApplicationObj() { if (m_pApp == NULL) { std::vector<HWND>::iterator it; std::vector<HWND> handles = getToplevelWindows(); for (it = handles.begin(); it != handles.end(); it++) { HWND hwndChild = NULL; ::EnumChildWindows( (*it), EnumChildProc, (LPARAM)&hwndChild); if (hwndChild != NULL) { Excel::Window* pWindow = NULL; HRESULT hr = ::AccessibleObjectFromWindow(hwndChild, OBJID_NATIVEOM, __uuidof(Excel::Window), (void**)&pWindow); if (SUCCEEDED(hr)) { if (pWindow != NULL) { m_pApp = pWindow->GetApplication(); pWindow->Release(); } break; } } } } return m_pApp; } std::vector<HWND> getToplevelWindows() { EnumWindowsCallbackArgs args( ::GetCurrentProcessId() ); if ( ::EnumWindows( &EnumWindowsCallback, (LPARAM) &args ) == FALSE ) { return std::vector<HWND>(); } return args.handles; } BOOL CALLBACK EnumWindowsCallback( HWND hnd, LPARAM lParam ) { EnumWindowsCallbackArgs *args = (EnumWindowsCallbackArgs *)lParam; DWORD windowPID; (void)::GetWindowThreadProcessId( hnd, &windowPID ); if ( windowPID == args->pid ) { args->handles.push_back( hnd ); } return TRUE; } BOOL CALLBACK EnumChildProc(HWND hwndChild,LPARAM lParam) { CHAR className[128]; ::GetClassName(hwndChild, className, 128); if (strcmp(className, "EXCEL7") == 0) { HWND * phandle = (HWND*)lParam; (*phandle) = hwndChild; return FALSE; } return TRUE; } 

您必须将string值包装成变体。

尝试这个:

 pSheet->Range["C2"]->Value = _variant_t(_bstr_t("Hello")).Detach();