2014-10-17 48 views
0

我在我的Excel VBA中使用下面的连接字符串。但我需要以一种方式设置它,即从A $ 1 $等单元中选取数据库和服务器。所以我可以在需要时更改数据库的详细信息。在连接字符串中使用单元格引用

Function Connect(Server As String, _ 
       Database As String) As Boolean 

    Set CN = New ADODB.Connection 
    On Error Resume Next 

    With CN 
     ' Create connecting string 
     .ConnectionString = "Provider=SQLOLEDB.1;" & _ 
          "Integrated Security=SSPI;" & _ 
          "Server=" & Server & ";" & _ 
          "Database=" & Database & ";" 
     ' Open connection 
     .Open 
    End With 
    ' Check connection state 
    If CN.State = 0 Then 
     Connect = False 
    Else 
     Connect = True 
    End If 

End Function 

在此先感谢

回答

3

喜欢的东西:

Sub check_database_connectivity() 
    Dim server_name As String 
    Dim database_name As String 

    server_name = ActiveSheet.Range("A1").Value 
    database_name = ActiveSheet.Range("A2").Value 

    If Connect(server_name, database_name) = True Then 
     'do something 
    End If 
End Sub 
+0

感谢伯尼......我现在是否可以连... – 2014-10-20 15:27:12

+0

干杯,队友。快乐的编码。 – bernie 2014-10-20 16:06:21

相关问题