Tuesday, November 24, 2015

Select Query in For Loop using VBA

Dim conn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim rowcount As Long, emprng As Range
Dim mycoll As Collection, i As Integer
Dim myArray(), rowcounter As Integer, counter As Integer
Sub updateclaimedtrainingDays()
rowcount = ThisWorkbook.Sheets(1).Range("D" & Rows.Count).End(xlUp).Row
Set emprng = ThisWorkbook.Sheets(1).Range("D2:D" & rowcount)
Set mycoll = New Collection
On Error Resume Next
'startdate = CDate("10/27/2015")
'endDate = CDate("10/28/2015")
conn.ConnectionString = "Data Source=TADA;Initial Catalog=Firdb;uid=kshrNew;pwd=A343jNMS;"
conn.Open
For Each cell In emprng
    mycoll.Add cell, CStr(cell)
Next
counter = 0
For i = 1 To mycoll.Count
        Set rst = conn.Execute("Select t2.DaysQty from tblTADATransDetail t2 where t2.TAId IN( Select t1.TAId  from tblTADATransMaster  t1 where (t1.CreatedDate >= '" & startdate & "' and t1.CreatedDate <='" & endDate & "') And t1.EmpId='" & mycoll(i) & "')and t2.NameOfExpenditure='1. Training Incentives'")
        If Not rst.EOF Then
            'cell.Offset(0, 16).CopyFromRecordset rst.Fields(4).Value
            myArray = rst.GetRows()
            rowcounter = UBound(myArray, 2)
            For j = 0 To rowcounter
            counter = counter + 1
           
                ThisWorkbook.Sheets(1).Range("T" & (1 + counter)) = myArray(0, j)
            Next
        Else
        counter = counter + 1
            ThisWorkbook.Sheets(1).Range("T" & (1 + counter)) = 0
        End If
Next
 rst.Close
Set rst = Nothing
Set conn = Nothing

End Sub

Wednesday, November 18, 2015

Add ValidationList in VBA

ThisWorkbook.Sheets(1).Range("B6").Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Formula1:="=" & validationrng.Address

Thursday, October 8, 2015

Extracting Excel Cell value with Multple Lines

'extracting cell value with multiple lines
        If (InStr(clientname, Chr(10)) > 0) Then
            tempArray = Split(clientname, Chr(10))
            clientname = tempArray(0)
        End If

Thursday, September 17, 2015

Using adOpenStatic in Databse Connectivity(VBA)

Dim conn As New ADODB.Connection
Dim rst As New ADODB.Recordset, rowcount As Long
Dim sqlqyerystr As String, coulumncounter As Long, rowcounter As Long
Sub updaterecord()
'On Error Resume Next
Application.ScreenUpdating = False
rowcount = ThisWorkbook.Sheets(1).Range("A" & Rows.Count).End(xlUp).Row
ThisWorkbook.Sheets(1).Range("A2:S" & rowcount).ClearContents
conn.ConnectionString = "Data Source=TADA;Initial Catalog=Firdb;uid=kshr;pwd=A343jNMS;"
conn.Open
sqlqyerystr = "Select * from tblnewjoineeemployeedetail ;"

rst.Open sqlqyerystr, conn, adOpenStatic
Dim myArray()
myArray = rst.GetRows()
MsgBox "updating File for New Employee.........."
coulumncounter = UBound(myArray, 1)
rowcounter = UBound(myArray, 2)
For j = 0 To rowcounter
    For i = 0 To coulumncounter
   
        ThisWorkbook.Sheets(1).Range("A1").Offset(0, i).Value = rst.Fields(i).Name
        ThisWorkbook.Sheets(1).Range("A1").Offset(j + 1, i).Value = myArray(i, j)
       
    Next
Next
rst.Close
conn.Close
rowcount = ThisWorkbook.Sheets(1).Range("A" & Rows.Count).End(xlUp).Row
ThisWorkbook.Sheets(1).Range("A1:AM1").AutoFilter Field:=39, Criteria1:="<" & Format(Date, "m/d/yyyy")
ThisWorkbook.Sheets(1).Range("AM2:AM" & rowcount).SpecialCells(xlCellTypeVisible).EntireRow.Delete
ThisWorkbook.Sheets(1).AutoFilterMode = False
Set rst = Nothing
Set conn = Nothing
End Sub

Thursday, September 3, 2015

Autofilter Automation inbetween two Dates

Dim myArray(3) As String, lookuprng As Range
Public rowcount As Long, wb As Workbook
Public sheetname As String, newrowcount As Long, datarng As Range, tempval As Integer
Private Sub CommandButton1_Click()
''On Error Resume Next
tempval = 0
    For j = 0 To 3
   
    sheetname = Format(CDate(TextBox1.Value), "mmm") & "'" & Format(CDate(TextBox1.Value), "yy")
   
    rowcount = ThisWorkbook.Sheets(sheetname).Range("B" & Rows.Count).End(xlUp).Row
    Set lookuprng = ThisWorkbook.Sheets(sheetname).Range("A:A").Find(myArray(j), LookIn:=xlValues)
   
        If lookuprng Is Nothing Then
            ThisWorkbook.Sheets(sheetname).Range("A" & rowcount + 3) = myArray(j)
            ThisWorkbook.Sheets(sheetname).Range("B" & rowcount + 3) = TextBox1.Value & "-" & TextBox2.Value
            ThisWorkbook.Sheets(sheetname).Range("A" & (rowcount + 3) & ":B" & (rowcount + 3)).Font.Bold = True
        Exit For
        End If
    Next
    Set wb = Workbooks.Open(ThisWorkbook.Path & "\Onsite Report.xlsx")
    newrowcount = wb.Sheets(sheetname).Range("B" & Rows.Count).End(xlUp).Row
    i = 0
    wb.Sheets(sheetname).AutoFilterMode = False
    wb.Sheets(sheetname).Range("A1:T1").AutoFilter field:=3, Criteria1:=">=" & TextBox1.Value, Operator:=xlAnd, Criteria2:="<=" & TextBox2.Value
   
    Set datarng = wb.Sheets(sheetname).Range("B4:B" & newrowcount).SpecialCells(xlCellTypeVisible)
    For Each cell In datarng
        i = i + 1
        ThisWorkbook.Sheets(sheetname).Range("B" & (rowcount + 5 + i)) = cell
        ThisWorkbook.Sheets(sheetname).Range("C" & (rowcount + 5 + i)) = cell.Offset(0, 7)
        ThisWorkbook.Sheets(sheetname).Range("D" & (rowcount + 5 + i)) = cell.Offset(0, 10)
        ThisWorkbook.Sheets(sheetname).Range("E" & (rowcount + 5 + i)) = cell.Offset(0, 15)
        ThisWorkbook.Sheets(sheetname).Range("F" & (rowcount + 5 + i)) = cell.Offset(0, 6)
        ThisWorkbook.Sheets(sheetname).Range("G" & (rowcount + 5 + i)) = cell.Offset(0, 4)
         tempval = tempval + CInt(ThisWorkbook.Sheets(sheetname).Range("G" & (rowcount + 5 + i)))
    Next
    ThisWorkbook.Sheets(sheetname).Range("G" & (rowcount + 6 + i)) = tempval
    With ThisWorkbook.Sheets(sheetname).Range("B" & (rowcount + 6) & ":G" & (rowcount + 5 + i)).Borders(xlEdgeRight)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With ThisWorkbook.Sheets(sheetname).Range("B" & (rowcount + 6) & ":G" & (rowcount + 5 + i)).Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With ThisWorkbook.Sheets(sheetname).Range("B" & (rowcount + 6) & ":G" & (rowcount + 5 + i)).Borders(xlEdgeLeft)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With ThisWorkbook.Sheets(sheetname).Range("B" & (rowcount + 6) & ":G" & (rowcount + 5 + i)).Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With ThisWorkbook.Sheets(sheetname).Range("B" & (rowcount + 6) & ":G" & (rowcount + 5 + i)).Borders(xlInsideVertical)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With ThisWorkbook.Sheets(sheetname).Range("B" & (rowcount + 6) & ":G" & (rowcount + 5 + i)).Borders(xlInsideHorizontal)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    Application.DisplayAlerts = False
    wb.Close
    Unload Me
End Sub
Private Sub UserForm_Initialize()
On Error Resume Next
'Application.ScreenUpdating = False
TextBox1.Value = Format(Date, "d-mmm-yy")
TextBox2.Value = Format(Date, "d-mmm-yy")

myArray(0) = "Week 1"
myArray(1) = "Week 2"
myArray(2) = "Week 3"
myArray(3) = "Week 4"

End Sub

Download File

Tuesday, August 4, 2015

Adding Controls Dynamically in User Form

Private Sub ComboBox1_Change()
Dim searchval As String, thelbl As Object, thelbl1 As Object, txtbox As Object
Application.ScreenUpdating = False
Application.EnableEvents = False
On Error Resume Next
ThisWorkbook.Sheets(2).Range("B2") = ComboBox1.Value
For Each cont In Me.Controls
    Me.Controls.Remove cont.Name
Next
Application.Calculation = xlCalculationAutomatic
If (Application.WorksheetFunction.CountIf(ThisWorkbook.Sheets(2).Range("E:E"), ">0") + 1) > 2 Then
    Set myrng1 = ThisWorkbook.Sheets(2).Range("E2:E" & Application.WorksheetFunction.CountIf(ThisWorkbook.Sheets(2).Range("E:E"), ">0") + 1)
Else
    Set myrng1 = ThisWorkbook.Sheets(2).Range("E2:E3")
End If
ComboBox1.List = myrng1.Value
cellrow = CLng(Application.WorksheetFunction.Match(CInt(ComboBox1.Value), ThisWorkbook.Sheets(1).Range("F:F"), 0))
Set lookupadd = ThisWorkbook.Sheets(1).Range("F3:F" & ThisWorkbook.Sheets(1).Cells(Rows.Count, 6).End(xlUp).Row).Find(Application.WorksheetFunction.Trim(ComboBox1.Value), LookIn:=xlValues)

    Set lblName = Existingemp.Controls.Add("Forms.Label.1", "Name", True)
    Set lblNameval = Existingemp.Controls.Add("Forms.Label.1", "Name", True)
    Set lblStatus = Existingemp.Controls.Add("Forms.Label.1", "Status", True)
    Set lblResignationDate = Existingemp.Controls.Add("Forms.Label.1", "ResignDate", True)
    Set txtBoxResignationDate = Existingemp.Controls.Add("Forms.TextBox.1", "ResignDate", True)
    Set lblNoticeDuration = Existingemp.Controls.Add("Forms.Label.1", "NoticeDuration", True)
    Set txtBoxNoticeDuration = Existingemp.Controls.Add("Forms.TextBox.1", "NoticeDuration", True)
    Set lblRelvDate = Existingemp.Controls.Add("Forms.Label.1", "RelvDate", True)
    Set txtBoxRelvDate = Existingemp.Controls.Add("Forms.TextBox.1", "RelvDate", True)
    Set lblOffLast = Existingemp.Controls.Add("Forms.Label.1", "OffLast", True)
    Set txtBoxOffLast = Existingemp.Controls.Add("Forms.TextBox.1", "OffLast", True)
    Set lblOffEmailIdStatus = Existingemp.Controls.Add("Forms.Label.1", "OffEmailIdStatus", True)
    Set txtBoxOffEmailIdStatus = Existingemp.Controls.Add("Forms.TextBox.1", "OffEmailIdStatus", True)
    Set lblHandoverAssetData = Existingemp.Controls.Add("Forms.Label.1", "HandoverAssetData", True)
    Set cmbboxHandoverAssetData = Existingemp.Controls.Add("Forms.ComboBox.1", "HandoverAssetData", True)
    Set lblExitInterview = Existingemp.Controls.Add("Forms.Label.1", "ExitInterview", True)
    Set cmbExitInterview = Existingemp.Controls.Add("Forms.ComboBox.1", "ExitInterview", True)
    Set lblReleivingLetterStatus = Existingemp.Controls.Add("Forms.Label.1", "ReleivingLetterStatus", True)
    Set cmbReleivingLetterStatus = Existingemp.Controls.Add("Forms.ComboBox.1", "ReleivingLetterStatus", True)
    Set lblFandF = Existingemp.Controls.Add("Forms.Label.1", "FandF", True)
    Set cmbFandF = Existingemp.Controls.Add("Forms.ComboBox.1", "FandF", True)
    Set lblRemark = Existingemp.Controls.Add("Forms.Label.1", "Remark", True)
    Set txtRemark = Existingemp.Controls.Add("Forms.TextBox.1", "Remark", True)
    Set cmbbox = Existingemp.Controls.Add("Forms.ComboBox.1", "cmbbox", True)
   
   
        With lblName
            .BackColor = RGB(141, 180, 226)
            .Caption = "Name"
            .Font.Bold = True
            .Left = 124
            .Width = 36
            .Top = 7
            .BorderStyle = 1
            .Height = 16
        End With
        With lblNameval
           
            .BackColor = RGB(141, 180, 226)
            .Font.Bold = True
            .Caption = ThisWorkbook.Sheets(1).Range(lookupadd.Address).Offset(0, -3) & " " & ThisWorkbook.Sheets(1).Range(lookupadd.Address).Offset(0, -2) & " " & ThisWorkbook.Sheets(1).Range(lookupadd.Address).Offset(0, -1)
            .Left = 160
            .Width = 127
            .Top = 7
            .BorderStyle = 1
            .Height = 16
        End With
        With lblResignationDate
            .BackColor = RGB(255, 153, 102)
            .Caption = "Resignation Date"
            .Font.Bold = True
            .Left = 10
            .Width = 75
            .Top = 55
            .BorderStyle = 1
            .Height = 15
        End With
        With txtBoxResignationDate
           
            .Value = Format(Date, "mm/dd/yyyy")
            .Font.Bold = True
            .Left = 85
            .Width = 75
            .Top = 55
            .BorderStyle = 1
            .Height = 15
        End With
        With lblNoticeDuration
            .BackColor = RGB(255, 153, 102)
            .Caption = "Notice Durartion"
            .Font.Bold = True
            .Left = 10
            .Width = 75
            .Top = 70.5
            .BorderStyle = 1
            .Height = 20
        End With
        With txtBoxNoticeDuration
           
           
            .Font.Bold = True
            .Left = 85
            .Width = 75
            .Top = 70.5
            .BorderStyle = 1
            .Height = 20
        End With
        With lblRelvDate
            .BackColor = RGB(255, 153, 102)
            .Caption = "Releieving Date"
            .Font.Bold = True
            .Left = 10
            .Width = 75
            .Top = 91.5
            .BorderStyle = 1
            .Height = 15
        End With
        With txtBoxRelvDate
           
            .Value = Format(Date + 60, "mm/dd/yyyy")
            .Font.Bold = True
            .Left = 85
            .Width = 75
            .Top = 91.5
            .BorderStyle = 1
            .Height = 15
        End With
        With lblOffLast
            .BackColor = RGB(255, 153, 102)
            .Caption = "Official Last Date"
            .Font.Bold = True
            .Left = 10
            .Width = 75
            .Top = 107
            .BorderStyle = 1
            .Height = 15
        End With
        With txtBoxOffLast
           
            .Value = Format(Date + 60, "mm/dd/yyyy")
            .Font.Bold = True
            .Left = 85
            .Width = 75
            .Top = 107
            .BorderStyle = 1
            .Height = 15
        End With
       
        With lblOffEmailIdStatus
            .BackColor = RGB(255, 153, 102)
            .Caption = "Off. Emailid Status"
            .Font.Bold = True
            .Left = 175
            .Width = 81
            .Top = 55
            .BorderStyle = 1
            .Height = 15
        End With
        With txtBoxOffEmailIdStatus
           
           
            .Font.Bold = True
            .Left = 256
            .Width = 220
            .Top = 55
            .BorderStyle = 1
            .Height = 15
        End With
        With lblHandoverAssetData
            .BackColor = RGB(255, 153, 102)
            .Caption = "Handover Asset & Data"
            .Font.Bold = True
            .Left = 175
            .Width = 81
            .Top = 70.5
            .BorderStyle = 1
            .Height = 20
        End With
        With cmbboxHandoverAssetData
           
            .List = Array("Yes", "No", "Not Required")
            .Font.Bold = True
            .Left = 256
            .Width = 40
            .Top = 70.5
            .BorderStyle = 1
            .Height = 20
        End With
        With lblExitInterview
            .BackColor = RGB(255, 153, 102)
            .Caption = "Exit Interview"
            .Font.Bold = True
            .Left = 175
            .Width = 81
            .Top = 91.5
            .BorderStyle = 1
            .Height = 15
        End With
        With cmbExitInterview
           
            .List = Array("Yes", "No", "Not Required")
            .Font.Bold = True
            .Left = 256
            .Width = 40
            .Top = 91.5
            .BorderStyle = 1
            .Height = 15
        End With
        With lblReleivingLetterStatus
            .BackColor = RGB(255, 153, 102)
            .Caption = "Releiving Letter"
            .Font.Bold = True
            .Left = 175
            .Width = 81
            .Top = 107
            .BorderStyle = 1
            .Height = 15
        End With
        With cmbReleivingLetterStatus
           
            .List = Array("Issued", "Pending", "Not Required")
            .Font.Bold = True
            .Left = 256
            .Width = 40
            .Top = 107
            .BorderStyle = 1
            .Height = 15
        End With
        With lblFandF
            .BackColor = RGB(255, 153, 102)
            .Caption = "F&F Status"
            .Font.Bold = True
            .Left = 10
            .Width = 75
            .Top = 122.5
            .BorderStyle = 1
            .Height = 15
        End With
        With cmbFandF
           
            .List = Array("Yes", "No", "On Hold", "Not Required")
            .Font.Bold = True
            .Left = 85
            .Width = 40
            .Top = 122.5
            .BorderStyle = 1
            .Height = 15
        End With
        With lblRemark
            .BackColor = RGB(255, 153, 102)
            .Caption = "Remark"
            .Font.Bold = True
            .Left = 175
            .Width = 81
            .Top = 122.5
            .BorderStyle = 1
            .Height = 15
        End With
        With txtRemark
           
           
            .Font.Bold = True
            .Left = 256
            .Width = 220
            .Top = 122.5
            .BorderStyle = 1
            .Height = 15
        End With
        With lblStatus
            .Caption = "Status"
            .Font.Bold = True
            .BackColor = RGB(255, 153, 102)
            .Left = 350
            .Width = 75
            .Top = 140
            .BorderStyle = 1
            .Height = 14.5
        End With
       
       
        With cmbbox
            .List = Array("Resigned")
            .Left = 425.5
            .Width = 51
            .Top = 140
            .BorderStyle = 1
            .Height = 14.5
           
        End With
Existingemp.Height = 180
Existingemp.Width = 481

Application.EnableEvents = True
End Sub

Thursday, May 28, 2015

Sending Emails with Image signature in Outlook


Dim outlukApp As Outlook.Application, outlukMailItm As Outlook.MailItem, emailid, myval, i As Integer, fullbody As String
Dim sigstring As String, signature As String
Sub sendMail()
    Set outlukApp = New Outlook.Application
    Set outlukMailItm = outlukApp.CreateItem(olMailItem)
    myval = Application.InputBox("Enter Mutiple  EmailId with ; delimiter", "EmailId")
    On Error Resume Next
    If myval = False Then
        Exit Sub
    Else
         emailid = Split(myval, ";")
        
       
         For i = 0 To UBound(emailid)
          fullbody = "Dear," & "<br>"
          fullbody = fullbody & "<p>Please find the attachment of new joinee details</p><br><br>"
          fullbody = fullbody & "<br> Best Regards,"
             With outlukMailItm
                     .Display
                     .To = emailid(i)
                    
                     .Subject = "New Joinee Details"
                     .HTMLBody = "Dear,<br>" & "<p>Please find the attachment of new joinee details</p><br><br><br> Best Regards," & .HTMLBody
                     .Attachments.Add (ThisWorkbook.Path & "\" & ThisWorkbook.Name)
                     .Display
                     Application.DisplayAlerts = False
                     .Send
             End With
            
            
         Next
     End If
    Set outlukMailItm = Nothing
    Set outlukApp = Nothing
   
End Sub

Saturday, May 23, 2015

Copy filtered Data with Criteria

Dim rowcount As Long, myrng As Range, cell
Sub copyFilteredData()
rowcount = ThisWorkbook.Sheets(1).Cells(Rows.Count, 2).End(xlUp).Row
Set myrng = ThisWorkbook.Sheets(1).Range("B2:B" & rowcount)
For Each cell In myrng
        If cell.Value Like "*LF*" Then
            cell.Offset(0, 1) = 0
        Else
            cell.Offset(0, 1) = 1
        End If
Next
ThisWorkbook.Sheets(1).Range("A1:B" & rowcount).AutoFilter field:=2, Criteria1:="*LF*"
ThisWorkbook.Sheets(1).Range("A1:B" & rowcount).SpecialCells(xlCellTypeVisible).Copy
ThisWorkbook.Sheets("Lost").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteAll
ThisWorkbook.Sheets(1).ShowAllData
ThisWorkbook.Sheets(1).Range("A1:B" & rowcount).AutoFilter field:=2, Criteria1:="<>*LF*"
ThisWorkbook.Sheets(1).Range("A1:B" & rowcount).SpecialCells(xlCellTypeVisible).Copy
ThisWorkbook.Sheets("State").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

End Sub

Download file
 

Monday, April 13, 2015

Autofit Column using VBA

Sub Hidealternatecolumns()

Dim first As Double
Dim last As Double

first = 4
last = 40

For i = first To last

If Cells(1, i).Column Mod 2 = 0 Then
        Cells(1, i).EntireColumn.Hidden = True
    End If
Next
Range("C8").CurrentRegion.Columns.AutoFit

End Sub


Sunday, April 12, 2015

Send mail with Condition

Dim outlukApp As Outlook.Application, outlukMail, daterng As Range, rowcount As Long, cell


Sub sendMail()
rowcount = ThisWorkbook.Sheets("Data").Range("I" & Rows.Count).End(xlUp).Row

Set daterng = ThisWorkbook.Sheets("Data").Range("I2:I" & rowcount)
For Each cell In daterng
Set outlukApp = New Outlook.Application
Set outlukMail = outlukApp.CreateItem(olMailItem)

        If (cell = Date) Then
         
                With outlukMail
             
                    .Display
                    .To = CStr(cell.Offset(0, 3))
                    .Subject = "Intimation Mail"
                    .HTMLBody = "Dear " & "<b>" & cell.Offset(0, 2) & "</b>,<br>        Please find the attachment of....."
                 
     
                End With
                Application.DisplayAlerts = False
                Application.Wait (Now + TimeValue("00:00:05"))
                'Application.SendKeys "%s"
        End If
        Set outlukApp = Nothing
        Set outlukMail = Nothing
     
Next


End Sub


Monday, February 2, 2015

Tuesday, November 4, 2014

Data Validation With rules


Private Sub Worksheet_Change(ByVal Target As Range)
        If Target.Address = "$C$2" Then
            Select Case Target.Value
                Case "All"
                                   
                       With ThisWorkbook.Sheets(1).Range("D2").Validation
                            .Delete
                            .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=allrng"
                       End With
                Case "X"
                        With ThisWorkbook.Sheets(1).Range("D2").Validation
                            .Delete
                            .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=xrng"
                       End With
                Case "Y"
                        With ThisWorkbook.Sheets(1).Range("D2").Validation
                            .Delete
                            .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=yrng"
                       End With
            End Select
        End If
End Sub


Download file:

Data Validation with rules

Friday, August 22, 2014

Sort Data based on count on the basis of VBA

Dim mycoll As Collection
Dim myrng As Range, assgnrng As Range, rowcount As Long, cell, i As Integer
Sub sortData()
On Error Resume Next

rowcount = ThisWorkbook.Sheets(1).Range("A1").End(xlDown).Row
Set assgnrng = ThisWorkbook.Sheets(1).Range("A1:A" & rowcount)
    For i = 1 To rowcount
        ThisWorkbook.Sheets(1).Range("E" & (i + 1)) = Application.WorksheetFunction.CountIfs(assgnrng, ThisWorkbook.Sheets(1).Range("A" & (i + 1)))
   
    Next
ThisWorkbook.Sheets(1).Range("A1:E" & rowcount).Copy ThisWorkbook.Sheets(2).Range("A1")
ThisWorkbook.Sheets(2).Range("A2:E" & rowcount).Sort key1:=ThisWorkbook.Sheets(2).Range("E2"), order1:=xlDescending
End Sub






Download file

Thursday, August 7, 2014

Advancedfilter Using VBA













Sub testAdvancefilter()
'remove current filter
ThisWorkbook.Sheets("Summary").Range("B10").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Clear
'*********************************
ThisWorkbook.Sheets("Data").Range(ThisWorkbook.Sheets("data").Range("A1").CurrentRegion.Address).AdvancedFilter Action:=xlFilterCopy, criteriarange:=ThisWorkbook.Sheets("Data").Range("M1:P2"), copytorange:=ThisWorkbook.Sheets("Summary").Range("B10"), unique:=True
Columns.AutoFit
End Sub
















Download File

Sample file

Wednesday, May 7, 2014

Application.OnKey Example

Application.Onkey method runs a specified procedure when a particular key or key combination is pressed.


Sub test()
Call onKeyExample(True, True, True, "z", "myprocedure")

End Sub

Sub onKeyExample(shiftkey As Boolean, ctrlkey As Boolean, altkey As Boolean, strkey As String, callfunction As String)
Dim strShift As String
Dim strCtrl As String
Dim stralt As String
    If (shiftkey = True) Then strShift = "+"
    If (ctrlkey = True) Then strCtrl = "^"
    If (altkey = True) Then stralt = "%"
 
 
    Application.OnKey strShift & strCtrl & stralt & "{" & strkey & "}", callfunction
End Sub

Sub myprocedure()
    MsgBox "My Procedure"

End Sub

Friday, April 18, 2014

Scope of Variable


'Procedure Scope
Sub TestSub()
        Dim X As Long
        Dim Y As Long
       
        X = 1234
        Y = 4321
        MsgBox "X: " & X & "Y: " & Y
End Sub
'Module Scope
'Module scope means that a variable can be declared before and outside of any procedure
'in a regular code module. If you use Private or Dim to declare the variable, only procedures
'that are in the same module can access that variable. Since a module level variable is not
'part of any procedure, it will retain its value even after the procedure that changes its
'value has terminated. For example,
'Dim ModVar As Long
'Private ModVar As Long

'Project scope
'Project scope variables are those declared using the Public keyword.
'These variables are accessible from any procedure in any module in the project.
'In Excel, a Project is all of the code modules, userforms, class modules, and object
'modules (e.g,. ThisWorkbook and Sheet1) that are contained within a workbook.
'If you want a variable to be accessible from anywhere within the project, but not accessible
'from another project, you need to use Option Private Module as the first line in the module
'Global Scope
'Global scope variables are those that are accessible from anywhere in the project that
'declares them as well as any other project that references the first project. To declare
'a variable with global scope, you need to declare it using the Public keyword in a module
'that does not use the Option Private Module directive.

Friday, March 28, 2014

Colored table in Outlook HtmlBody

Option Explicit
Dim outlApp As Outlook.Application, outlMailitem As Outlook.MailItem
Dim heading As String, fullbody As String, myrng As Range, rowcount As Long, cell
Sub sendmailsinhtmlBody()



Set outlApp = New Outlook.Application
Set outlMailitem = outlApp.CreateItem(olMailItem)
rowcount = ThisWorkbook.Sheets(1).Range("D6").End(xlDown).Row
Set myrng = ThisWorkbook.Sheets(1).Range("D7:D" & rowcount)
heading = "<table align=" & """center""" & "border=" & """4""" & ",collapsing=4><tr bgcolor=#808080 ><b><td>" & ThisWorkbook.Sheets(1).Range("D6") & "</td><td>" & ThisWorkbook.Sheets(1).Range("e6") & "</td><td>" & ThisWorkbook.Sheets(1).Range("f6") & "</td></b></tr>"
            fullbody = "Hi," & "<br>"
            fullbody = fullbody & "<p>Please find the status below:</p>" & vbNewLine & vbNewLine
            fullbody = fullbody & heading
For Each cell In myrng

         
            fullbody = fullbody & "<tr bgcolor=#CCFFFF ><td>" & cell.Value & "</td><td>" & cell.Offset(0, 1) & "</td><td>" & cell.Offset(0, 2) & "</td></tr>"
Next
            fullbody = fullbody & "</table>"
         
        With outlMailitem
         
                .To = "pc_soumyendu@yahoo.co.in"
                .htmlbody = fullbody
                .Subject = "Daily Report"
                .Display
        End With
 

End Sub

Tuesday, March 25, 2014

Insert & Delete Entire Row in VBA



Option Explicit
Dim rowcount As Long, myrng As Range
Sub removeBlankcells()

rowcount = ThisWorkbook.Sheets(1).Range("A65500").End(xlUp).Row
    Set myrng = ThisWorkbook.Sheets(1).Range("A2:A" & rowcount)
     ThisWorkbook.Sheets(1).UsedRange.AutoFilter field:=1, Criteria1:=""
     ThisWorkbook.Sheets(1).Range("A1:A" & rowcount).SpecialCells(xlCellTypeBlanks).Select
     Selection.EntireRow.Delete
    ThisWorkbook.Sheets(1).AutoFilterMode = False
End Sub



Option Explicit
Dim rowcount As Long, i As Integer
Sub insertRow()
Application.ScreenUpdating = False
    rowcount = ThisWorkbook.Sheets(1).Range("A1").End(xlDown).Row
    For i = 2 To (rowcount - 1) * 2
        ThisWorkbook.Sheets(1).Range("A" & (i + 1)).EntireRow.Insert
          i = i + 1
       Next

End Sub





File to downlaod

Saturday, March 15, 2014

Use Find Method(VBA) to search fraction

Option Explicit
Dim rowcount As Long, myrng As Range, i As Integer, lookupval As String, lookuprng As Range
Dim totalrng As Range, rownum As Variant
Sub sortData()
rowcount = ThisWorkbook.Sheets(1).Range("D2").End(xlDown).Row

Set myrng = ThisWorkbook.Sheets(1).Range("D1:D" & rowcount)
    i = 1
    For i = 1 To rowcount - 1
        lookupval = Format(Application.WorksheetFunction.Large(myrng, i), "#.00")
       
        With ThisWorkbook.Sheets(1).Range(myrng.Address)
            If InStr(lookupval, ".") > 1 Then
                Set lookuprng = .Find(what:=lookupval, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows)
            ElseIf (InStr(lookupval, ".")) = 1 Then
                Set lookuprng = .Find(what:=lookupval, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows)
            End If
        End With
     
        ThisWorkbook.Sheets(1).Range("K" & (i + 1)) = lookupval
        ThisWorkbook.Sheets(1).Range("H" & (i + 1)) = lookuprng.Offset(0, -3)
        ThisWorkbook.Sheets(1).Range("I" & (i + 1)) = lookuprng.Offset(0, -2)
        ThisWorkbook.Sheets(1).Range("J" & (i + 1)) = lookuprng.Offset(0, -1)
     Set lookuprng = Nothing
     lookupval = vbNullString
    Next
End Sub