2

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

1 回答 1

0

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

尝试这个:

pSheet->Range["C2"]->Value = _variant_t(_bstr_t("Hello")).Detach();
于 2014-06-27T08:26:21.720 回答