我在 Oracle 数据库的表中有不同的列名,我正在使用 VB 宏从 oracle 数据库中获取数据到 excel 并将具有不同列名的数据排序到不同的工作表
目前我为每张纸写了一个单独的代码,但我想循环它,这样代码会很简单。有 60 个协作名称,而且都是不同的名称,我想将它们分类到 60 个不同的工作表
因此,如果我循环它,我不需要编写相同的代码 60 次
当前代码:
cn.Open ( _
"User ID=USERID" & _
";Password=PASSWORD" & _
";Data Source=xx.xx.xx.xxx:xxxx/xxxx" & _
";Provider=OraOLEDB.Oracle")
rs.Open "select COLLABNAME,DATETIME,TOTALFLOWS from TABLE_NAME AND COLLABNAME like 'COLLAB_NAME1' ORDER BY DATETIME ASC", cn
With Sheet1
col = 0
'First Row: names of columns
Do While col < rs.Fields.Count
.Cells(1, col + 1) = rs.Fields(col).Name
col = col + 1
Loop
mtxData = Application.Transpose(rs.GetRows)
.Range("A2").Resize(UBound(mtxData, 1) - LBound(mtxData, 1) + 1, UBound(mtxData, 2) - LBound(mtxData, 2) + 1) = mtxData
End With
rs.Close
rs.Open "select COLLABNAME,DATETIME,TOTALFLOWS from TABLE_NAME AND COLLABNAME like 'COLLAB_NAME_2' ORDER BY DATETIME ASC", cn
With Sheet2
col = 0
'First Row: names of columns
Do While col < rs.Fields.Count
.Cells(1, col + 1) = rs.Fields(col).Name
col = col + 1
Loop
mtxData = Application.Transpose(rs.GetRows)
.Range("A2").Resize(UBound(mtxData, 1) - LBound(mtxData, 1) + 1, UBound(mtxData, 2) - LBound(mtxData, 2) + 1) = mtxData
End With
rs.Close
rs.Open "select COLLABNAME,DATETIME,TOTALFLOWS from TABLE_NAME AND COLLABNAME like 'COLLAB_NAME1_NAME2_3' ORDER BY DATETIME ASC", cn
With Sheet3
col = 0
'First Row: names of columns
Do While col < rs.Fields.Count
.Cells(1, col + 1) = rs.Fields(col).Name
col = col + 1
Loop
mtxData = Application.Transpose(rs.GetRows)
.Range("A2").Resize(UBound(mtxData, 1) - LBound(mtxData, 1) + 1, UBound(mtxData, 2) - LBound(mtxData, 2) + 1) = mtxData
End With
rs.Close
End Sub
新代码:
Sub Load_data()
Sheets("Sheet1").Select
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim col As Integer
Dim row As Integer
Dim Query As String
Dim mtxData As Variant
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open ( _
"User ID=USERID" & _
";Password=PASSWORD" & _
";Data Source=xx.xx.xx.xxx:xxxx/xxxxxx" & _
";Provider=OraOLEDB.Oracle")
'Creates an Array with all the Collabnames.
Dim arrayCOLLABNAME(59) As String
Dim idx As Integer
idx = 0
Sheets("COLLABNAME").Select
Range("A1").Select
Do While Not ActiveCell.Offset((idx), 0) = ""
arrayCOLLABNAME(idx) = ActiveCell.Offset(idx, 0).Value
idx = idx + 1
Loop
'The name of the First Sheet
Sheets("Sheet1").Select
'Loop for 60 Sheets
For i = 0 To 60
'adds the new Sheet
Sheets.Add
rs.Open "select COLLABNAME,DATETIME,TOTALFLOWS from TABLE_NAME AND COLLABNAME like '" & arrayCOLLABNAME(idx) & "' ORDER BY DATETIME ASC", cn
'use the new Sheet for inserting the Data
With ActiveSheet
col = 0
'First Row: names of columns
Do While col < rs.Fields.Count
.Cells(1, col + 1) = rs.Fields(col).Name
col = col + 1
Loop
mtxData = Application.Transpose(rs.GetRows)
.Range("A2").Resize(UBound(mtxData, 1) - LBound(mtxData, 1) + 1, UBound(mtxData, 2) - LBound(mtxData, 2) + 1) = mtxData
End With
rs.Close
Next i
End Sub