Wednesday, October 30, 2013

Copy Range from Another Workbook through VBA

Option Explicit
Dim fso As FileSystemObject
Dim fl As File
Dim fldr As Folder
Public wb As Workbook, wbnew As Workbook
Dim fldrpath As String
Sub trackSheet()
Set wb = ThisWorkbook
On Error GoTo ErrorHandler
Set fso = New Scripting.FileSystemObject
Application.FileDialog(msoFileDialogFolderPicker).Title = "Choose Folder"
Application.FileDialog(msoFileDialogFolderPicker).Show
fldrpath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) & "\"
Set fldr = fso.GetFolder(fldrpath)
For Each fl In fldr.Files
    wb.Sheets.Add after:=Sheets(Sheets.Count)
 
    wb.Sheets(Sheets.Count).Name = fl.Name
Call copySheet(fldrpath & fl.Name)


Next
Set wb = Nothing
Exit Sub
ErrorHandler:

MsgBox "Select Folder"

End Sub



Sub copySheet(ByVal pathname As String)
 i = InStr(pathname, ".")
 extn = Mid(pathname, i, Len(pathname) - (i - 1))
 If extn Like ".xl*" Then
        Set wbnew = Workbooks.Open(pathname)
        Application.DisplayAlerts = False
        wbnew.Sheets(1).UsedRange.Copy Destination:=wb.Sheets(wb.Sheets.Count).Range("A1")
        wb.Save
        wbnew.Close
 End If
End Sub





https://drive.google.com/file/d/0B23eJ2xd9ODycEVOclQ5TmJkYnM/edit?usp=sharing

Friday, October 18, 2013

Application.Caller Example in VBA

Option Explicit
Dim myrng As Range
Dim shp As Shape
Sub displayData()
Set shp = ThisWorkbook.Sheets(1).Shapes(Application.Caller)

        Select Case shp.TextFrame.Characters.Text
            Case "Display Data Hiding Zero"
                  shp.TextFrame.Characters.Text = "Display all Data"
                  For Each myrng In Range("D2:D23")
                     If myrng = 0 Then myrng.EntireRow.Hidden = True
                 
                  Next
            Case Else
                  shp.TextFrame.Characters.Text = "Display Data Hiding Zero"
                  Cells.EntireRow.Hidden = False
        End Select

End Sub

For details about Application.Caller plz refer:


Example file link

https://docs.google.com/file/d/0B23eJ2xd9ODyZXNHNktaeWlFUkU/edit?usp=sharing

Bubble Sort in VBA







Option Explicit
Dim myarray(), lookuprange As Range
Dim myrng As Range, mycell, i As Integer, k As Integer, l As Integer, tempvar

Sub sortarrangeData()
Application.ScreenUpdating = False
ReDim myarray(countUnique(Sheets(1).Range("A2:A31")))
Set myrng = ThisWorkbook.Sheets(1).Range("A2:A31")
For Each mycell In myrng
        If mycell <> mycell.Offset(1, 0) Then
            myarray(i) = mycell
            i = i + 1
         
        End If
Next
i = 0
'bubble sort
For k = 0 To countUnique(Sheets(1).Range("A2:A31")) - 1
    For l = k + 1 To countUnique(Sheets(1).Range("A2:A31"))
         If myarray(k) > myarray(l) Then
            tempvar = myarray(k)
            myarray(k) = myarray(l)
            myarray(l) = tempvar
         End If
       
       
    Next
 
Next
For l = 1 To countUnique(Sheets(1).Range("A2:A31"))
 
    Set lookuprange = ThisWorkbook.Sheets(1).Cells.Find(myarray(l), LookIn:=xlValues, lookat:=xlWhole)
    'MsgBox myarray(l) & "Addess" & lookuprange.Address
    Cells(l + 1, 5) = myarray(l)
    Cells(l + 1, 6) = lookuprange.Offset(0, 1)
    Cells(l + 1, 7) = lookuprange.Offset(1, 1)
    Cells(l + 1, 8) = lookuprange.Offset(2, 1)
Next
End Sub


Function countUnique(rng As Range) As Long
Dim coll As New Collection
Dim cell As Variant

On Error Resume Next
    For Each cell In rng
     
        coll.Add CStr(cell.Value), CStr((cell.Value))

    Next
    countUnique = coll.Count
 
    Set coll = Nothing
End Function


https://docs.google.com/file/d/0B23eJ2xd9ODyWUtvbUpJZ08wbE0/edit?usp=sharing

Thursday, October 3, 2013

VBA Sample Code for Two Dimensional Array

Option Explicit
Dim daterng As Range, otherrng As Range, i As Integer, j As Integer, tempCounter As Integer, tempcounternew As Integer
Dim tempcounternew1 As Integer, tempcounternew2 As Integer, tempcounternew3 As Integer
Dim myArray()
Sub realignmentofreport()
Set daterng = ThisWorkbook.Sheets(1).Range("B10:B13")
Set otherrng = ThisWorkbook.Sheets(1).Range("B3:B6")
tempCounter = 0
tempcounternew = 0
tempcounternew1 = 0
tempcounternew2 = 0
tempcounternew3 = 0
On Error Resume Next
    ReDim myArray(1 To daterng.Rows.Count * 5, 1 To otherrng.Rows.Count)
    For i = 1 To UBound(myArray())
   
        tempCounter = tempCounter + 1
       
              
        Select Case (tempCounter < 6)
            Case True
               
                tempcounternew = tempcounternew + 2
                myArray(i, 1) = ThisWorkbook.Sheets(1).Range("B10")
                myArray(i, 2) = ThisWorkbook.Sheets(1).Range("B10").Offset(0, tempcounternew)
                myArray(i, 3) = Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets(1).Range("B10").Offset(0, tempcounternew - 1), [lookuprng], 2, 0)
                myArray(i, 4) = Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets(1).Range("B10").Offset(0, tempcounternew - 1), [lookuprng], 3, 0)
            Case Else
                Select Case (tempCounter < 11) And (tempCounter > 5)
                Case True
                    tempcounternew1 = tempcounternew1 + 2
                   
                    myArray(i, 1) = ThisWorkbook.Sheets(1).Range("B11")
                    myArray(i, 2) = ThisWorkbook.Sheets(1).Range("B11").Offset(0, tempcounternew1)
                    myArray(i, 3) = Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets(1).Range("B11").Offset(0, tempcounternew1 - 1), [lookuprng], 2, 0)
                    myArray(i, 4) = Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets(1).Range("B11").Offset(0, tempcounternew1 - 1), [lookuprng], 3, 0)
                 Case Else
                    Select Case (tempCounter < 16) And (tempCounter > 10)
                        Case True
                            tempcounternew2 = tempcounternew2 + 2
                           
                            myArray(i, 1) = ThisWorkbook.Sheets(1).Range("B12")
                            myArray(i, 2) = ThisWorkbook.Sheets(1).Range("B12").Offset(0, tempcounternew2)
                            myArray(i, 3) = Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets(1).Range("B12").Offset(0, tempcounternew2 - 1), [lookuprng], 2, 0)
                            myArray(i, 4) = Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets(1).Range("B12").Offset(0, tempcounternew2 - 1), [lookuprng], 3, 0)
                   
                        Case Else
                            Select Case (tempCounter < 21) And (tempCounter > 15)
                                Case True
                                    tempcounternew3 = tempcounternew3 + 2
                                   
                                    myArray(i, 1) = ThisWorkbook.Sheets(1).Range("B13")
                                    myArray(i, 2) = ThisWorkbook.Sheets(1).Range("B13").Offset(0, tempcounternew3)
                                    myArray(i, 3) = Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets(1).Range("B13").Offset(0, tempcounternew3 - 1), [lookuprng], 2, 0)
                                    myArray(i, 4) = Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets(1).Range("B13").Offset(0, tempcounternew3 - 1), [lookuprng], 3, 0)
                            End Select
                    End Select
                End Select
        End Select
       
       
  Next
    Sheets(1).Range("H19").Resize(tempCounter, UBound(myArray, 2)) = myArray
End Sub
 https://drive.google.com/file/d/0B23eJ2xd9ODyQTY0blFYRk9McVU/edit?usp=sharing

Wednesday, October 2, 2013

VBA Code to Display Which Button was Pressed

Sub ClickonwhichButton()

         ' Assign the calling object to a variable.
         ButtonName = Application.Caller

         ' Display the name of the button that was clicked.
         Select Case ButtonName

            ' NOTE: When you type the name of the button, note that
            ' Visual Basic is case and space sensitive when comparing                                                
            ' strings. For example, "Button 6" and "button6" are not the 
            ' same.
            Case "Button 6"
            MsgBox Application.Caller & "  was Clicked"

            Case "Button 7"
            MsgBox Application.Caller & " was clicked."

            Case "Button 8"
            MsgBox Application.Caller & " was clicked."

         End Select

End Sub

Extracting Button Caption on a Click Event of a Button

'Assign this macro to button


Sub test()
MsgBox ActiveSheet.Buttons(Application.Caller).Caption
End Sub

Load MultipleImageFilename in Excel Using VBA

Dim fl, i As Integer, fildialog As Variant

Sub LoadImageFile()
 Set fildialog = Application.FileDialog(msoFileDialogFilePicker)
    With fildialog
        .AllowMultiSelect = True
         .Title = "Select Image"
        .Filters.Clear
     
        .Filters.Add "Image Files", "*.jpg,*.bmp,*.png,*.gif"
        i = 1
        If .Show = True Then
                    For Each fl In .SelectedItems
                        ThisWorkbook.Sheets(1).Range("A" & i) = fl
                   
                        i = i + 1
                    Next
        Else
            MsgBox "Precess cancelled"
        End If
    End With
End Sub


Thursday, September 26, 2013

Updation of file using VBA

First update data from raw file to final file , second  when i do any changes in raw file it will automatic change in final workbook. Keep both files in same folder


https://docs.google.com/file/d/0B23eJ2xd9ODyY2tCdmxOTXh4Snc/edit?usp=sharing
https://docs.google.com/file/d/0B23eJ2xd9ODyZ05PM3lzU2NVRjQ/edit?usp=sharing

Tuesday, September 24, 2013

Using # In If Condition

# is used only for numeric values in VBA


Option Explicit
Dim mydata, tempval, i

Sub getData()
mydata = Application.InputBox("Enter Data", "Data", Type:=2)
For i = 1 To Len(mydata)
    If Mid(mydata, i, 1) Like "#" Then
        tempval = tempval & Mid(mydata, i, 1)
    End If
Next i
MsgBox tempval
tempval = vbNullString
End Sub

Finding files name from folders/Subfolders



first of all you will add FSO References

Step for Add:- Tools-Reference-Microsoft Scripting Runtime
and try below code

Sub File_name()

Dim fso As FileSystemObject
Dim fl As File
Dim fldr As Folder
Dim wb As Workbook
Set wb = ThisWorkbook
Set fso = New FileSystemObject
Application.FileDialog(msoFileDialogFolderPicker).Title = "Choose Folder"
Application.FileDialog(msoFileDialogFolderPicker).Show
Dim fldpath As String
fldpath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)
& "\"
Set fldr = fso.GetFolder(fldpath)
i = 2
For Each fl In fldr.Files
Sheet3.Cells(i, "D").Value = fl.Name
i = i + 1
Next fl
End Sub

Friday, September 20, 2013

Form Control vs. ActiveX Control in MS Excel

Difference
ActiveX Controls
Excel Controls
Excel versions
97, 2000
5, 95, 97, 2000
Which toolbar?
Control Toolbox
Forms
Controls available
CheckBox, TextBox, CommandButton, OptionButton, ListBox, ComboBox, ToggleButton, SpinButton, ScrollBar, Label, Image
Label, GroupBox, Button, CheckBox, OptionButton, ListBox, ComboBox, ScrollBar, Spinner
Macro code storage
In the code module for the Sheet
In any standard VBA module
Macro name
Corresponds to the control name (e.g., CommandButton1_Click)
Any name you specify.
Correspond to...
UserForm controls
Dialog Sheet controls
Customization
Extensive, using the Properties box
Minimal
Respond to events
Yes
Click or Change events only

Convert Time Zone through VBA

Option Explicit
Private Type SYSTEMTIME
    wYear As Integer
    wMonth As Integer
    wDayOfWeek As Integer
    wDay As Integer
    wHour As Integer
    wMinute As Integer
    wSecond As Integer
    wMilliseconds As Integer
End Type
Private Type TIME_ZONE_INFORMATION
    Bias As Long
    StandardName(31) As Integer
    StandardDate As SYSTEMTIME
    StandardBias As Long
    DaylightName(31) As Integer
    DaylightDate As SYSTEMTIME
    DaylightBias As Long
End Type
Private Declare Function GetTimeZoneInformation Lib "kernel32" (lpTimeZoneInformation As TIME_ZONE_INFORMATION) As Long
'Purpose     :  Converts local time to GMT.
'Inputs      :  dtLocalDate                 The local data time to return as GMT.
'Outputs     :  Returns the local time in GMT.
'Author      :  Andrew Baker
'Date        :  13/11/2002 10:16
'Notes       :
'Revisions   :
Public Function ConvertLocalToGMT(dtLocalDate As Date) As Date
    Dim lSecsDiff As Long
 
    'Get the GMT time diff
    lSecsDiff = GetLocalToGMTDifference()
    'Return the time in GMT
    ConvertLocalToGMT = DateAdd("s", -lSecsDiff, dtLocalDate)
End Function

'Purpose     :  Converts GMT time to local time.
'Inputs      :  dtLocalDate                 The GMT data time to return as local time.
'Outputs     :  Returns GMT as local time.
'Author      :  Andrew Baker
'Date        :  13/11/2002 10:16
'Notes       :
'Revisions   :
Public Function ConvertGMTToLocal(gmtTime As Date) As Date
    Dim Differerence As Long
 
    Differerence = GetLocalToGMTDifference()
    ConvertGMTToLocal = DateAdd("s", Differerence, gmtTime)
End Function

'Purpose     :  Returns the time lDiff between local and GMT (secs).
'Inputs      :  dtLocalDate                 The local data time to return as GMT.
'Outputs     :  Returns the local time in GMT.
'Author      :  Andrew Baker
'Date        :  13/11/2002 10:16
'Notes       :  A positive number indicates your ahead of GMT.
'Revisions   :
Public Function GetLocalToGMTDifference() As Long
    Const TIME_ZONE_ID_INVALID& = &HFFFFFFFF
    Const TIME_ZONE_ID_STANDARD& = 1
    Const TIME_ZONE_ID_UNKNOWN& = 0
    Const TIME_ZONE_ID_DAYLIGHT& = 2
 
    Dim tTimeZoneInf As TIME_ZONE_INFORMATION
    Dim lRet As Long
    Dim lDiff As Long
 
    'Get time zone info
    lRet = GetTimeZoneInformation(tTimeZoneInf)
 
    'Convert diff to secs
    lDiff = -tTimeZoneInf.Bias * 60
    GetLocalToGMTDifference = lDiff
 
    'Check if we are in daylight saving time.
    If lRet = TIME_ZONE_ID_DAYLIGHT& Then
        'In daylight savings, apply the bias
        If tTimeZoneInf.DaylightDate.wMonth <> 0 Then
            'if tTimeZoneInf.DaylightDate.wMonth = 0 then the daylight
            'saving time change doesn't occur
            GetLocalToGMTDifference = lDiff - tTimeZoneInf.DaylightBias * 60
        End If
    End If
End Function

Tuesday, September 17, 2013

Data Validation Using VBA

Please find the attachment

https://docs.google.com/file/d/0B23eJ2xd9ODyemRISnRSMmQ5LUk/edit?usp=sharing

Example of Select Case in VBA







Dim rng As Range, totalsalary As Long

Sub calculatesalary()
Set rng = Application.InputBox("Select Range", "salary", Type:=8)
For Each cell In rng
        Select Case cell.Value
        Case Is <= 900
         totalsalary = cell.Value + (cell.Value * 0.1)
        Case 901 To 1000
         totalsalary = cell.Value + (cell.Value * 0.125)
        Case Is > 1000
        totalsalary = cell.Value + (cell.Value * 0.15)
        End Select
        cell.Offset(, 1) = totalsalary
Next
End Sub

Monday, September 16, 2013

Using Enumeration In VBA




VBA code to develop a function to calculate salary with allowance



Public Enum commission
grade1 = 100
grade2 = 125
grade3 = 150
End Enum

Function Calculatesalary(ByVal rng As Range) As Long
Dim salary, totalsalary As Long, myrng As Range

Set myrng = rng

salary = CLng(myrng.Value)

Select Case (salary <= 900)
Case True

    totalsalary = salary + salary * ((commission.grade1) / 1000)
 
Case Else
    Select Case (900 < salary <= 1000)
    Case True
    totalsalary = salary + salary * ((commission.grade2) / 1000)
    Case Else
        Select Case (1000 < salary)
        Case True
            totalsalary = salary + salary * ((commission.grade3) / 1000)
        End Select
    End Select

End Select

Calculatesalary = totalsalary


totalsalary = 0
End Function

For details read

http://www.cpearson.com/excel/Enums.aspx

Sunday, September 15, 2013

Count of Vowels In A String USING VBA

Option Explicit
Dim i As Integer, j As Integer
Dim myval As String
Sub countofVowels()
myval = Application.InputBox("Enter a word", "Word", Type:=2)

For i = 1 To Len(myval)
If LCase(Mid(myval, i, 1)) Like "[a,e,i,o,u]" Then
j = j + 1
End If


Next
MsgBox "Total count of Vowels" & j
i = 0
j = 0
End Sub

Saturday, September 14, 2013

Insert Multiple Row before Unique Value through VBA



Region Product  Grand_Total
ANZ Tech                     159
ANZ OFM                       70
ANZ OFM                       70
TC HCIL                       41
TC HCIL                     297
ASEAN Apps                       80
ASEAN Apps                     587
ASEAN Systems                     350
ASEAN Apps                       34
MGI ORC                     600
MGI ORC                     658
MGI ORC                     750
DL ORG 340
DL ORG 123
DL ORG 107
GC Systems                     161
GC Apps                       83
GC Apps                       83
HR CI 611
HR CI 113
HR CI 596
IN Tech                     551
IN Tech                     832
IN Tech                       66
KR Tech                     275
KR OFM                       87
KR OFM                       81
MP HCL 665
MP HCL 579
HP MPGC 662
HP MPGC 672
HP MPGC 319
HP MPGC 772
HP MPGC 129


For example  if you want to insert a row after every unique region here is code


Option Explicit
Dim mycoll As Collection, strrow As String, finalstrrow As String
Dim myrng As Range, rowcount As Long, cell, i As Integer
Sub insertRowafterUnique()
rowcount = ThisWorkbook.Sheets(1).Range("A1").End(xlDown).Row
Set mycoll = New Collection
Set myrng = ThisWorkbook.Sheets(1).Range("A2:A" & rowcount)
strrow = vbNullString
On Error Resume Next
    For Each cell In myrng
        mycoll.Add cell, CStr(cell)

    Next
 
    For i = 2 To rowcount
            If ThisWorkbook.Sheets(1).Range("A" & i) <> ThisWorkbook.Sheets(1).Range("A" & (i + 1)) Then
                strrow = strrow & (i + 1) & ":" & (i + 1) & ","
             
 
 
            End If
    Next
    finalstrrow = Left(strrow, Len(strrow) - 1)
    ThisWorkbook.Sheets(1).Range(finalstrrow).EntireRow.Insert
End Sub

Thursday, September 12, 2013

Find vs Search

Find
- Case Sensitive
- Can't using Wildcard

Seach
- Not Case Sensitive
- Can Using Wildcard

Create Validation by Removing Duplicates

A
B
C
D
B
C
A
F
G
D
A

Option Explicit
Dim rowcount As Long
Dim myarray As New Collection, tempval As String, finaltempval As String

Sub addValidation()
On Error Resume Next
rowcount = Sheets(2).Range("a3").End(xlDown).Row
For i = 3 To rowcount
tempval = vbNullString
myarray.Add Range("A" & i), Range("A" & i)

Next i
For j = 1 To myarray.Count
    tempval = tempval & myarray(j) & ","

Next j

finaltempval = Mid(tempval, 1, Len(tempval) - 1)

With Range("B1").Validation

    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=finaltempval

End With
finaltempval = vbNullString
End Sub

Wednesday, September 11, 2013

Hide Formula in Workbook

Goto format of cell - protection- check Hidden - OK....after this protect your sheet...

Friday, September 6, 2013

Setting Up Expiry Date for Workbook

Private Sub Workbook_Open()
    Dim ExpDate As Date
    ExpDate = #8/17/2013 10:00:00 AM#
    
    If Now > ExpDate Then ThisWorkbook.Close
    MsgBox "This workbook will expired at " & Format(ExpDate, "dd mmmm yyyy hh:mm:ss AM/PM")
End Sub

Thursday, September 5, 2013

VBA Automation for MS Excel File

In Master Sheet there are three cells in attached sheet G1,G2 & J2.  When I will run macro it should check that whether values are entered in these cells.  If any one of cells are blank, cell should be RED and give message that values are not entered. and then it should ask Do you want to enter data now, if yes input box for entering value.


Option Explicit
Dim birth As Range, PANNo As Range, empName As Range, userInput



Sub validateData()
Application.ScreenUpdating = False
Set birth = [G2]
Set PANNo = [J2]
Set empName = [G1]
If IsEmpty(empName) Then
    [empName].Interior.ColorIndex = 3
    [empName].Interior.Pattern = xlSolid
    If MsgBox("Employee Name is empty;Please enter now", vbYesNo) = vbYes Then
        userInput = Application.InputBox("Please Enter Employee name", Type:=2)
        If Len(userInput) > 0 Then
            [empName].Value = userInput
            [empName].Interior.ColorIndex = 2
        End If
    End If
End If
If IsEmpty(birth) Then
    [birth].Interior.ColorIndex = 3
    [birth].Interior.Pattern = xlSolid
    If MsgBox("Date of Birth is empty; Please enter now", vbYesNo) = vbYes Then
    userInput = vbNullString
        userInput = Application.InputBox("Enter DOB", "DOB in mm/dd/yyyy format", Default:=Format(Date, "mm/dd/yyyy"), Type:=2)
        If IsDate(userInput) Then
            [birth].Value = userInput
            [birth].Interior.ColorIndex = 2
        End If
    End If

 
End If
If IsEmpty(PANNo) Then

    [PANNo].Interior.ColorIndex = 3
    [PANNo].Interior.Pattern = xlSolid
    If MsgBox("PAN No. is empty;Please enter now", vbYesNo) = vbYes Then
        userInput = vbNullString
        userInput = Application.InputBox("Enter PAN No.", "PAN No.", Type:=2)
        If Len(userInput) = 10 Then
            [PANNo].Value = userInput
            [PANNo].Interior.ColorIndex = 2
        End If
    End If
End If
End Sub



https://docs.google.com/file/d/0B23eJ2xd9ODybDdROVo4dUxLVjA/edit?usp=sharing

Friday, August 23, 2013

Use Split in VBA

Sub useSplitinVBA()
Dim myarry1 As Variant
Dim i As Integer
On Error Resume Next
myarry1 = Split(Sheet1.Cells(1, 1).Value, "\")
    For i = LBound(myarry1) To UBound(myarry1)
 
        If WorksheetFunction.Find(",", myarry1(i)) > 0 Then
        myarry2 = Split(myarry1(i), ",")
            For k = LBound(myarry2) To UBound(myarry2)
            MsgBox myarry2(k)
            Next
        End If
 
    Next
End Sub

Using Resize Property to Change the size of a range


The Resize property enables you to change the size of a range based on the location of the active cell.
You can create a new range as you need it.

For Example

Sub rngresize()

    Set Rng = Range("B1:B16").Find(What:="0", LookAt:=xlWhole, LookIn:=xlValues)
 
    Rng.Offset(, -1).Resize(, 2).Interior.ColorIndex = 15


End Sub


https://docs.google.com/file/d/0B23eJ2xd9ODySGNBdEhITWNKeHc/edit?usp=sharing

Tuesday, August 20, 2013

Print Userform in Landscape Format


Private Declare Sub keybd_event Lib "user32" _
(ByVal bVk As Byte, _
ByVal bScan As Byte, _
ByVal dwFlags As Long, _
ByVal dwExtraInfo As Long)

'dwFlags parameter of keybd_event controls various aspects of function operation. _

'This parameter can be one or more of the following values.

'KEYEVENTF_KEYUP
'if specified, the key is being released.If not specified, the key is being depressed.

'KEYEVENTF_EXTENDEDKEY
'If specified, the scan code was preceded by a prefix _
'byte having the value 0xE0 (224).

Private Const KEYEVENTF_KEYUP = &H2
Private Const KEYEVENTF_EXTENDEDKEY = &H1
'Print Screen key
Private Const VK_SNAPSHOT = &H2C
'Alt Key
Private Const VK_MENU = &H12
'Left Alt Key
Private Const VK_LMENU = &HA4

Private Sub CommandButton1_Click()
    Dim wshTemp As Worksheet
    DoEvents

    ' Simulate pressing ALT+Printscreen to copy the form window (=picture) to
    ' the clipboard
    keybd_event VK_LMENU, 0, KEYEVENTF_EXTENDEDKEY, 0
    keybd_event VK_SNAPSHOT, 0, KEYEVENTF_EXTENDEDKEY, 0
    keybd_event VK_SNAPSHOT, 0, KEYEVENTF_EXTENDEDKEY + KEYEVENTF_KEYUP, 0
    keybd_event VK_LMENU, 0, KEYEVENTF_EXTENDEDKEY + KEYEVENTF_KEYUP, 0
    DoEvents

    ' Add a worksheet named Temp
    ThisWorkbook.Worksheets.Add
    ActiveSheet.Name = "Temp"
    Set wshTemp = ThisWorkbook.Worksheets("Temp")

    ' Paste the picture, set print orientation to landscape en print it
    With wshTemp
     .Paste
     .PageSetup.Orientation = xlLandscape
     .PrintOut
    End With

    ' Delete the worksheet Temp and suppress the not-saved Warning.
    Application.DisplayAlerts = False
    ThisWorkbook.Worksheets("Temp").Delete
    Application.DisplayAlerts = True
End Sub

Sunday, August 18, 2013

Searching Files of All Format in a Folder

Option Explicit
Dim pathname As String
Dim i As Integer
Dim fso As Object
Dim folder1 As Object
Dim file1 As Object
Sub getFileDetailsunderSpecifiedFolder()
pathname = Application.InputBox("Provide path of specified Folder", "Pathname", Type:=2)
i = 2
Set fso = New Scripting.FileSystemObject
Set folder1 = fso.GetFolder(pathname)
    For Each file1 In folder1.Files
        Cells(i, 1) = file1.Name
        Cells(i, 2) = Environ("Username")
        Cells(i, 3) = file1.DateLastAccessed
        Cells(i, 4) = file1.DateLastModified
   
        i = i + 1
   
    Next
End Sub


https://docs.google.com/file/d/0B23eJ2xd9ODyampNbDRmOEd3R3c/edit?usp=sharing


Thursday, August 8, 2013

Compare Strings in Cases Insensitive Cases

When you compare 2 Strings for Case insensitive cases use
Option Compare Text at the top of the sub procedure.

One small example

Option Compare Text

Sub check()
If ("A" = "a") Then

MsgBox "Case insensitive"
End If
End Sub

Wednesday, August 7, 2013

Listing of File Names with Different Folders



Public pathname As String
Public fileformat As String
Dim strfile As String
Dim rowcount As Long
'Parameters are passed from Forms
Sub ListFiles()

rowcount = 2
strfile = Dir(pathname & "\" & fileformat, vbNormal)
    If Len(strfile) = 0 Then
            MsgBox "No file Exists", vbOKOnly

    End If
    Application.ScreenUpdating = False
    Do While Len(strfile) > 0
 
        Cells(rowcount, 3) = strfile
        Cells(rowcount, 4) = FileDateTime(pathname & "\" & strfile)
        rowcount = rowcount + 1
        'get nextfile from Folder
        strfile = Dir
    Loop
    Columns.AutoFit
End Sub

Convert Excel File To PDF




Sub Excel2PDFConverter()
With Application.FileDialog(msoFileDialogFolderPicker)
              .Show
              Path = .SelectedItems(1)
End With
              ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Path & "\" & "exceltopdf"
End Sub

Creating a Folder Inside SubFolder


'take reference of Microsoft Scripting Runtime
Sub createFolderinsideSubFolder()
Dim fso As Scripting.FileSystemObject
Dim parentfolder As Object
Dim subfolder As Object
Dim myfolder As String

Set fso = CreateObject("Scripting.FileSystemObject")
myfolder = "D:\Somu\"
Set parentfolder = fso.GetFolder(myfolder)
For Each subfolder In parentfolder.SubFolders
'searching all SubFolders inside D:\Somu\
myfolder = subfolder.Path & "\2013"
    If Not fso.FolderExists(myfolder) Then
        MkDir (myfolder)
    End If
Next

End Sub

Friday, August 2, 2013

ConnectionString Briefing(Used in SQL Server connectivity)

In computing, a Connectionstring is a string that specifies information about a data source and the means of connecting to it. It is passed in code to an underlying driver or provider in order to initiate the connection. Whilst commonly used for a database connection, the data source could also be a spreadsheetor text file.  ConnectionString property can be set only when the connection is closed. The connection string is parsed immediately after being set. If errors in syntax are found when parsing, a runtime exception, such asArgumentException, is generated. Other errors can be found only when an attempt is made to open the connection.
The connection string may include attributes such as the name of the driver, server and database, as well as security information such as user name and password.
For Reference:
www.connectionstrings.com

For example:
 con_string = "DRIVER={MySQL ODBC 3.51 Driver};user=internalros;password=internalros;database=TBS; server=206.71.169.000;option=18475"
ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=NEW\SQLEXPRESS;"

ODBC-it is designed for connecting to relational databases.
However, OLE DB can access relational databases as well as nonrelational databases.
List of Parameters for Microsoft OLE-DB Provider:

https://docs.google.com/file/d/0B23eJ2xd9ODyZDg2ZFdCZUM1MWM/edit?usp=sharing

Thursday, July 25, 2013

Suffixes after variable name in VBA

Dim A!, B@, C#, D$, E%, F&
Debug.Print "A! - " & TypeName(A)
Debug.Print "B@ - " & TypeName(B)
Debug.Print "C# - " & TypeName(C)
Debug.Print "D$ - " & TypeName(D)
Debug.Print "E% - " & TypeName(E)
Debug.Print "F& - " & TypeName(F)
A! - Single
B@ - Currency
C# - Double
D$ - String
E% - Integer
F& - Long
For Reference:
http://support.microsoft.com/kb/110264

Tuesday, July 16, 2013

Export Userform to Another Workbook

Dim vbcomponent As Variant
Sub exportForm()
On Error Resume Next
Dim wbSource As Workbook, wbDestination As Workbook
Set wbSource = Workbooks.Open("C:\abc\DIR\Desktop\Book1")
Set wbDestination = ThisWorkbook
For Each vbcomponent In wbSource.VBProject.VBComponents
        If (vbcomponent.Name = "displayForm") Then
     
                wbSource.VBProject.VBComponents(vbcomponent.Name).Export "C:\temp\displayForm.frm"
                wbDestination.VBProject.VBComponents.Import "C:\temp\displayForm.frm"
        End If
     
     
Next
        Kill "C:\temp\displayForm.frm"
        Kill "C:\temp\displayForm.frx"
     
wbSource.Close
End Sub

Thursday, July 4, 2013

Sending mails without taking Outlook Reference

If your mailId is configured to Outlook Express; following code will send mails of each excel sheet

Sub Mail_every_Worksheet()

    Dim strDate As String
    Dim sh As Worksheet
    Application.ScreenUpdating = False
    For Each sh In ThisWorkbook.Worksheets
        If sh.Range("a1").Value Like "*@*" Then
            sh.Copy
            strDate = Format(Date, "dd-mm-yy") & " " & Format(Time, "h-mm-ss")
            ActiveWorkbook.SaveAs "Part of " & ThisWorkbook.Name _
                                & " " & strDate & ".xls"
            ActiveWorkbook.SendMail ActiveSheet.Range("a1").Value, _
                                    ActiveSheet.Range("b1").Value
            ActiveWorkbook.ChangeFileAccess xlReadOnly
         
            ActiveWorkbook.Close False
        End If
    Next sh
    Application.ScreenUpdating = True

End Sub

Wednesday, July 3, 2013

Calculate Age Using Nested Select Case

Sub calculateAge()
Dim tempdate As Date, sysdate As Date, mydob As Date
Dim y As Integer, m As Integer, d As Integer
mydob = CDate(Application.InputBox("Select your DoB", "DoB", Default:=Format(Date, "mm/dd/yyyy"), Type:=2))
sysdate = Format(Date, "mm/dd/yyyy")
tempdate = DateSerial(Year(Date), Month(mydob), Day(mydob))

Select Case (tempdate > sysdate)

    Case True
                y = Year(sysdate) - Year(mydob) - 1
             
                Select Case Day(mydob) > Day(Date)
                    Case True
                           
                        m = -Month(mydob) - 12 * (tempdate > sysdate) + Month(Date) - 1
                        d = Day(DateSerial(Year(Date), Month(Date), 0)) - Day(mydob) + Day(Date)
                    Case False
                        m = -Month(mydob) - 12 * (tempdate > sysdate) + Month(Date)
                        d = Day(Date) - Day(mydob)
                End Select
    Case Else
                y = Year(sysdate) - Year(mydob)
                Select Case Day(mydob) > Day(Date)
                    Case True
                           
                        m = Month(Date) - Month(mydob) - 1
                        d = Day(DateSerial(Year(Date), Month(Date), 0)) - Day(mydob) + Day(Date)
                    Case False
                        m = Month(Date) - Month(mydob)
                        d = Day(Date) - Day(mydob)
                End Select
       
End Select
MsgBox "Your Age is" & y & " years " & m & "months" & d & "days"
End Sub

Tuesday, July 2, 2013

Remote Connection for SQL Server

Dim rec As New ADODB.Recordset
Dim con As New ADODB.Connection
Dim col As Long, row As Long

con_string = "DRIVER={MySQL ODBC 3.51 Driver};user=internalros;password=internalros;database=TBS;server=206.71.169.000;option=18475"
con.ConnectionString = con_string
con.Open

Wednesday, June 19, 2013

Brief Introduction to Sensitivity Analysis

A technique used to determine how different values of an independent variable will impact a particular dependent variable under a given set of assumptions. This technique is used within specific boundaries that will depend on one or more input variables, such as the effect that changes in interest rates will have on a bond's price.


One of the finest features in Microsoft Excel is sensitivity analysis using either a table (Excel 2003) or 'What-if' in Excel 2007. Suppose you want to start a cybercafe or a restaurant in a new mall. You have done a study on the footfall and the kind of people who visit the mall. You have also found out about the business atmosphere, security and rent or the outright purchase price. You also know the rates in the market that other businesses are charging, let's say, for surfing the net per hour. You then estimate your capital costs like doing up the cybercafe and the price of the computers. You also use the Excel spreadsheet to estimate and calculate the number of people you'll need to run the show and the amount of salaries you'll have to pay. You have also estimated other variable costs like electricity and phone.
From the above data in the Excel worksheet you can calculate your total monthly or yearly costs. Now based on a certain price that you will charge the customers, number of computers and working hours you can calculate your revenue per month or per year. From the data of revenue and income you can easily calculate the profit. Till now everything was easy to implement in Excel.
Now you decide to find out how your profit can vary if you vary the charge per hour or the number of people who will visit your cybercafe or establishment. Of course, you cannot charge what you want but you can get a good estimate by observing what others are charging and what quality of service and environment they are providing.
Arranging all your data properly, click on 'Data' in the ribbon in Microsoft Office 2007 or 'Data' in the menu bar in Excel 2003. In Excel 2007 select 'What-if' analysis and finally 'Data Table...'. In the popup window in the 'Row input cell' type the data that you have input horizontally next to the profit and in the 'column input cell' write down the price and vary it it by 1% 0r 2% so that that Excel can perform an analysis for, say., $0.5 per hour charge for a cybercafe to $1.5 per hour. The horizontal values can be the number of people per hour or month or year that will visit the shop and keep on varying the values by a certain estimated percentage. Click 'OK' and you can see how your profit varies with the number of customers and the price you charge. This is also known as a two variable table because you calculated the changes in your profit based on two parameters - price and number of customers.
Contribution by Dr. Dinesh K Takyar



<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->