2016-02-24

VBA - Object creation example


' Object creation sample
Public Sub CreateCustomer(ByVal firstName As String, ByVal lastName As String, ByVal email As String)
    'Declare a Customer object
    Dim objNewCustomer As Customer
    'Create the new customer
    objNewCustomer.firstName = firstName
    objNewCustomer.lastName = lastName
    objNewCustomer.email = email
    'Add the new customer to the list
    objCustomers.Add (objNewCustomer)
    'Add the new customer to the ListBox control
    lstCustomers.Items.Add (objNewCustomer)
End Sub

EXCEL/VBA - Refresh sheet data and prepare for CSV export (remove headers)


Sub refreshAndPrepareForCSVExport()

    ' 1. Gather parameters
    Dim strPARAMETER_1 As String
        strPARAMETER_1 = Range("NAMED_RANGE_OR_CELL_REF").Value
   
    ' 2. Update the connection... customize if if necessary
    With ActiveWorkbook.Connections("CONNECTION_NAME").ODBCConnection
        .BackgroundQuery = False
        .CommandText = "exec DB.dbo.STORED_PROCEDURE_NAME " & strPARAMETER_1 & ", 'HARD_CODED_PARAMETER_2_EXAMPLE';"
        .RefreshOnFileOpen = False
        .SavePassword = False
        .SourceConnectionFile = ""
        .SourceDataFile = ""
        .ServerCredentialsMethod = xlCredentialsMethodIntegrated
        .AlwaysUseConnectionFile = False
    End With
   
    ' 3. Refresh the connection
    ActiveWorkbook.Connections("CONNECTION_NAME").Refresh
   
        ' Save!
        DoEvents
        ActiveWorkbook.Save
   
    ' 4. Remove headers
    Rows("1:4").Select
    Selection.Delete Shift:=xlUp

    ' 5. Save as CSV
    Dim strFileName As String
    strFileName = _
        CreateObject("WScript.Shell").specialfolders("Desktop") & _
        "\" & _
        strFrom & "FILE_NAME.csv"
    ActiveWorkbook.SaveAs _
        Filename:=strFileName _
        , FileFormat:=xlCSV _
        , CreateBackup:=False
       
    ' 6. Close
    ThisWorkbook.Close False
       
End Sub
nd Sub

EXCEL/VBA/TERADATA - Pull a scalar value from Teradata into an Excel cell


Option Explicit
Private con As ADODB.Connection
Private cst As String
Private rst As ADODB.Recordset
Private DBFunctionsMenuSetupFrequencyCount As Integer
Private DBConnectionFrequencyCount As Integer


' 1. Connection

    ' 1.1. Start
    Public Sub setDBConnection()

        ' Exit if the connection is already present
        If Not IsEmpty(DBConnectionFrequencyCount) _
            And DBConnectionFrequencyCount > 0 _
        Then
            'Exit Sub
        End If
       
        ' Open the connection
        Set con = New ADODB.Connection
        con.ConnectionTimeout = 3 'Seconds
        con.CursorLocation = adUseClient
        con.IsolationLevel = adXactReadUncommitted
        cst = _
            "Data Source=DB_ODBC_NAME; " & _
            "Database=DATABASE_NAME; " & _
            "Session Mode=TERA;" 'or ANSI (Teradata)
        con.Open cst
       
        ' Generic Recordset Declaration
        Set rst = New ADODB.Recordset
        rst.CursorLocation = adUseClient
        rst.CursorType = adOpenForwardOnly
        rst.LockType = adLockReadOnly
        rst.MaxRecords = gloMaxRecords
       
        ' Count the number of times a connection has been made
        DBConnectionFrequencyCount = DBConnectionFrequencyCount + 1
    End Sub
   
   
    ' 1.2. Terminate
    Public Sub getDBConnectionTerminated()
        Set con = Nothing
        DBConnectionFrequencyCount = 0
    End Sub



' 2.1. getCustomerName
Public Function getCustomerName( customerId As String) As String
   
    ' SQL
    Dim sql As String
    sql = _
        "SELECT max( clientName ) as Result " & _
        "FROM " & _
            "CLIENTS " & _
        "WHERE " & _
            "clientId='" & customerId & "' " & _
        ";"
       
    ' Open connection and recordset
    Call setDBConnection
    rst.Open sql, con
    'Debug.Print rst.ActiveConnection.ConnectionString   

    ' Use the recordset
    Do While Not rst.EOF
        getCustomerName = rst.Fields("Result")
        rst.MoveNext
    Loop

    ' Exit, cleanup
    rst.Close
    'getDBConnectionTerminated
    con.Close
    Exit Function
  
End Function

2016-02-23

EXCEL/VBA - Verify the existence of a sheet


' 1. getSheetExistence
Public Function getSheetExistence(sheetName As String) As Boolean
On Error GoTo err

    ' If no error, then it exists
    If ThisWorkbook.Sheets(sheetName).Name <> "" Then
    End If
    getSheetExistence = True
    Exit Function
   
err:
    getSheetExistence = False
    Exit Function
End Function

EXCEL/VBA - Get a column's letter


' getColumnLetter
Public Function getColumnLetter(columnNumber As Integer)
    getColumnLetter = _
        Left( _
            Cells(1, columnNumber).Address(1, 0) _
            , InStr( _
                1 _
                , Cells(1, columnNumber).Address(1, 0) _
                , "$" _
            ) - 1 _
        )
End Function

EXCEL/VBA - Write a record log into a sheet, appending at its bottom end


Public Function setLog( _
    SessionID As String _
    , functionName As String _
    , sql As String _
    , Optional userName As String _
) As Boolean

    ' Validate
    'Dim iris As New cIRIS
    If Not getSheetExistance("Log") Then
        setLog = False
        Exit Function
    End If

    ' Target Row
    Dim targetRow As Long
    targetRow = Cells(Rows.Count, 1).End(xlUp).Row + 1

    ' Log
    ThisWorkbook.Sheets("Log").Range("A1").Select
    Range("A" & CStr(targetRow)).Value = SessionID
    Range("B" & CStr(targetRow)).Value = Now()
    Range("C" & CStr(targetRow)).Value = sql
    Range("D" & CStr(targetRow)).Value = functionName
    Range("E" & CStr(targetRow)).Value = userName
    Range("F" & CStr(targetRow)).Formula = "=(B" & targetRow & "-B" & (targetRow - 1) & ")/0.0000115740741118013"
   
End Function