下面的代码是点击Button1后,新建一个Excel文档,并在指定的单元格上添加一个超链接。
void __fastcall TForm1::Button1Click(TObject *Sender) { Variant vHandleExcelApp, vHandleWorkbook, vHandleSheet, vHandleCell; AnsiString ansi,tmpStr; tmpStr = "file:///E:\aaa\zOut1\sss.txt"; //字符串中“\”要写成“\” //this->Edit1->Text = ansi; try{ vHandleExcelApp = Variant::CreateObject("Excel.Application"); } catch(...) { Application->MessageBox("无法启动Excel", "错误", MB_ICONSTOP|MB_OK); return; } vHandleExcelApp.OlePropertySet("Visible", true); vHandleExcelApp.OlePropertyGet("WorkBooks").OleFunction("Add",1); vHandleWorkbook = vHandleExcelApp.OlePropertyGet("ActiveWorkBook"); vHandleSheet = vHandleWorkbook.OlePropertyGet("ActiveSheet"); ansi = "research for"; vHandleSheet.OlePropertyGet("Cells", 2, 1).OlePropertySet("Value", ansi); vHandleCell = vHandleSheet.OlePropertyGet("Cells", 2, 1); vHandleSheet.OlePropertyGet("Hyperlinks").OleFunction("Add",vHandleCell,tmpStr,"the caption here"); }
相应的VBA代码是:
ActiveSheet.Hyperlinks.Add Anchor:=ActiveSheet.Cells(2,1), Address:= "E:\MyDoc\using_javadoc.doc", TextToDisplay:="some text here"
可见使用OlePropertyGet、OlePropertySet、OleFunction三个函数基本上可以实现从VBA到C++代码的转换。