Archive for August, 2008

Displaying A Chart In A Userform

- Selva V Pasupathy, HSBC Global Resourcing

Original Source: John Walkenbach

I was pretty impressed when I came across a page where John has mentioned how you can use userform to show all the chrts in a spreadsheet on a userform and you can move betwee different charts with the help of a commandbutton.

Image showing how your userform with chart will look like

HOW SHOULD I USE THE FOLLOWING CODE

Copy the code below and paste in code section of a userform

Dim ChartNum As Integer

Private Sub UserForm_Initialize()
    ChartNum = 1
    UpdateChart
End Sub

Private Sub PreviousButton_Click()
    If ChartNum = 1 Then ChartNum = 3 Else ChartNum = ChartNum - 1
    UpdateChart
End Sub

Private Sub NextButton_Click()
    If ChartNum = 3 Then ChartNum = 1 Else ChartNum = ChartNum + 1
    UpdateChart
End Sub

Private Sub CloseButton_Click()
    Unload Me
End Sub

Private Sub UpdateChart()
    Set CurrentChart = Sheets("Charts").ChartObjects(ChartNum).Chart
    CurrentChart.Parent.Width = 300
    CurrentChart.Parent.Height = 150

'   Save chart as GIF
    Fname = ThisWorkbook.Path & Application.PathSeparator & "temp.gif"
    CurrentChart.Export FileName:=Fname, FilterName:="GIF"

'   Show the chart
    Image1.Picture = LoadPicture(Fname)
End Sub

Copy the code below and paste in a code module.

Sub ShowChart()
    UserForm1.Show
End Sub

Download the example file from here CLICK HERE

Leave a Comment

Show Status on Userform While executing Code

by Selva V Pasupathy, HSBC Global Resourcing, Hyderabad

Copy the code below and paste it in code module and make sure that you make a userform with two labels with name property as label1 & label2….

Image of the splash screen that you can use to show to your users on your excel application


Option Explicit
Sub Show_userForm()
Userform1.Show
Userform1.Caption = “Splash screen or Status form”
Userform1.Label1.Caption = “Selva V Psaupathy”
Userform1.Label2.Caption = _
“There’s code in this example that shows ” & _
“the form for at least ten seconds in case ” & _
“the initialization procedure runs to quick. ” & _
“If you go through the trouble of showing a ” & _
“splash screen, you’ll want to make sure that ” & _
“it’s visible long enough for the user to see ” & _
“it. “
Application.Wait Now() + TimeValue(“00:00:10″)
Unload Userform1
DoEvents
End Sub

Download an Example File Here CLICK HERE

Leave a Comment

Create HyperlinkObject on Sheet

The following code will help you create a drawing object on the sheet and the location, url, and link name can be customised as user will input those details.

- Selva V Pasupathy, HSBC Global Resourcing, Hyderabad1

Option Explicit
Private myCell As Range
Private myLeft, myTop, myWidth, myHeight
'     ________________________________________________________________________________
'
'     Written by  :        Selva V Pasupathy
'     Description :        The following macro will help you create
'                              a hyperlink object for you and link that
'                              object to url that you want.
'     site        :           http://socko.wordpress.com
'     ________________________________________________________________________________
'

Sub CreateMenuButton_link()
   Set myCell = Application.InputBox( _
    prompt:="Select a cell", Type:=8)

    myLeft = ActiveSheet.Range(myCell.Address).Left
    myTop = Range(myCell.Address).Top
    myWidth = Range(myCell.Address).Width
    myHeight = Range(myCell.Address).Height

    ActiveSheet.Shapes.AddShape( _
            msoShapeFlowchartTerminator, _
            myLeft, _
            myTop, _
            myWidth, _
            myHeight _
            ).Select
    Selection.Characters.Text = Link_Caption
    ActiveSheet.Hyperlinks.Add Anchor:= _
            Selection.ShapeRange.Item(1), _
            Address:=Link_Url
    With Selection
        .Font.Name = "Arial"
        .Font.Size = 8
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .ReadingOrder = xlContext
        .Orientation = xlHorizontal
        .AutoSize = False
    End With

    Selection.ShapeRange.Fill.Visible = msoFalse
    Selection.ShapeRange.Line.Visible = msoFalse
    On Error Resume Next
    ActiveSheet.Cells(1, 1).Select
End Sub
'_____________________________________________________________________________
Function Link_Caption() As String
   Link_Caption = Application.InputBox("Enter the caption for the link")
End Function
'_____________________________________________________________________________
Function Link_Url() As String
Url_Again:
   Link_Url = Application.InputBox("Enter url for the link")
   If Left(UCase$(Link_Url), 7)  "HTTP://" Then
      MsgBox "Plesae enter a valid URL that starts with <> "
      GoTo Url_Again
   End If
End Function

Leave a Comment

Code to Create FileHandle on Users’ Desktop

by Selva V Pasupathy, HSBC Global Resourcing, Hyderabad

While at my workplace, I came across a situation when to get input from users, we had to create a file but without giving physical access to the users to that file. The code below helps to create a vbs file on desktop and you may ask the users to click on the vbs file to open the workbook and they can start the input through userform. I set application visible property as false, so user will be able to see only userform, and it will make you get a feel of a standalone application. I am not sure whether this will be a successful attempt, but there is nothing wrong in giving this a try.

Sub Create_Opener()
Dim fso, txt As Object
Dim myFile As String
Dim i As Integer
  Call Get_CodeLines
  myFile = File_on_DeskTop
  Set fso = CreateObject("scripting.filesystemobject")
  Set txt = fso.createtextfile(myFile, 2, True)
  For i = 1 To 7
    txt.WriteLine CodeLines(i)
  Next i
  txt.Close
  Set txt = Nothing
  Set fso = Nothing
  MsgBox "A Handle for this File has been " & _
        "successfully created on desktop " & _
        "with filename " & vbNewLine & _
        File_on_DeskTop
End Sub

Private Sub Get_CodeLines()
CodeLines(1) = "'  The following lines of " & _
                  the codes act as an Opener to this file"
CodeLines(2) = "dim xlApp"
CodeLines(3) = "dim myFile"
CodeLines(4) = "myFile=" & Chr(34) & ThisWorkbook.Path & "\" & _
                  ThisWorkbook.Name & Chr(34)
CodeLines(5) = "set xlApp= CreateObject(" & Chr(34) & _
                 "excel.application" & Chr(34) & ")"
CodeLines(6) = "xlApp.workbooks.open(myFile)"
CodeLines(7) = "xlApp.VISIBLE=false"
End Sub

Function File_on_DeskTop() As String
File_on_DeskTop = CreateObject("WScript.Shell"). _
                   SpecialFolders("Desktop") & _
                   "\" & "DataInput.vbs"
End Function

Leave a Comment

Find and Replace in VBA

- Selva V Pasupathy, HSBC Global Resourcing, Hyderabad

'____________________________________________________________
'   Author :     Selva V Pasupathy
'   Description:  The following macro code helps you find and replace
'                 by the use of vba
'____________________________________________________________
Sub Find_Replace(ByVal txtFind As String, ByVal txtReplace As String)
If Selection.Cells.Count = 1 Then
    ActiveSheet.Cells.Replace What:=txtFind, _
                    Replacement:=txtReplace, _
                    LookAt:=xlPart, _
                    SearchOrder:=xlByRows, _
                    MatchCase:=False, _
                    SearchFormat:=False, _
                    ReplaceFormat:=False
Else
    Selection.Replace What:=txtFind, _
                    Replacement:=txtReplace, _
                    LookAt:=xlPart, _
                    SearchOrder:=xlByRows, _
                    MatchCase:=False, _
                    SearchFormat:=False, _
                    ReplaceFormat:=False
End If
End Sub

Sub Test_Run()
  ' To find "2007" and replace with "2008" you can use following statement
  Call Find_Replace("2007", "2008")
End Sub

Leave a Comment

Convert Numbers to Words

I came across the following codes at www.dailydoseofexcel.com. This code builds a UDF (User defined function) that can be used as a Excel Worksheet function, for e.g., Write “=ToWords(10284)” in a cell and enter, Excel calculates and returns a string “Ten Thousand Two Hundred Eighty Four”…
- Selva V Pasupathy, HSBC Global Resourcing, Hyderabad

Attribute VB_Name = "Module1"
Option Explicit
'  ____________________________________________________________
Public Function UnitString(ByVal Ind As Integer) As String
   Dim ToStr As Variant
   ToStr = Array("Zero", "One", "Two", _
                "Three", "Four", "Five", _
                "Six", "Seven", "Eight", _
                "Nine", "Ten", "Eleven", _
                "Tweleve", "Thirteen", _
                "Fourteen", "Fifteen", _
               "Sixteen", "Seventeen", _
               "Eighteen", "Nineteen", "Twenty")
   UnitString = ToStr(Ind)
End Function
'  ____________________________________________________________
Public Function TenString( _
                ByVal Ind As Integer _
                ) As String
   Dim ToStr As Variant
   ToStr = Array("Ten", "Twenty", "Thirty", _
            "Fourty", "Fifty", "Sixty", _
            "Seventy", "Eighty", "Ninety")
   TenString = ToStr(Ind)
End Function
'  ____________________________________________________________
Public Function PlaceString( _
            ByVal Ind As Integer _
            ) As String
   Dim ToStr As Variant
   ToStr = Array("Unit", "Tenth", "Hundred", _
                  "Thousand", "Lakh", "Crore", _
                  "Hundred" _
                 )
   PlaceString = ToStr(Ind)

End Function
'  ____________________________________________________________
Public Function ToWords(ByVal No As Long) _
                    As String
   Dim ToStr As String
   'Dim No As Long
   Dim Value As Long
   Dim Divisor As Long
   Dim i As Long

   Divisor = 1000000000

   i = 6
   Do While (No >= 1000)
      Value = Int(No / Divisor)
      No = No Mod Divisor
      Divisor = Int(Divisor / 100)
      If (Value <> 0) Then
         ToStr = ToStr & NumberToWords100(Value) _
                    & " " & PlaceString(i) + " "
      End If
      i = i - 1
   Loop

   Value = Int(No / 100)
   No = No Mod 100

   If (Value <> 0) Then
      ToStr = ToStr & NumberToWords100(Value) _
                & " " & PlaceString(i) + " "
   End If
   i = i - 1

   If No <> 0 Then
      ToStr = ToStr & NumberToWords100(No)
   End If
   ToWords = Trim(ToStr)
End Function
'  ____________________________________________________________
Private Function NumberToWords100( _
                ByVal No As Integer _
                ) As String
   Dim ToStr As String
   Dim Ten As Integer, Unit As Integer

   If (No <= 20) Then
      NumberToWords100 = UnitString(No)
      Exit Function
   End If
   No = No Mod 100
   Ten = Int(No / 10)
   No = No Mod 10
   Unit = No
   If (Ten >= 2) Then
      ToStr = ToStr & " " & TenString(Ten - 1)
      If (Unit > 0) Then
         ToStr = ToStr & " " & UnitString(Unit)
      End If
   ElseIf (Ten > 0) Then
      ToStr = ToStr & " " & UnitString((Ten * 10) + Unit)
   ElseIf (Unit > 0) Then
      ToStr = ToStr & " " & UnitString(Unit)
   End If

   NumberToWords100 = Trim(ToStr)
End Function
'  ____________________________________________________________
Private Sub Form_Load()
     MsgBox ToWords(10023)
End Sub

Leave a Comment

Sort WorkSheets by Name

Sometime while working on some data in spreadsheets, you might want to sort the sheets by their name.
When you have so many sheets that you do not want to sit and sort it manually, you may use the following code to get it done by VBA for you.
- Selva V Pasupathy, HSBC Global Resourcing, Hyderabad

Option Explicit
Private i, j, k As Integer
Private N As Integer
Private M As Integer
Private FirstWSToSort, LastWSToSort As Integer
Private SortDescending As Boolean
Private AscDesc

Private Sub SortWorksheets()
'  _________________________________________________________________
'  Code Starts Here
'  Gets the permission from the user to sort the worksheets
'  Written By :   Selva V Pasupathy
'                 HSBC Global Resourcing
'                 Hyderabad
   AscDesc = MsgBox(prompt:="Sort worksheets in ascending order?", _
                             Title:="Sort Order", _
                             Buttons:=vbYesNoCancel)
'  _________________________________________________________________
'  If the user clicks "YES" then it sorts in ascending order or else
'  the sorting is done in descending order

   If AscDesc = vbYes Then
      SortDescending = False
   ElseIf AscDesc = vbNo Then
      SortDescending = True
   Else
      Exit Sub
   End If

'  _________________________________________________________________

   If ActiveWindow.SelectedSheets.Count = 1 Then
      FirstWSToSort = 1
      LastWSToSort = Worksheets.Count
   Else
      With ActiveWindow.SelectedSheets
         For N = 2 To .Count
            If .Item(N - 1).Index  .Item(N).Index - 1 Then
               MsgBox "You cannot sort non-adjacent sheets"
               Exit Sub
            End If
         Next N
   FirstWSToSort = .Item(1).Index
   LastWSToSort = .Item(.Count).Index
   End With
   End If
'  _________________________________________________________________

   For M = FirstWSToSort To LastWSToSort
      For N = M To LastWSToSort
         If SortDescending = True Then
            If UCase(Worksheets(N).Name) > UCase(Worksheets(M).Name) Then
               Worksheets(N).Move Before:=Worksheets(M)
            End If
         Else
            If UCase(Worksheets(N).Name) < UCase(Worksheets(M).Name) Then
               Worksheets(N).Move Before:=Worksheets(M)
         End If
      End If
      Next N
   Next M
'  _________________________________________________________________
'  Code Ends here
End Sub

Leave a Comment

Older Posts »