VB是常用的应用软件开发工具之一,由于VB的报表功能有限,而且一但报表格式发生变化,就得相应修改程序,给应用软件的维护工作
带来极大的不便。因此有很多程序员现在已经充分利用EXECL的强大报表功来实现报表功能。但由于VB与EXCEL由于分别属于不同的应用系统,
如何把它们有机地结合在一起,是一个值得我们研究的课题。
VB连接SQL Server的是这么写的:
set conn = CreateObject("ADODB.Connection")
conn_str = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=jgb_center;Data Source=IBMWEB"
conn.ConnectionString = conn_str
连接Excel数据库的连接字符串的写法1
Set DB = OpenDatabase(App.Path + "\" + "tG4.xls", False, False, "excel 5.0; hdr=no;")
Set RST(1) = DB.OpenRecordset("sheet1$")
Set RST(2) = DB.OpenRecordset("sheet2$")
Set RST(3) = DB.OpenRecordset("sheet3$")
连接Excel数据库的连接字符串的写法3
Dim adoConnection As New ADODB.Connection
Dim adoRecordset As New ADODB.Recordset
'OLE DB + ODBC Driver 方式:
'adoConnection.Open "Data Provider=MSDASQL.1;driver=Microsoft Excel Driver (*.xls);DBQ=e:\temp\book2.xls"
'Microsoft.Jet.OLEDB.4.0 方式,(建议)
adoConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=e:\temp\book2.xls;Extended Properties='Excel 8.0;HDR=Yes'"
adoRecordset.Open "select * from [sheet1$]", adoConnection, adOpenKeyset, adLockOptimistic
Debug.Print adoRecordset.GetString
Debug.Print adoRecordset.RecordCount
Dim i As Integer
Do Until adoRecordset.EOF
For i = 0 To adoRecordset.Fields.Count - 1
Debug.Print adoRecordset.Fields.Item(0).Name
Debug.Print adoRecordset.Fields.Item(0).Value
Next i
adoRecordset.MoveNext
Loop
'注: OLE DB + ODBC Driver 方式不支持以下语句,但 Microsoft.Jet.OLEDB.4.0 方式支持!
adoConnection.Execute "insert into [sheet1$](F1) values(3)"
adoRecordset.AddNew Array("f1", "f2", "f3", "f4"), Array(1, 2, 3, 4)