如何在execl 中加个查询按钮,结果直接显示在当前工作表!
如何在execl 中加个查询按钮,结果直接显示在当前工作表!
数据库通过DSN 连接!
[解决办法]
用VBA完成
SHEET1:
Private Sub CommandButton1_Click()
Call ReadData
End Sub
Module1:
Option Explicit
Private m_conn As New Connection
Public Function ReadData() As Long
Dim strSQL As String
Dim rst As New Recordset
Dim lngIndex As Long
If m_conn.State = adStateClosed Then
OpenConn
End If
strSQL = "select * from table1 "
rst.Open strSQL, m_conn, adOpenStatic, adLockReadOnly
lngIndex = 2
While Not rst.EOF
Sheet1.Cells(lngIndex, 1) = rst.Fields(0).Value
Sheet1.Cells(lngIndex, 2) = rst.Fields(1).Value
Sheet1.Cells(lngIndex, 3) = rst.Fields(2).Value
Sheet1.Cells(lngIndex, 4) = rst.Fields(3).Value
Sheet1.Cells(lngIndex, 5) = rst.Fields(4).Value
rst.MoveNext
lngIndex = lngIndex + 1
Wend
End Function
Public Function OpenConn() As Long
m_conn.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=SA;Password=123;Initial Catalog=TEST;Data Source=GAO-YANG "
m_conn.Open
End Function
[解决办法]
也可以在VBA里面引用的,菜单上的工具->引用,我的是office2003,不知道其他版本是不是这样。
[解决办法]
依次点击 "View---> Visual Basic(不好意思是英文版) "......
你也可以插入一个物件像艺术字,单击右键,然后点击 "Assign Macro(也就是宏) "
另外,如果你是将的数据是很规则的放在EXCEL中的话用.range( "A1 ").CopyFromRecordset 比较好