Option Explicit
Global m_connection As ADODB.connection
Global fileNo As Integer
Sub getRegions()
Dim thisYear As String
Dim sheetName As String
Dim sql As String
Dim rs As Integer
sql = "select host_name,server_vendor,architecture,project,owner "
& _
"from servers where owner=test123 and architecture='64' "
sheetName = "Sheet 1"
OpenConnection
rs = selectData(sql, sheetName)
CloseConnection
End Sub
Public Sub OpenConnection()
Dim dbsource As String
Dim username As String
Dim password As String
Select Case Sheets("Home").DropDowns
("sg_database_dropdown").ListIndex
Case Else
dbsource = "MySQL connection information"
End Select
username = "myusername"
password = "mypassword"
Set m_connection = CreateObject("ADODB.Connection")
m_connection.CommandTimeout = 2000
m_connection.Open dbsource, username, password
End Sub
Public Sub CloseConnection()
m_connection.Close
End Sub
Public Sub doSql(sql As String)
Dim Command As Command
If 0 = fileNo Then
Set Command = CreateObject("ADODB.Command")
Set Command.ActiveConnection = m_connection
Command.CommandText = sql
Call Command.Execute
Set Command = Nothing
Else
Print #fileNo, sql & ";" & Chr(10)
End If
End Sub
'Function fixSingleQuotes(s As String) As String
' Dim oRegExp As RegExp
' Set oRegExp = New RegExp
' oRegExp.IgnoreCase = True
' oRegExp.Global = True
' oRegExp.Pattern = "'"
' fixSingleQuotes = oRegExp.Replace(s, "''")
'End Function
Public Function selectData(sql As String, sheetName As String) As
Integer
Dim count As Integer
Dim Command As ADODB.Command
Set Command = CreateObject("ADODB.Command")
Set Command.ActiveConnection = m_connection
Command.CommandTimeout = 2000
Command.CommandType = adCmdText
Command.CommandText = sql
Dim sheet As Worksheet
Set sheet = ThisWorkbook.Sheets(sheetName)
sheet.Visible = True
sheet.Cells.Clear
Dim rs As ADODB.Recordset
Set rs = Command.Execute
Dim field As ADODB.field
Dim fieldIndex As Integer
fieldIndex = 1
For Each field In rs.Fields
sheet.Cells(1, fieldIndex).Value = field.Name
fieldIndex = fieldIndex + 1
Next field
Dim colCount As Integer
colCount = rs.Fields.count
Dim rowIndex, index As Integer
rowIndex = 2
count = 0
While Not rs Is Nothing And Not rs.BOF And Not rs.EOF
For index = 1 To colCount
sheet.Cells(rowIndex, index).Value = rs(index - 1).Value
Next index
rowIndex = rowIndex + 1
count = count + 1
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
Set Command = Nothing
Sheets(sheetName).Select
Range("A1").Select
selectData = count
End Function