Archive for October, 2008

Userform Resizer – VBA

- Selva V Pasupathy, HSBC Global Resourcing, Hyderabad 1

Copy following code and paste in a userform module to add form resizer.
Original Source: Andy Pope

Option Explicit
Private Const MResizer = "ResizeGrab"
Private WithEvents m_objResizer As MSForms.Label
Private m_sngLeftResizePos As Single
Private m_sngTopResizePos As Single
Private m_blnResizing As Single
'________________________________________
Private Sub UserForm_Initialize()
    m_AddResizer
End Sub
'________________________________________
Private Sub UserForm_Terminate()
    Me.Controls.Remove MResizer
End Sub
'________________________________________
Private Sub m_AddResizer()
'
'add resizing control to bottomright corner of form
'
Set m_objResizer = Me.Controls.Add _
    ("Forms.label.1", MResizer, True)
With m_objResizer
  With .Font
      .Name = "Marlett"
      .Charset = 2
      .Size = 14
      .Bold = True
  End With
  .BackStyle = fmBackStyleTransparent
  .AutoSize = True
  .BorderStyle = fmBorderStyleNone
  .Caption = "o"
  .MousePointer = fmMousePointerSizeNWSE
  .ForeColor = RGB(100, 100, 100)
  .ZOrder
  .Top = Me.InsideHeight - .Height
  .Left = Me.InsideWidth - .Width
End With
End Sub
'________________________________________
Private Sub m_objResizer_MouseDown( _
            ByVal Button As Integer, _
            ByVal Shift As Integer, _
            ByVal X As Single, _
            ByVal Y As Single)
    If Button = 1 Then
        m_sngLeftResizePos = X
        m_sngTopResizePos = Y
        m_blnResizing = True
    End If
End Sub
'________________________________________
Private Sub m_objResizer_MouseMove( _
            ByVal Button As Integer, _
            ByVal Shift As Integer, _
            ByVal X As Single, _
            ByVal Y As Single)
  If Button = 1 Then
    With m_objResizer
      .Move .Left + X _
            - m_sngLeftResizePos, _
            .Top + Y - m_sngTopResizePos
      Me.Width = Me.Width + _
            X - m_sngLeftResizePos
      Me.Height = Me.Height + Y - m_sngTopResizePos
      .Left = Me.InsideWidth - .Width
      .Top = Me.InsideHeight - .Height
    End With
  End If
End Sub
'________________________________________
Private Sub m_objResizer_MouseUp( _
            ByVal Button As Integer, _
            ByVal Shift As Integer, _
            ByVal X As Single, _
            ByVal Y As Single)
    If Button = 1 Then
        m_blnResizing = False
    End If
End Sub

Leave a Comment

Sorting Text with Worksheet Formula

- Selva V Pasupathy, HSBC Global Resourcing, Hyderabad1

I was trying to see if text sorting can be done with the help of worksheet formula. I tried and I think I am successful to some extent. Sorting text is such a day to day activity, it surprises me why Microsoft hasn’t provided a worksheet formula for doing it.

I know that you always had a choice of autofilter but it requires manual steps. While trying to wrok with countif() formula, I came across with following worksheet array formula which sorts the array. “myArray” is the name of the array this worksheet formula would sort. Please remember, you need to use it as an array formula, i.e., select the whole area where you want the output, and then type your formula and while entering please hold on to ctrl+shift and then press enter.

=INDEX(myarray,MATCH(SMALL(COUNTIF(myarray,”<=”&myarray),ROW(myarray)-ROW(INDEX(myarray,ROWS(myarray),0))+ROWS(myarray)),COUNTIF(myarray,”<=”&myarray),0),0)

Leave a Comment

Show Formula in a cell

- Selva V Pasupathy, HSBC Global Resourcing, Hyderabad1
Today someone asked me how to display a formula in a cell. What a silly question? It’s Easy, just enter an apostrophe (‘) in front of the formula and one can see the formula. Oh No! But if you don’t want to disturb the cell where the formula resides? Oh! So you want to show the result of the formula as well… Yes! at the same time a user should be able to see the formula as it is in a different cell. Isn’t it simple? Enter into the cell, copy the formula starting “=” and till the end and paste it in a different cell and add apostrophe in front of it. But what if, you have thousands of formula to show? Now, there is something to work on…. Let me share what i tried sometime back and i think this should work!

Open a new Excel Workbook, press alt+F11, if you dont see a small window with the names of the sheets in a workbook, click ctrl+R… Now you will be able to see a window with all the workbooks and its contents like sheets, userforms, & codemodules. Right click the new workbook project and choose insert –> module… Now double click the module that has just been inserted… Do you see code window? If you are not, press F7 key and you will see the code module. Now in this module, copy the following code and paste it.


Option Explicit
Public Function ShowFormula(ByRef iCell As Range)
  If iCell.HasFormula = True Then
    ShowFormula = iCell.Formula
  Else
      ShowFormula = ""
  End If
End Function

Now, you are ready to show the user the formula as it is wherever you want. just type "=showformula(" and then the reference to a cell to display the formula of that particular cell.

eg., =showformula(e6)

To download an example workbook, CLICK HERE

Leave a Comment

Create UserForm at Runtime using Code

- Selva V Pasupathy, HSBC Global Resourcing, Hyderabad

The following code, I found at www.eng-tips.com, is the process to create a UserForm dynamically using a macro in VBA.

  1. From the VBE (open Excel and hit ALT+F11)you need to set a reference to the extensibility add-in. To do this, go to Tools/References and find the add-in Micrsoft
    Visual Basic for Applications Extensibility
  2. Create a macro module in the project file. To do this, right-click on VBAProject and
    select Insert->Module.
  3. Right-click the module and select View Code.
  4. Paste this code into the window:

Option Explicit

Sub MakeForm()
  Dim TempForm As Object ' VBComponent
  Dim FormName As String
  Dim NewButton As MSForms.CommandButton
  Dim TextLocation As Integer
  '   ** Additional variable
  Dim X As Integer

'Locks Excel spreadsheet and speeds up form processing
  Application.VBE.MainWindow.Visible = False
  Application.ScreenUpdating = False

'Create the UserForm
  Set TempForm = ThisWorkbook.VBProject.VBComponents. _
            Add(vbext_ct_MSForm)

'Set Properties for TempForm
  With TempForm
    .Properties("Caption") = _
        "HSBC Global Resourcing "
    .Properties("Width") = 400
    .Properties("Height") = 300
  End With
  FormName = TempForm.Name

'Add a CommandButton
  Set NewButton = TempForm.Designer.Controls _
    .Add("forms.CommandButton.1")
  With NewButton
    .Caption = "Click Me"
    .Width = 60
    .Height = 24
    .Left = TempForm.Properties("InsideWidth") - 2 - 60
    .Top = TempForm.Properties("insideheight") - 2 - 24
  End With
'Add an event-hander sub for the CommandButton
  With TempForm.CodeModule
'** Delete This: TextLocation = _
      .CreateEventProc("Click","CommandButton1")

'** Add/change next 5 lines
'This code adds the commands/event handlers to the form
    X = .CountOfLines
    .InsertLines X + 1, _
          "Sub CommandButton1_Click()"
    .InsertLines X + 2, _
          "MsgBox ""Hello!"""
    .InsertLines X + 3, "Unload Me"
    .InsertLines X + 4, "End Sub"
  End With

  '   Show the form
  VBA.UserForms.Add(FormName).Show
  '
  '   Delete the form
  ThisWorkbook.VBProject.VBComponents. _
          Remove VBComponent:=TempForm
End Sub


VBE Programming – www.vbaexpress.com

Leave a Comment

Create LogFile for Workbook Open

- Selva V Pasupathy, HSBC Global Resourcing, Hyderabad

The following code will creqate log entry each time a workbook is opened.

' Original Source:	johnske, www.vbaexpress.com
'__________________________________________________
'	CODE FOR MODULE1
'__________________________________________________

Option Explicit 

Public Function LogInformation(LogMessage$)
    On Error Goto MakeFolder
Entry:
  Open Thisworkbook.path & "\MyLogFiles\" _
	& Left(ThisWorkbook.Name, _
  Len(ThisWorkbook.Name) - 4) & _
  " Log.Log" For Append As #1
  Print #1, LogMessage
  Close #1
  Exit Function
MakeFolder:
  MkDir Thisworkbook.path & "\MyLogFiles\"
  Resume Entry
End Function
'__________________________________________________
'__________________________________________________

'__________________________________________________
'	CODE FOR THISWORKBOOK MODULE
'__________________________________________________

Option Explicit 

Private Sub Workbook_Open()
  LogInformation "Opened by " & _
         Application.UserName & _
         " " & Format(Now, "dd mmm yyyy hh:mm:ss")
End Sub
'__________________________________________________
'__________________________________________________

Leave a Comment

Export Chart as Image

- Selva V Pasupathy, HSBC Global Resourcing, Hyderabad


The following code will help you export a selected chart as an image and will be saved in the same folder as the workbook.

Copy the following code and paste it in a code module

'__________________________________________________
'**************************************************
'*
'* MODULE NAME:     <<>>
'* AUTHOR:          Selva V Pasupathy,
'*                  HSBC Global Resourcing, Hyderabad
'* CONTACT:         socko@rediffmail.com
'__________________________________________________
Option Explicit
Sub Export_Chart2GIF()
'   Before exporting a chart need to select one
  Const PathSEP = "/"
  Const sPicType$ = ".gif"
  Dim sChartname
  Dim myPath
  Dim thisbook
  Dim myChart As ChartObject

  On Error Resume Next
'   If there is no chart object on this sheet,
'   let the user know about this
  Set myChart = ActiveSheet.ChartObjects(1)
  If myChart Is Nothing Then
    MsgBox "There are no charts on this sheet", 0
    Exit Sub
  End If

  If ActiveChart Is Nothing Then
    MsgBox "Please select a chart before exporting ", 0
    Exit Sub
  End If

ProcStart:
sChartname = Application.InputBox("Please Specify a name " & _
              "for the exported chart" & vbCr & _
              "There is no default name available" & vbCr & _
              "The chart will be saved in the same " & _
              "folder as this file", "Chart Export", "")

'   User presses "OK" without entering a name
  If sChartname = Empty Then
    MsgBox "You have not entered a " & _
        "name for this chart", _
        , "Invalid Entry"
    GoTo ProcStart
  End If

'   Test for Cancel button
    If sChartname = "False" Then
        Exit Sub
    End If

'   If a name was given, chart is exported
'   as a picture in the same
'   folder location as their current file
  thisbook = ActiveWorkbook.Path
  myPath = thisbook & PathSEP & _
        sChartname & sPicType
  ActiveChart.Export Filename:= _
      myPath, FilterName:="GIF"
End Sub


Leave a Comment

Creating a watermark in Excel with VBA

- Selva V Pasupathy, HSBC Global Resourcing, Hyderabad

    ActiveSheet.Shapes.AddTextEffect(PresetTextEffect:=2, _
              Text:="DRAFT", FontName:="Arial Black", FontSize:=36, _
              FontBold:=False, FontItalic:=False, Left:=50, Top:=150).Select

    With Selection.ShapeRange
         .ScaleHeight 1.23, False
         .ScaleWidth 1.6, False

         ' Solid or no color
         .Fill.Visible = False                     ' Hide any colors
         .Fill.Transparency = 0.5                  ' semi-transparent

         ' Outline
         .Line.Weight = 0.75                       ' Line weight outline (1.25 is darker)
         .Line.DashStyle = 1                       ' Use a solid line
         .Line.Style = 1                           ' use continuous, I am guessing
         .Line.Transparency = 0#                   ' Make the line semi-transparent
         .Line.Visible = True                      ' show the line
         .Line.ForeColor.SchemeColor = 12          ' line color is blue
         .Line.BackColor.RGB = RGB(255, 255, 255)

         .Height = 80                              ' expand the height of the text
         .Width = 400                              ' expand the width of the text
    End With

Leave a Comment

Older Posts »