最近车间制造部有需求,需要通过excel填写的ID获取数据库中的某个取值。研究了一下VBA,简要记录一下代码,仅供参考。
Function GETPMAX(SID As String) As String
Dim result As String
'链接数据库
Set Cnn = CreateObject("ADODB.Connection")
Set rt = CreateObject("ADODB.Recordset")
Cnn.ConnectionString = "Provider = SQLOLEDB;User ID= ;password=;Data Source=;Initial Catalog = "
Cnn.Open
Sql = "SELECT TOP 1 Pmax FROM dbo where ID='" & SID & "' order by hDateTime desc"
'获取记录集
Set rt = Cnn.Execute(Sql)
'根据字段获取值
result = CStr(rt("Pmax"))
GETPMAX = result
'关闭记录集
rt.Close
'关闭数据库链接,释放资源
Cnn.Close
End Function
来源:oschina
链接:https://my.oschina.net/u/4277043/blog/3555215