【问题标题】:set value to Excel cell in C++ throw exception 0x800A03EC在 C++ 中将值设置为 Excel 单元格引发异常 0x800A03EC
【发布时间】:2013-03-18 01:03:06
【问题描述】:

我正在编写一个 Excel 插件。插件中的 UDF 之一是使用 C++ 中的 Excel 自动化为选定的单元格设置值。在我的代码中,我没有问题获取范围,从选定的单元格读取值,但是当我尝试将值设置为单元格时,如果该值是一个字符串,代码抛出异常(0x80020005 类型不匹配),否则,它总是抛出HResult 0x800A03EC 异常。下面是一段代码sn-p:

有什么想法吗?

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;
}

【问题讨论】:

标签: c++ excel automation cell


【解决方案1】:

您必须将string 值包装到一个变体中。

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多