我在列中生成了一个SQL语句列表,我想从excel运行,在另一个表中输出结果。我正在使用Oracle SQL Developer来运行我的查询并且无法使连接正常工作。我的数据库本地托管,并且在我连接到的数据库的属性中,我看到:连接名称,用户名,密码,主机名,端口,SID。
我知道我需要采取的步骤是:
1)创建连接 2)运行我的查询(选择语句) 3)关闭连接(如果它仍然打开)
我使用它作为我的模板:
Sub GetData()
Dim Conn As New ADODB.Connection
Dim RS As New ADODB.Recordset
Dim Cmd As New ADODB.Command
Dim sqlText As String
Dim Row As Long
Dim Findex As Long
Dim Data As Worksheet
Dim X As Long
Set Data = Sheets("Results")
Data.Select
Cells.ClearContents
Conn.Open "PROVIDER=ORAOLEDB.ORACLE;DATA SOURCE=ORCL;USER ID=xxxx;PASSWORD=password"
Cmd.ActiveConnection = Conn
Cmd.CommandType = adCmdText
sqlText = "SELECT * FROM test"
Cmd.CommandText = sqlText
Set RS = Cmd.Execute
For X = 1 To RS.Fields.Count
Data.Cells(1, X) = RS.Fields(X - 1).Name
Next
If RS.RecordCount < Rows.Count Then
Data.Range("A2").CopyFromRecordset RS
Else
Do While Not RS.EOF
Row = Row + 1
For Findex = 0 To RS.Fields.Count - 1
If Row >= Rows.Count - 50 Then
Exit For
End If
Data.Cells(Row + 1, Findex + 1) = RS.Fields(Findex).Value
Next Findex
RS.MoveNext
Loop
End If
Cells.EntireColumn.AutoFit
End Sub
更新:弄清楚我的连接问题并更新了上面的代码......我现在要做的是循环遍历一个表单列C中的select语句列表。我希望能够遍历每一个并在D列中输出结果。如果Select返回为null或者失败我想返回值失败