2013-03-27 50 views
2

我在寫一個Excel Addin。插件中的UDF之一是通過在C++中使用Excel自動化將值設置爲所選單元格。在我的代碼中,我沒有問題來獲取範圍,從選定的單元格中讀取值,但是當我嘗試將值設置爲單元格時,如果值是一個字符串,則代碼會拋出異常(0x80020005類型不匹配),否則它總是拋出例外與HResult 0x800A03EC。下面的代碼片段:將值設置爲C++中的Excel單元格拋出異常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; 
} 
+0

您搜索? http://stackoverflow.com/q/7099770/85371,http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/412dd4d6-df62-449c-bb3b-f53cb408ab68/等 – sehe 2013-03-27 19:28:11

+0

我我使用的是Excel 2010,工作表是一個不超過5行的.xlsx。 – user2216761 2013-03-27 19:48:29

+0

然後,它仍然可能是權限,文件系統空間,錯誤的列說明等。 – sehe 2013-03-27 19:51:42

回答

0

您必須將string值包裝爲變體。

試試這個:

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