环境:xp sp3,vs2008,wps2012,word2010
如果直接设置Range对象的Start或End属性可能会报异常,所以使用SetRange方法或者让Start小于等于Range的End值
word2010直接设置Start的值超过End不会报出异常,但是会将End=Start
void Ctest09242Dlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
::CoInitialize(NULL);
//OnOK();
WPS::_ApplicationPtr g_app;
CLSID clsid;
HRESULT hr;
hr=::CLSIDFromProgID(L"WPS.Application",&clsid); //通过ProgID取得CLSID
try
{
g_app.CreateInstance(__uuidof(WPS::Application )) ;
}
catch (...)
{
AfxMessageBox("啊呀不是没装wps吧?");
return;
}
WPS::DocumentsPtr docs =g_app->GetDocuments();
//内容:abcdefghijklmn
CString sWord="e:\\1011.doc";
WPS::_DocumentPtr p_doc;
_bstr_t sNull;
try
{
p_doc = docs->Open(
_bstr_t(sWord),
VARIANT_FALSE, // 确认转换
VARIANT_TRUE, // 只读
VARIANT_FALSE, // 添加到最近文件中
sNull, // 文档口令.
sNull, // 模板口令.
VARIANT_FALSE, // 恢复原状.
sNull, // 写文档口令.
sNull, // 写模板口令.
0, // 格式.
KSO::ksoEncodingAutoDetect, // 编码
VARIANT_TRUE, // 可见
VARIANT_FALSE, // 打开并修复
0, // DocumentDirection wdDocumentDirection LeftToRight
VARIANT_FALSE // 无编码对话框
);
}
catch(_com_error)
{
g_app->Quit(&vtMissing,&vtMissing,&vtMissing);
return ;
}
g_app->put_Visible(VARIANT_TRUE);
WPS::SelectionPtr p_sel = p_doc->Get_Selection();
WPS::FindPtr p_fid = p_sel->GetFind();
CString sField = "cde";
_variant_t FindText=(LPCTSTR)sField;
_variant_t ReplaceWith=vtMissing ;
_variant_t Forward=VARIANT_TRUE;
_variant_t Wrap=(_variant_t)(WPS::wpsFindContinue);
_variant_t Format=VARIANT_FALSE;
_variant_t MatchCase=VARIANT_FALSE;
_variant_t MatchWholeWord=VARIANT_FALSE;
_variant_t MatchWildcards=VARIANT_FALSE;
_variant_t MatchSoundsLike=VARIANT_FALSE;
_variant_t MatchAllWordForms=VARIANT_FALSE;
VARIANT_BOOL bExec = p_fid->Execute(
&FindText, &MatchCase, &MatchWholeWord, &MatchWildcards, &MatchSoundsLike,
&MatchAllWordForms, &Forward, &Wrap, &Format, &ReplaceWith,&vtMissing);
WPS::RangePtr lprage = p_sel->GetRange();
long ns = lprage->Start; //2
long ne = lprage->End; //5
CString str = lprage->GetText();
try
{
//lprage->Start = 6; //异常
//lprage->End = 1; //异常
lprage->SetRange(6,7); //正确
}
catch (_com_error& e)
{
CString ErrorStr;
ErrorStr.Format( "Code = %08lx\n\tCode meaning = %s\n\tSource = %s\n\tDescription = %s\n",
e.Error(), e.ErrorMessage(), (LPCSTR)(_bstr_t)e.Source(), (LPCSTR)(_bstr_t)(e.Description()));
}
long ns1 = lprage->Start;
long ne1 = lprage->End;
str = (CString)(LPCSTR)lprage->GetText();
WPS::RangePtr lprage2 = p_sel->GetRange();
long ns2 = lprage2->Start;
long ne2 = lprage2->End;
}