Tuesday, July 15, 2014

Pivot Table and VBA

Creating a pivot table
Below Figure shows a pivot table created from the data, along with the PivotTable Field List task bar. This pivot table summarizes the Salary of Employee and month. This pivot table is set up with the following fields:


v  Department: A report filter field in the pivot table.
v  Employee Name: A row field in the pivot table.
v  Month: A column field in the pivot table.
v  Salary: A values field in the pivot table that uses the Sum function.
I turned on the macro recorder before I created this pivot table and specified a new worksheet for the pivot table location. The code that was generated follows:

Sub CreatePivot()
'This Macro is recorded and done necessary changes
    Range(“A1:E28”).Select
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "'Monthwise Salary Register'!R1C1:R28C5", Version:=xlPivotTableVersion12). _
        CreatePivotTable TableDestination:="", TableName:="PivotTable1", _
        DefaultVersion:=xlPivotTableVersion12
    ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(3, 1)
    ActiveSheet.Cells(3, 1).Select
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Department")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Employee Name")
        .Orientation = xlRowField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Month")
        .Orientation = xlColumnField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
        "PivotTable1").PivotFields("Salary"), "Sum of Salary", xlSum
End Sub

Cleaning up the recorded pivot table code
As with most recorded macros, the preceding example isn’t as efficient as it could be. And, as I noted, it’s very likely to generate an error. You can simplify the code to make it more understandable and also to prevent the error. The hand-crafted code that follows generates the same pivot table as the procedure previously listed:
Sub CreatePivotTable()
Dim PTCache As PivotCache
Dim PT As PivotTable
‘ Create the cache
Set PTCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=Range(“A1”).CurrentRegion)
‘ Add a new sheet for the pivot table
Worksheets.Add
‘ Create the pivot table
Set PT = ActiveSheet.PivotTables.Add( _
PivotCache:=PTCache, _
TableDestination:=Range(“A3”))
‘ Specify the fields
With PT
.PivotFields(“Department”).Orientation = xlPageField
.PivotFields(“Month”).Orientation = xlColumnField
.PivotFields(“Employee Name”).Orientation = xlRowField
.PivotFields(“Salary”).Orientation = xlDataField
‘no field captions
.DisplayFieldCaptions = False
' Change the captions
.PivotFields("Sum of Salary").Caption = " Salary  "
.PivotFields("Sum of Incentive").Caption = " Incentive  "
End With
End Sub
The CreatePivotTable procedure is simplified and might be easier to understand, because it declares two object variables: PTCache and PT. A new PivotCache object is created by using the Create method. A worksheet is added, and it becomes the active sheet (the destination for the pivot table). Then a new PivotTable object is created by using the Add method of the PivotTables collection. The last section of the code adds the four fields to the pivot table and specifies their location within it by assigning a value to the Orientation property. The original macro hard-coded both the data range used to create the PivotCache object (‘'Monthwise Salary Register'!R1C1:R28C5’) and the pivot table location (Sheet2 or Sheet3). In the CreatePivotTable procedure, the pivot table is based on the current region surrounding cell A1. This ensures that the macro will continue to work properly if more data is added. Adding the worksheet before the pivot table is created eliminates the need to hard-code the sheet reference. Yet another difference is that the hand-written macro doesn’t specify a pivot table name. Because the PT object variable is created, your code doesn’t ever have to refer to the pivot table by name.
Note: Changes the captions displayed in the pivot table. For example, Sum of Salary is replaced by Salary. Note that the string Salary is preceded by a space. Excel doesn’t allow you to change a caption that corresponds to a field name, so adding a space gets around this restriction.


Monday, July 14, 2014

Stand-alone Progress indicator UserForm

Building the stand-alone progress indicator UserForm
Follow these steps to create the UserForm that will be used to display the progress of your task:
1.       Insert a new UserForm and change its Caption property setting to Progress.
2.       Add a Frame control and name it FrameProgress.
3.       Add a Label control inside the Frame, name it LabelProgress, remove the label’s caption, and make its background color (BackColor property) something that will stand out.
4.       Add another label above the frame to explain what’s going on (optional).
5.       In this example, the label reads, Cell Updation in Progress
6.       Adjust the UserForm and controls so that they look something like below Figure.



Insert the following procedure in the code window for the UserForm. This procedure simply calls a procedure named GenerateRandomNumbers when the UserForm is displayed. This procedure, which is stored in a VBA module, is the actual macro that runs while the progress indicator is displayed.
Private Sub UserForm_Activate()
Call GenerateRandomNumbers
End Sub
The GenerateRandomNumber procedure with additional code keeps track of the progress and stores it in a variable named PctDone.
Sub GenerateRandomNumbers()
‘ Inserts random numbers on the active worksheet
Dim Counter As Long
Const RowMax As Long = 500
Const ColMax As Long = 40
Dim r As Integer, c As Long
Dim PctDone As Double
If TypeName(ActiveSheet) <> “Worksheet” Then Exit Sub
Cells.Clear
Counter = 1
For r = 1 To RowMax
For c = 1 To ColMax
Cells(r, c) = Int(Rnd * 1000)
Counter = Counter + 1
Next c
PctDone = Counter / (RowMax * ColMax)
Call UpdateProgress(PctDone)
Next r
Unload UserForm1
End Sub
The GenerateRandomNumbers procedure contains two loops. Within the inner loop is a call to the UpdateProgress procedure, which takes one argument (the PctDone variable, which represents the progress of the macro). PctDone will contain a value between 0 and 100.
Sub UpdateProgress(Pct)
With UserForm1
.FrameProgress.Caption = Format(Pct, “0%”)
.LabelProgress.Width = Pct * (.FrameProgress.Width - 10)
.Repaint
End With
End Sub
Creating the start-up procedure for a stand-alone progress indicator, all that’s missing is a procedure to display the UserForm. Enter the following procedure in a VBA module:
Sub ShowUserForm()
With UserForm1
.LabelProgress.Width = 0
.LabelProgress.BackColor = ActiveWorkbook.Theme. _
ThemeColorScheme.Colors(msoThemeAccent1)
.Show
End With
End Sub



Saturday, July 5, 2014

Controlling Sheets from UserForm



Controlling Sheet from a UserForm
Below is the example how to create and use ScrollBar controls to allow sheet scrolling and zooming while a dialog box is displayed. Below figure shows how the example dialog box is set up. When the UserForm is displayed, the user can adjust the worksheet’s zoom factor (from 10% to 400%) by using the ScrollBar at the top. The two ScrollBars in the bottom section of the dialog box allow the user to scroll the worksheet horizontally and vertically.
Follow these instructions to create a Zoom and Scroll Dialog Box for your project:
1.             Create your workbook.
2.             Activate the Visual Basic Editor (VBE) and insert a new UserForm into the project.The code in this example assumes that this form is named UserForm1.
3.             Place Scroll Bar controls as shown in below figure on UserForm1. 

Now Set the Properties for above controls.
Control Name
Property
Value
Frame1
Caption
Zoom
ScrollBar1
Name
ScrollBarZoom
Label1
Caption
%
Frame2
Caption
Scroll
Frame3
Caption

ScrollBar2
Name
ScrollBarRows
ScrollBar3
Name
ScrollBarColumns
CommandButton1
Name
CloseButton
CommandButton1
Caption
Close

Press Alt+F11 to activate the VBE. Make sure that the UserForm is displayed and double-click the CommandButton captioned Close.
Add below mention code in Module.
                                                Option Explicit
________________________________________________________________________________________________________________
Private Sub UserForm_Initialize()
    LabelZoom.Caption = ActiveWindow.Zoom & "%"
'   Zoom
    With ScrollBarZoom
        .Min = 10
        .Max = 400
        .SmallChange = 1
        .LargeChange = 10
        .Value = ActiveWindow.Zoom
    End With
'   Horizontally scrolling
    With ScrollBarColumns
        .Min = 1
        .Max = ActiveSheet.UsedRange.Columns.Count
        .Value = ActiveWindow.ScrollColumn
        .LargeChange = 25
        .SmallChange = 1
    End With
'   Vertically scrolling
    With ScrollBarRows
        .Min = 1
        .Max = ActiveSheet.UsedRange.Rows.Count
        .Value = ActiveWindow.ScrollRow
        .LargeChange = 25
        .SmallChange = 1
    End With
End Sub
________________________________________________________________________________________________________________
Private Sub ScrollBarZoom_Change()
    With ActiveWindow
        .Zoom = ScrollBarZoom.Value
        LabelZoom = .Zoom & "%"
        .ScrollColumn = ScrollBarColumns.Value
        .ScrollRow = ScrollBarRows.Value
    End With
End Sub
________________________________________________________________________________________________________________
Private Sub ScrollBarColumns_Change()
ActiveWindow.ScrollColumn = ScrollBarColumns.Value
End Sub
________________________________________________________________________________________________________________
Private Sub ScrollBarRows_Change()
ActiveWindow.ScrollRow = ScrollBarRows.Value
End Sub
________________________________________________________________________________________________________________
Private Sub CloseButton_Click()
    Unload Me
End Sub
Now Add a commandButton on sheet and write down the below mention mecro in general VBA module
Sub ShowForm()
    UserForm1.Show vbModeless
End Sub


Random Number Generator
The below example demonstrates how to animate a Label control. The UserForm shown in below Figure is an interactive Random Number Generator. Two TextBox controls hold the lower and upper values for the random number. A Label control initially displays Eight question marks, but the text is animated to show random numbers when the user clicks the Start button. The Start button changes to a Stop button, and clicking it again stops the animation and displays the random number. Figure below shows the dialog box displaying a random number between 1 and 1,000,000,000.


Please set the property of CommandButton as given below:
Name: StartStopButton
Caption: Start
The code that’s attached to the CommandButton is as follows:
Dim Stopped As Boolean
______________________________________________________________________________________________________________
Private Sub StartStopButton_Click()
    Dim Low As Double, Hi As Double
    If StartStopButton.Caption = "Start" Then
' validate low and hi values
        If Not IsNumeric(TextBox1.Text) Then
            MsgBox "Non-numeric starting value.", vbInformation
            With TextBox1
                .SelStart = 0
                .SelLength = Len(.Text)
                .SetFocus
            End With
            Exit Sub
        End If
        If Not IsNumeric(TextBox2.Text) Then
            MsgBox "Non-numeric ending value.", vbInformation
            With TextBox2
                .SelStart = 0
                .SelLength = Len(.Text)
                .SetFocus
            End With
            Exit Sub
        End If
' Make sure they aren’t in the wrong order
        Low = Application.Min(Val(TextBox1.Text), Val(TextBox2.Text))
        Hi = Application.Max(Val(TextBox1.Text), Val(TextBox2.Text))
' Adjust font size, if necessary
        Select Case Application.Max(Len(TextBox1.Text), Len(TextBox2.Text))
            Case Is < 5: Label1.Font.Size = 72
            Case 5: Label1.Font.Size = 60
            Case 6: Label1.Font.Size = 48
            Case Else: Label1.Font.Size = 36
        End Select
        StartStopButton.Caption = "Stop"
        Stopped = False
        Randomize
        Do Until Stopped
            Label1.Caption = Int((Hi - Low + 1) * Rnd + Low)
            DoEvents ' Causes the animation
        Loop
    Else
        Stopped = True
            StartStopButton.Caption = "Start"
    End If
End Sub

Excel ShortCuts

Heading Short Cut Key Discription The Fundamentals Ctrl + O Open File The Fundamentals Ctrl + N ...