连接到云上的SQL

时间:2018-03-13 12:33:15

标签: sql sql-server excel-vba cloud vba

我有一份excel报告,目前通过此报告将数据从我们的内部SQL服务器提取到Excel中。为了建立连接,我有一个下拉框,使用Workbook_Open()子填充服务器名称。一旦用户选择了服务器。启动下面的代码以返回所有可用数据库的列表供用户选择。

这在内部服务器上一直运行良好,并且是我多年来为许多报告复制的一段代码。然而,我们公司刚刚转移到托管/基于云的SQL服务器,IT已经给了我所有相关权限,我通过凭证管理器访问了服务器。

但是每次运行代码时都会出现以下错误:

[DBNETLIB] [ConnectionOpen(Connect())。] SQL Server不存在或访问被拒绝。

我知道这听起来很明显,但我让技术人员看着它,即使获得了许可,他们也会得到同样的错误。如果我跳到管理工作室,我可以访问服务器。它就在我试图通过Excel拉出来的时候?

任何想法/建议都会非常感激,因为我从未见过这个错误而且不知道该去哪里。

Private Sub CB_Server_Change()

With Application
    .Calculation = xlManual
    .EnableEvents = False
    .ScreenUpdating = False
End With

Dim stSQL As String, rst As ADODB.Recordset, k As Integer, vaData As Variant
Dim objConn As ADODB.Connection
Dim ConnectionString As String, sServer As String
ConnectionString = "Provider=sqloledb.1;data source=" & sServer & ";Initial catalog=master;Integrated Security = SSPI;Trusted_Connection=Yes;"
Set objConn = New ADODB.Connection

sServer = "[" & CB_Server & "]"

If sServer = "[Select Server]" Then

MsgBox "Please Select Server", vbExclamation, "Geo Server"

Exit Sub

End If

stSQL = "EXEC ('SELECT NAME " & _
                "FROM " & sServer & ".master.dbo.sysdatabases " & _
                "WHERE NAME LIKE ''%US%'' AND NAME LIKE ''%UK%'' " & _
                "ORDER BY NAME')"

With objConn
    .CursorLocation = adUseClient
    .Open ConnectionString
    '.Open "Provider=sqloledb.1;data source==" & sServer & ";Initial catalog=Master;Integrated Security = SSPI;"
    .CommandTimeout = 300
     'Instantiate the Recordsetobject and execute the SQL-state.
    Set rst = .Execute(stSQL)
End With


With rst
    Set .ActiveConnection = Nothing 'Disconnect the recordset.
    k = .Fields.Count
          'Populate the array with the whole recordset.
    vaData = .GetRows
End With

CB_EDM.List = Application.Transpose(vaData)

'Close the connection.
objConn.Close

'Release objects from memory.
Set rst = Nothing
Set objConn = Nothing

bClear = True

'Restore the settings.
With Application
    .Calculation = xlAutomatic
    .EnableEvents = True
    .ScreenUpdating = True
End With

End Sub

提前致谢

1 个答案:

答案 0 :(得分:0)

您的连接字符串在分配值之前尝试使用变量sServer。假设其余连接输入有效,请尝试使用

sServer = "[" & CB_Server & "]"
ConnectionString = "Provider=sqloledb.1;data source=" & sServer & ";Initial catalog=master;Integrated Security = SSPI;Trusted_Connection=Yes;"
Set objConn = New ADODB.Connection