Monday, November 28, 2016

Bubble Sort in Collection VBA

'Sorting Collection in VBA
    For l = 1 To mycoll1.Count - 1
           'MsgBox mycoll1(l)
            For m = l + 1 To mycoll1.Count
                       
            If (IsNumeric(Mid(mycoll1(l), 1, 2))) And (IsNumeric(Mid(mycoll1(m), 1, 2))) Then
                    If CInt(Mid(mycoll1(l), 1, 2)) > CInt(Mid(mycoll1(m), 1, 2)) Then
                     'store the lesser item
                         mycoll1temp = mycoll1(m)
                     'remove the lesser item
                         mycoll1.Remove m
                      're-add the lesser item before the
                    'greater Item
                         mycoll1.Add mycoll1temp, mycoll1temp, l
                     End If
            ElseIf (IsNumeric(Mid(mycoll1(l), 1, 2))) And (IsNumeric(Mid(mycoll1(m), 1, 1))) Then
                    If CInt(Mid(mycoll1(l), 1, 2)) > CInt(Mid(mycoll1(m), 1, 1)) Then
                     'store the lesser item
                         mycoll1temp = mycoll1(m)
                     'remove the lesser item
                         mycoll1.Remove m
                      're-add the lesser item before the
                    'greater Item
                         mycoll1.Add mycoll1temp, mycoll1temp, l
                     End If
            ElseIf (IsNumeric(Mid(mycoll1(l), 1, 1))) And (IsNumeric(Mid(mycoll1(m), 1, 2))) Then
                    If CInt(Mid(mycoll1(l), 1, 1)) > CInt(Mid(mycoll1(m), 1, 2)) Then
                     'store the lesser item
                         mycoll1temp = mycoll1(m)
                     'remove the lesser item
                         mycoll1.Remove m
                      're-add the lesser item before the
                    'greater Item
                         mycoll1.Add mycoll1temp, mycoll1temp, l
                        
                     End If
            ElseIf (IsNumeric(Mid(mycoll1(l), 1, 1))) And (IsNumeric(Mid(mycoll1(m), 1, 1))) Then
                    If CInt(Mid(mycoll1(l), 1, 1)) > CInt(Mid(mycoll1(m), 1, 1)) Then
                     'store the lesser item
                         mycoll1temp = mycoll1(m)
                     'remove the lesser item
                         mycoll1.Remove m
                      're-add the lesser item before the
                    'greater Item
                         mycoll1.Add mycoll1temp, mycoll1temp, l
                        
                     End If
           
            End If
            Next
           
    Next

Sunday, November 13, 2016

Friday, November 11, 2016

MOD Function

http://www.get-digital-help.com/2014/06/03/learn-how-the-mod-function-works/

Moving Average Chart

http://www.get-digital-help.com/2015/11/03/follow-stock-market-trends-moving-average/

Tuesday, November 8, 2016

Updating Data Using Cursor in VBA

Option Private Module
Option Explicit
Dim conn As ADODB.Connection, dateval As String, day As String, month As String, Yr As String
Dim empCode As String
Dim rst As ADODB.Recordset, querystring, i As Integer, rowcount As Long

Sub updateempDetailsForOracle()
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
dateval = ThisWorkbook.Sheets(1).Range("A1")
empCode = ThisWorkbook.Sheets(1).Range("A2")
If InStr(Mid(dateval, 1, 2), "/") > 0 Then
        day = Mid(dateval, 1, 1)
        month = Mid(dateval, 3, 1)
        Yr = Mid(dateval, 5, 4)
Else
        day = Mid(dateval, 1, 2)
        month = Mid(dateval, 4, 2)
        Yr = Mid(dateval, 7, 4)

End If

querystring = "update empDetails set empDOJ=" & Chr(39) & Yr & "-" & month & "-" & day & Chr(39) & " where empCode=" & empCode
i = 1
rowcount = ThisWorkbook.Sheets(1).Range("B" & Rows.Count).End(xlUp).Row
If (rowcount > 1) Then
        ThisWorkbook.Sheets(1).Range("A2:B" & rowcount).ClearContents
End If
    conn.ConnectionString = "Data Source=empDetails;Initial Catalog=dbMentorMenteedetails;uid="*";pwd="*"
    conn.CursorLocation = adUseServer
    conn.Open
    rst.Open querystring, conn, adOpenDynamic
       
        conn.Close
        Set rst = Nothing
        Set conn = Nothing
End Sub

Check Directory Exists If Not Create

Dim pathname As String, tripid As String, respCreate
Sub ChecknCreateDirectory()
tripid = "12"
pathname = "C:\Users\" & Environ("username") & "\Google Drive\" & tripid
   If (Len(Dir(pathname, vbDirectory)) = 0) Then
         rspCreate = MsgBox("Directory doesn't exist, do you wish to create it?", vbYesNo)
            If (rspCreate = vbYes) Then
                MkDir "C:\Users\" & Environ("username") & "\Google Drive\" & tripid
            End If
    End If
End Sub

Monday, November 7, 2016

Create Pivot Table Using CTE

http://sqlmag.com/t-sql/create-pivoted-tables-3-steps

CTE

Extracting Data using Cursor in VBA

Option Private Module
Option Explicit
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset, querystring, i As Integer, rowcount As Long
'get employeelis for Oracle Domain
Sub getempDetailsForOracle()
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
querystring = "Select tbemp.empCode,tbemp.empName from empDetails tbemp join tbldomainList tbdom on " _
& "tbemp.empDomainId=tbdom.domainId  where tbdom.domainId=8"
i = 1
rowcount = ThisWorkbook.Sheets(1).Range("B" & Rows.Count).End(xlUp).Row
If (rowcount > 1) Then
        ThisWorkbook.Sheets(1).Range("A2:B" & rowcount).ClearContents
End If
    conn.ConnectionString = "Data Source=empDetails;Initial Catalog=*;uid=*;pwd=*"
    conn.CursorLocation = adUseClient
    conn.Open
    rst.Open querystring, conn, adOpenStatic
        Do While Not rst.EOF
        i = i + 1
             ThisWorkbook.Sheets(1).Range("A" & i) = rst.Fields(0).Value
             ThisWorkbook.Sheets(1).Range("B" & i) = rst.Fields(1).Value
                rst.MoveNext
        Loop
        rst.Close
        conn.Close
        Set rst = Nothing
        Set conn = Nothing
End Sub

Setting SQL Server 2008 Authentication New Login

Create a Login for SQL Server 2008

get ServerName in SQL

SELECT @@SERVERNAME;

Saturday, November 5, 2016

Create Custom Events using Withevents in VBA

WithEvents specifies that one or more declared member variables refer to an instance of a'
class that can raise events. WithEvents connects the event system to the  variable and
lets you utilize the events of the object.

In this example; we have raised cellSelect event. On selection of value in "A1"; we can
get cell name, cell address, colorindex and cell content in column B,C,D,E.

Steps:
 1.Declare a variable with  WithEvents and classname in Sheet where we need to raise
events.

 2.Write attributes and methods in a class, There are three attributes, for selecting
range, cell name, &set color and one method for setting color in selected range.

3.Declare 3 variables for three attributes for selected range, color and name.

4.Declare an event cellSelect.

5.RaiseEvent inside set property for selected Range.

6.Write a method named methodColor for assigning colorindex to a selected cell.


              Dim rngVar As Range
              Dim intColor As Integer
              Dim strName As String
              Public Event cellSelect(cell As Range)
   Public Property Set selectedRng(objVar As Range)
            Set rngVar = objVar
            RaiseEvent cellSelect(rngVar)
   End Property
   Public Property Get selectedRng() As Range
          Set selectedRng = rngVar
   End Property

  Public Property Let Name(objName As String)
         strName = objName
  End Property
  Public Property Get Name() As String
         Name = strName
  End Property

  Public Property Let Color(objColor As Integer)
        intColor = objColor
  End Property
  Public Property Get Color() As Integer
         Color = intColor
  End Property
  Sub methodColor()
        selectedRng.Interior.ColorIndex = Color
  End Sub


7.Now write an event procedure rng_cellSelect

8.Now assign  selected Range under Private Sub
  Worksheet_SelectionChange(ByVal Target As Range)




Private WithEvents rng As clsWithEvents
Dim i As Integer
Private Sub rng_cellSelect(cell As Range)
    rng.Color = 24
    If (rng.Color < 1) And (rng.Color > 56) Then
            MsgBox "Error! please enter a color index between 1 and 56"
    End If
        rng.Name = "First Cell"
        rng.methodColor
        rng.selectedRng.Select
        i = rng.Color
        Selection.Offset(0, 1).Value = "Name: " & rng.Name
        Selection.Offset(0, 2).Value = "Address:  " & Selection.Address
        Selection.Offset(0, 3).Value = "Interior color Index:  " & i
        Selection.Offset(0, 4).Value = "Cell Content  " & Selection.Value
       
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        Set rng = New clsWithEvents
       
            If (Target.Address = Range("A1").Address) Then
                Set rng.selectedRng = Target
           
           
            End If
End Sub
Download File

Sunday, October 23, 2016

Extract Data from MS Access 2010 to Excel using ADODB Connection

Option Explicit
Dim conn As ADODB.Connection, i As Integer
Dim rst As ADODB.Recordset, querystring As String
Sub accesData()
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
i = 1
querystring = "Select [Order Id], sum(([Unit Price]*Quantity))  as Sales  from [Order Details] group  by [Order Id]"
conn.ConnectionString = "Provider=Microsoft.Access.OLEDB.10.0;Persist Security Info=False;Data Source=somu"
conn.Open
conn.CursorLocation = adUseClient
rst.Open querystring, conn, adOpenStatic
    Do While Not rst.EOF
        ThisWorkbook.Sheets(1).Range("A" & (i + 1)) = rst.Fields(0).Value
        ThisWorkbook.Sheets(1).Range("B" & (i + 1)) = rst.Fields(1).Value
        rst.MoveNext
        i = i + 1
    Loop
rst.Close
conn.Close
Set rst = Nothing
Set conn = Nothing
End Sub


Download Excel

Sample Database


Thursday, October 20, 2016

Create and Populate ListBox from MSSQL Database

Set conn = New ADODB.Connection
    Set rst = New ADODB.Recordset
   
    conn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=.;Initial Catalog=CourseMasterDB;"
    conn.Open
    querystring = "Select GeoName from MST_Geo"
    i = 0
    k = 3
   
           
            rst.Open querystring, conn, adOpenStatic
            ReDim geoArray(rst.RecordCount)
            Do While Not rst.EOF
            geoArray(i) = rst.Fields(0).Value
            rst.MoveNext
            i = i + 1
            Loop
   
            rst.Close
            conn.Close
            Set rst = Nothing
            Set conn = Nothing
           For k = 3 To ThisWorkbook.Sheets.Count
                            Set lookuprng = ThisWorkbook.Sheets(k).Columns("J:J").Find("Select GEO", LookIn:=xlValues, lookat:=xlWhole)
                            If (Not lookuprng Is Nothing) Then
                             ThisWorkbook.Sheets(k).Range(lookuprng.Address).ClearContents
                             ThisWorkbook.Sheets(k).Range(lookuprng.Offset(0, 1).Address).Validation.Delete
                            End If
                            rowcount = ThisWorkbook.Sheets(k).Range("J" & Rows.Count).End(xlUp).Row
                            ThisWorkbook.Sheets(k).Range("J" & (rowcount + 15)) = "Select GEO"
                            ThisWorkbook.Sheets(k).Range("J" & (rowcount + 15)).FontSize = 15
                            ThisWorkbook.Sheets(k).Range("J" & (rowcount + 15)).Interior.ColorIndex = 24
                         With ThisWorkbook.Sheets(k).Range("K" & (rowcount + 15)).Validation
                             .Delete
                             .Add Type:=xlValidateList, Formula1:=Join(geoArray, ",")
                             .InCellDropdown = True
                             .InputTitle = ""
                             .ErrorTitle = ""
                             .InputMessage = ""
                             .ErrorMessage = ""
                             .ShowInput = True
                             .ShowError = True
                        End With

Add Form Control CheckBox in VBA

objrng.Offset(k, 0) = rst.Fields(0).Value
                'add check box
                ThisWorkbook.Sheets(shtcnt).CheckBoxes.Add(Left:=objrng.Offset(k, 1).Left, Top:=objrng.Offset(k, 1).Top, Width:=objrng.Offset(k, 1).Width, Height:=objrng.Offset(k, 1).Height).Select
                ThisWorkbook.Sheets(shtcnt).Range(objrng.Offset(k, 1).Address).NumberFormat = ";;;"
                With Selection
               
                    .Caption = ""
                    .Name = ""
               
                    .LinkedCell = objrng.Offset(k, 1).Address
                End With

Wednesday, October 19, 2016

Using ShellExecute to open an .exe File

Public Declare Function ShellExecute _
    Lib "shell32.dll" _
        Alias "ShellExecuteA" ( _
            ByVal Hwnd As Long, _
            ByVal lpOperation As String, _
            ByVal lpFile As String, _
            ByVal lpParameters As String, _
            ByVal lpDirectory As String, _
            ByVal nShowCmd As Long) _
As Long
Sub my_Procedure()
pathname = "C:\Program Files (x86)\TechSmith\Camtasia Studio 8\CamRecorder.exe"


'ThisWorkbook.Windows(1).WindowState = xlMinimized
procId = ShellExecute(0, "Open", pathname, vbNullString, "C:\", SW_SHOWNORMAL)
Application.Wait (Now + TimeValue("00:00:03"))
'AppActivate procId
Application.SendKeys ("{F9}"), True


end Sub

Wednesday, October 12, 2016

Select Query with Case

Select t3.LocationName, t1.CourseSDate,t1.CourseEDate,
CASE WHEN GI.CorporateId = 0 THEN GI.CompanyName ELSE CO.CORPORATENAME END AS ComapyName , ' ' as Venue from TRAN_SCINTERESTEDCOURSES t1
INNER JOIN TRAN_SCGENERALINFO GI ON T1.StudnetCardId = GI.StudnetCardId
 left JOIN MST_LOCATION t3 on t3.LocationId=t1.LocationId
 LEFT JOIN MST_CORPORATEDETAIL CO ON CO.CORPORATEID = GI.CorporateId where T1.StudnetCardId=4127

Wednesday, September 21, 2016

Populating ComboBox from SQl ResultSet

querystring = "Select AccomodationName from MST_ONSITEACCOMMODATION where CityName=" & Chr(39) & cityname & Chr(39)
                    conn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=.;Initial Catalog=Test;"
                    conn.Open
                    rst.Open querystring, conn, adOpenStatic
                    With ComboBox7
                                .Clear
                                    Do While Not rst.EOF
                                       .AddItem rst![AccomodationName]
                                                   
                                        rst.MoveNext
                                    Loop
                    End With
                                       
                    rst.Close
                    conn.Close
                    querystring = vbNullString
                    Set rst = Nothing
                    Set conn = Nothing

Sunday, September 11, 2016

Extract Data Using Select Query in VBA

Option Explicit

Dim conn As New ADODB.Connection, querystring As String, blockname As String, hadoopblockrowcount As Long
Dim rst As New ADODB.Recordset

Sub extractData()
blockname = Application.InputBox("Please Mention Block Name to be Created")
querystring = "Select t1.Cid,t1.CName,t1.PSName,t1.StDuration,t2.CourseExamId from MST_COURSE t1"
querystring = querystring & " join LNK_COURSE_EXAM t2 on t1.CId=t2.courseid"
querystring = querystring & " where t1.CId in(Select distinct CourseId from Lnk_COURSE_VENDOR where VendorId=32)and PSName is not null"
querystring = querystring & " Union Select t1.Cid, t1.CName,t1.PSName,t1.StDuration,null from MST_COURSE t1"
querystring = querystring & " where t1.CId in(Select distinct CourseId from Lnk_COURSE_VENDOR where VendorId=32)and PSName is not null;"

hadoopblockrowcount = 3
Application.ScreenUpdating = False
    conn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=.;Initial Catalog=CourseMasterDB;"
    conn.Open
    rst.Open querystring, conn, adOpenStatic
    Do While Not rst.EOF
    hadoopblockrowcount = hadoopblockrowcount + 1
    ThisWorkbook.Sheets(1).Range("A" & (hadoopblockrowcount)) = rst.Fields(0).Value
    ThisWorkbook.Sheets(1).Range("B" & (hadoopblockrowcount)) = rst.Fields(1).Value
    ThisWorkbook.Sheets(1).Range("C" & (hadoopblockrowcount)) = rst.Fields(2).Value
                If (rst.Fields(4).Value <> vbNullString) Then
                        ThisWorkbook.Sheets(1).Range("E" & (hadoopblockrowcount)) = "Y"
                Else
                        ThisWorkbook.Sheets(1).Range("E" & (hadoopblockrowcount)) = "N"
                End If
    ThisWorkbook.Sheets(1).Range("G" & (hadoopblockrowcount)) = rst.Fields(3).Value
        rst.MoveNext
    Loop
   
    rst.Close
    conn.Close
    Set rst = Nothing
    Set conn = Nothing
   
End Sub