用户更新Excel时更新SQL查询

时间:2015-07-08 20:33:41

标签: mysql sql sql-server excel vba

我有一个excel文档,我想链接到SQL查询。在excel文档中,我有一个项目编号列表。每当项目编号被更改时,我希望sql查询查询项目编号列表并返回输出。基本上我希望excel表使用Item Number作为数据库项目编号的参数? excel项目编号每天更新。

1 个答案:

答案 0 :(得分:0)

请记住,这是您尝试执行的操作的模拟示例。由于不了解您的数据库或电子表格,我无法保证其中任何一项都能正常运行。至少,它需要你做一些调整才能使用它。

考虑到这一点,我已经对代码的各个部分进行了评论,以便让您知道那里发生了什么。具有***的部分是您可能想要更改的区域。包含###的部分是您要更改以便为您工作的区域。

此代码假设您在表单1的A列中有一个项目编号列表,每个项目编号只返回一个记录,并且项目编号列表中没有空白单元格。

Sub GrabItemInfo()
Dim objADO As New ADODB.Connection
Dim objRecSet As New ADODB.Recordset
Dim objCmd As New ADODB.Command
Dim strConn As String
Dim strSQL As String
Dim RowNum As Long
Dim errNum As Long

'open a connection to the database
'### change the properties for the connection to suit your needs
strConn = "DSN=DSNName; DBQ=Database; UID=Username; PWD=Password"
objADO.Open strConn
objCmd.ActiveConnection = objADO
objCmd.CommandType = adCmdText

'errNum is the row that the error log will start on
'***change errNum to change which row it starts on
errNum = 1
'***changeRowNum here to change which row to start on
RowNum = 1
'start the loop
Do Until ThisWorkbook.Sheets(1).Cells(RowNum, 1) = ""
    On Error Resume Next
    '### change the sql to whatever you need
    '*** change the cells section if you're not using the first column
    strSQL = "SELECT [field] FROM [table] WHERE ItemNum = " & ThisWorkbook.Sheets(1).Cells(RowNum, 1).Value
    objCmd.CommandText = strSQL
    Set objRecSet = objCmd.Execute
    'pastes results from query into the cell next to the item number
    '***change the cells section if you want to use a different column
    ThisWorkbook.Sheets(1).Cells(RowNum, 2).CopyFromRecordset objRecSet
    'clear out the recordset before the loops starts again
    Set objRecSet = Nothing
    'put the item number, error number, and error description on the second sheet of the work book
    '***change the sheet number to put it on another sheet if you're already using the second
    If Err > 0 Then
        ThisWorkbook.Sheets(2).Cells(errNum, 1).Value = ThisWorkbook.Sheets(1).Cells(RowNum, 1).Value
        ThisWorkbook.Sheets(2).Cells(errNum, 2).Value = Err.Number
        ThisWorkbook.Sheets(2).Cells(errNum, 3).Value = Err.Description
        On Error GoTo 0
    End If
    'raise the value for the row for the next iteration
    RowNum = RowNum + 1
Loop

'clear out the connection
Set objADO = Nothing
Set objRecSet = Nothing
Set objCmd = Nothing

End Sub

有关连接字符串的更多信息,建议http://www.connectionstrings.com 这是一个很好的资源,用于确定您需要什么样的连接字符串。连接字符串可能......很棘手......有时,这确实有帮助。

如果您需要任何SQL资源,我建议http://www.w3schools.com/sql 他们在那里有一个很好的介绍。过去,获得一本好的参考书,找一个导师,加入论坛(或像这样的Q& A网站)等。如果你查看这个网站上的SQL标签,有更多的信息,以及一些推荐的资源,如好。

祝你好运。