代码录入结束后,先在B1单元格中选择要显示的核算项目,然后点击右侧的按钮,即可得到该核算项目的资料。
以上就是从金蝶K3数据库中提取核算项目的方法,各位有什么想法可以在评论区中留言,
最后附上源代码:
Option Explicit
Private Sub CommandButton1_Click()
Dim ado As Object
Dim rst As Object
Dim str As String
Dim sql As String
Dim dbIP As String
Dim dbsa As String
Dim dbpwd As String
Dim dbname As String
'清屏
Range("3:" & Rows.Count).Clear
'如果没有选择核算项目,退出
If Range("B1") = "" Then Exit Sub
'如果有自动筛选,先取消自动筛选
If ActiveSheet.AutoFilterMode Then Range("A3").AutoFilter
'设置表头,根据核算项目类别不同,显示不同的标题
Select Case Range("B1")
Case "客户", "供应商"
Range("A3:G3") = Array("代码", "名称", "地址", "电话", "传真", "银行", "联系人")
Case "部门", "职员", "仓库"
Range("A3:B3") = Array("代码", "名称")
Case "物料"
Range("A3:C3") = Array("代码", "名称", "规格")
End Select
'设置数据库连接字符串
dbIP = "(local)" '安装数据库的电脑IP地址,(local)代表本机
dbsa = "sa" 'SQLServer数据库的登录用户名
dbpwd = "123456" 'SQLServer数据库的登录密码
dbname = "AIS20210318095953" '需要提取数据的金蝶数据库名
str = "Provider=SQLOLEDB.1;"
str = str & "Data Source=" & dbIP & ";"
str = str & "Persist Security Info=True;"
str = str & "User ID=" & dbsa & ";"
str = str & "Password=" & dbpwd & ";"
str = str & "Initial Catalog=" & dbname & ";"
'建立数据库连接
Set ado = CreateObject("ADODB.Connection")
ado.Open str
'从指定表头提取数据并返回到工作表,根据选择的核算项目类别显示不同的内容
Select Case Range("B1")
Case "客户"
sql = "select FNumber,FName,FAddress,FPhone,FFax,FBank,FContact from t_Organization "
Case "供应商"
sql = "select FNumber,FName,FAddress,FPhone,FFax,FBank,FContact from t_Supplier "
Case "部门"
sql = "select FNumber,FName from t_Department "
Case "职员"
sql = "select FNumber,FName from t_Emp "
Case "仓库"
sql = "select FNumber,FName from t_Stock "
Case "物料"
sql = "select FNumber,FName,FModel from t_ICItem "
End Select
sql = sql & "Order By FNumber"
Set rst = ado.Execute(sql)
If Not rst.EOF Then Range("A4").CopyFromRecordset rst
rst.Close
Set rst = Nothing
Set ado = Nothing
'提取数据后加上自动筛选
Range("A3").Resize(1, Range("A3").End(xlToRight).Column).AutoFilter
End Sub