动态读取数据库信息以连接到数据库

时间:2015-11-24 17:11:37

标签: excel oracle vba excel-vba odbc

如果我在Excel中使用VBA从服务器导入数据,我写了以下内容:

Sub ImportData(message_string, location, table_name, env_name)
If env_name = "Name" Then
    connstring = "OLEDB;Provider=MSDAORA.1;User ID=myID1;password= MyPass1;Data Source=server1"
Else
    connstring = "OLEDB;Provider=MSDAORA.1;User ID=myID2;password= MYPass2;Data Source=Server2"
End If

With ActiveSheet.QueryTables.Add(Connection:=connstring, _
        Destination:=Range(location), Sql:=message_string)
    .RefreshStyle = xlOverwriteCells
    .Refresh
    .Name = table_name


End With
End Sub

如何阅读数据myUserNamemyPassserver1server2 在Excel表格中?

例如,将此信息放在单元格A1,A2和A3中。

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,您要做的就是使用连接字符串中工作表中的数据 - 您可以像创建任何其他字符串一样执行此操作。

它看起来如下:

Sub ImportData(message_string, location, table_name, env_name)

Dim connstring As String

Dim myUserName As String
Dim myPass As String
Dim server1 As String
Dim server2 As String

    myUserName = Sheets(1).Range("A1").Value
    myPass = Sheets(1).Range("A2").Value
    server1 = Sheets(1).Range("A3").Value
    server2 = Sheets(1).Range("A4").Value

    connstring = "OLEDB;Provider=MSDAORA.1;User ID=" & myUserName & ";password=" & myPass & ";Data Source="

    If env_name = "Name" Then
        connstring = connstring & server1
    Else
        connstring = connstring & server2
    End If

    With ActiveSheet.QueryTables.Add(Connection:=connstring, _
            Destination:=Range(location), Sql:=message_string)
        .RefreshStyle = xlOverwriteCells
        .Refresh
        .Name = table_name
    End With

End Sub

我更新了代码,使其尽可能轻松更新 - 希望一切都有意义。