一、什么是VBA
Visual Basic Application是一种自动化语言(过去称为“宏语言”),可以用它是常用的过程或进程自动化,可以创建自定义的解决方案。目前,主要用它来扩展Window office的功能。
要了解VBA,有两个简单的办法:
1,查看“EXCEL帮助(F1)" -> ”搜索“ -> ”开发人员参考“ -> ”VB语言“
2,查看宏录制
这类的”宏“指一系列EXCEL能够执行的名字保存的命令。
参考
EXCEL_VBA完全手册的第一节。或通过右击worksheet,查看源码的方式进入。同过宏录制,查看源代码,获知VBA的一些属性值和操作方法,如
左对齐(xlLeft):-4131
;居中(xlCenter):-4108
;右对齐(xlRight):-4152 ;
上对齐(xlTop):-4160
;居中(xlCenter):4108
;下对齐(xlBottom):-4107等等。
二、Qt是如何来操作Excel?
Qt操作Excel主要通过QAxObject + Excel VBA来实现。查看Qt的帮助文档:
The QAxObject class provides a QObject that wraps a COM object.
A QAxObject can be instantiated as an empty object, with the name of the COM object it should wrap, or with a pointer to the IUnknown that represents an existing COM object. If the COM object implements the IDispatch interface, the properties, methods and events of that object become available as Qt properties, slots and signals. The base class, QAxBase, provides an API to access the COM object directly through the IUnknown pointer.
QAxObject is a QObject and can be used as such, e.g. it can be organized in an object hierarchy, receive events and connect to signals and slots.
QAxObject also inherits most of its ActiveX-related functionality from QAxBase, notably dynamicCall() and querySubObject().
这段的大意就是:QAxObject是对COM对象的封装。COM Object的属性、方法和事件与Qt的属性、slot方法和信号对应。其中,最重要的两个函数是:
dynamicCall() 和 querySubObject()。
此外,可以查看“QAxbase”,它提供了COM type和Qt property的对照表,并提供了
dynamicCall() 和 querySubObject()函数以及
QObject::property() and QObject::setProperty()函数(
Note that it is faster to get and set properties using QObject::property() and QObject::setProperty())的说明。
函数
querySubObject()实现对象关联或对象转换(从COM Object转为Qt Object),如:
QAxObject * workBooks = excel.querySubObject("WorkBooks");
函数
dynamicCall()
实现跨QT到COM的函数调用,如:
workBooks->dynamicCall("Open(const QString&)", QString("D:/Development/Trunk09/test.xlsx"));
函数
property()
获取属性,函数
setProperty()设置属性。
三、示例代码
1,读Excel文件
新建一个“Qt console”应用程序,在“.pro文件”中添加(查看QAxObject即可知),QT += axcontainer,然后在main文件中添加如下代码:
#include
#include
#include
#include
// 使用
CoInitializeEx(NULL, COINIT_MULTITHREADED);
int main(int argc, char *argv[])
{