Showing posts with label Macro. Show all posts
Showing posts with label Macro. Show all posts

March 31, 2017

Change currency (Rupees and Euros) to English text in Microsoft Excel

Hi Friends,

Today I'll discussing about converting currency (Rupees and Euros) to textual representation which I have found by googling and updated to cover 2 currencies.

Source

The VBA Macro code is available on my public GIST
ConvertCurrencyToEnglish.txt

Usage


  • Add this in your excel module using developer options
  • Two functions
  • ConvertRupeesToEnglish - Which converts numeric data to rupees with pre-pending "Rupees " and appending " Only"
  • ConvertEurosToEnglish - Which converts numeric data to rupees with pre-pending "Euros " and appending " Only"
  • Note: If number has precisioin, it will add "Paise" and "Cent" to respective currency.
Please send your review and feedback to psrdotcom@gmail.com

March 21, 2012

Excel Macro to Split Cell Data with Delimiter and Copy in other Columns

Hi all,
Today I have written one more small macro in Excel to split the data with the delimiter and copy to the columns which are beside to the data.


Sub splitdata()

Dim data As String
Dim values As Variant
Dim i As Long

    Set DataRange = Range("A1").CurrentRegion
    Range("A1").Select
    For Each cell In Range("A1").CurrentRegion
       
        'Getting text from the cell
        data = cell.Text
       
        'MsgBox ("Data :" & data)
       
        'Gettings Values
        values = split(data, ",")
       
        For i = 0 To UBound(values)
            'MsgBox ("Value is: " & values(i))
            'Splitting to other columns
            cell.Offset(0, i + 1).Value = values(i)

        Next i

    Next cell  
 

'Autofit the content to the column
    Cells.EntireColumn.AutoFit
   
End Sub


Please send your feedback and comments to psrdotcom@gmail.com

December 16, 2010

Word 2007 Macro for auto-formatting the content in each line

Description:
Word macro for iterating entire document line by line and edit the content

Sometimes we may need to format the string with quotes and comma. I have been facing this for sometime. If the content is less, it will ok to go to the starting position of the string and type " or ' and go to the end of the string and type " or ' and appending , at the end of every line, etc.

Example:

Input:
abc
def
ghi

Output:
'abc',
'def',
'ghi'

What you need to do, Please follow the below steps.

1) Just download the macro code below and paste in word visual basic editor or create a macro with this code
2) Edit the code according to your convience either to use " or '
3) Save the code and run the macro
4) It will confirm with the user whether the user copied the data or not.
5) Wait for user to copy the content
6) Automatically format and copy the formatted content
7) Displays a message to user saying that "Data is formatted and copied. You can paste the content in required application"

Its very simple and useful. Try this.
Macro Code:
sub FormatData()
Dim lineCount, i As Integer
Dim oWB As Document
Dim decision As Variant


Set oWB = Documents.Add
oWB.Activate


decision = MsgBox("Please copy the content and then click on OK", vbOKCancel, "Decision")


Select Case decision
Case vbOK 'If user agrees proceed further by pasting the content
'Paste the content from clipboard which is copied
Selection.PasteSpecial DataType:=wdPasteText, Placement:=wdInLine
Case vbCancel 'If user clicks on cancel then exit
GoTo last
Case Else
GoTo last
End Select


'got the first line
Selection.GoTo What:=wdGoToLine, Which:=wdGoToFirst


'Formatting the data


'Counting number of lines
lineCount = oWB.BuiltInDocumentProperties("Number of lines").Value


For i = 1 To lineCount
'Quoting the line
Selection.HomeKey Unit:=wdLine
Selection.TypeText Text:="'"
Selection.EndKey Unit:=wdLine
Selection.TypeText Text:="'"


'Appending , till linecount-1 line
If i < lineCount Then
Selection.TypeText Text:=","
End If
'Moving to next line
Selection.MoveDown Unit:=wdLine, Count:=1
Next i


'copy the content in the document
ActiveDocument.Content.Copy


ActiveDocument.Close savechanges:=wdDoNotSaveChanges


'Informing user that he/she can paste the data where ever required
MsgBox ("Content is formatted and copied, Please paste the data in the required application")


last:


End Sub


'Help:
'go to the beginning
'Selection.HomeKey Unit:=wdStory


'go to the end
'Selection.EndKey Unit:=wdStory


'got the first line
'Selection.GoTo What:=wdGoToLine, Which:=wdGoToFirst


'go to the last line
'Selection.GoTo What:=wdGoToLine, Which:=wdGoToLast


'If you just want to select a line, you can also do something like this :
'Selection.HomeKey Unit:=wdLine
'Selection.EndKey Unit:=wdLine, Extend:=wdExtend


'Count number of words
'sNumberofwords = oWB.BuiltInDocumentProperties("Number of words").Value

For any further queries, please send mail to psrdotcom@gmail.com

November 24, 2010

Copy Paste Pl/Sql developer queried table data and Auto Format the content

Paste and Auto-format Table records in Excel

While taking backup of the tables, we are doing the following steps.
1.       Executing the query
2.       Copying the content from pl/sql developer
3.       Opening excel and paste the copying content
4.       If we want multiple tables to take backup, we need select next sheet and paste the content
5.       If we need more than 3 sheets we are adding new sheets.
6.       Just copying content from the pl/sql developer doesn’t finish our work, am I right?
7.       We need to format the data too.

So, I just tried to create one auto-formatter which will paste the data and auto-format the data.

Please download the attachment and unzip the file.

After opening the excel file, do the following.

a) Please change the macro settings to "Disable all macros with notification"
     Note: To see how you can change the macro settings, please see the following link


b) Please click on the "User Friendly Formatter" button and follow the procedure.
c) It will open a new file and asks you to save the file.
d) Copy the content from pl/sql developer, when it displayed the following pop-up window.


e) The data will be auto formatted and then asks user for continuation by displaying the following window.

f) If user wants to continue, user can click “Yes” button, and the next sheet will be auto-selected.
g) Goto step (d)
h) When your clicks on “No” button, the file will be autosaved.


Please see the macro code and change according to your requirements.

Source Code:



Public Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function EmptyClipboard Lib "user32" () As Long
Public Declare Function CloseClipboard Lib "user32" () As Long

Sub CreateNewWorkbook()
    Dim oWorkbook As Workbook
    Dim wbName, fileSaveName As String
    Dim sCount, decision, copied, sIndex As Integer
    Dim oSheet As Worksheet
    
    'On Error GoTo errHandler
    
    Set oWorkbook = Workbooks.Add
    
    Save_ActiveWorkbook
    
    sCount = ActiveWorkbook.Sheets.Count
    'MsgBox (sCount)
    
    If MsgBox("Please copy the content and then click on OK", vbOKOnly, "Decision") = vbOK Then
        CopyAndFormatData
    End If
    
    sIndex = 1
    
askUser:
    decision = MsgBox("Do you want to continue with the next sheet?", _
    vbYesNo, "Decision")
  
'If user wants to continue
    If decision = vbYes Then
    
        'Asking user to copy the data first
        copied = MsgBox("Please copy the content and then click on OK", vbOKCancel, "Decision")
        
        'If user copied data
        If copied = vbOK Then
        
            'Selecting next sheet
            If sIndex < 3 Then
                Sheets(sIndex + 1).Select
                sIndex = sIndex + 1
            'ElseIf sIndex = 3 Then
            '    Sheets(sIndex).Select
            'Adding additional sheet from sheet4
            ElseIf sIndex >= 3 Then
                    Set oSheet = Worksheets.Add(After:=Worksheets(Worksheets.Count))
            End If
            
            'copying and formatting data
            CopyAndFormatData
            
        ElseIf copied = vbCancel Then
            'Confirm the user whether user want to quit and save file
            If MsgBox("Do you want to remain in the same sheet", vbOKOnly, "Save File") = vbOK Then
                Sheets(ActiveSheet.Index).Select
            End If
        End If
        GoTo askUser
    End If
    

savingFile:
    ActiveWorkbook.Save
    
End Sub

Sub CopyAndFormatData()

'If Range("A1").Font.Bold = True Then
    ActiveSheet.Range("A1").Select
    
    On Error Resume Next
    ActiveSheet.PasteSpecial Format:=Text, Link:=False, DisplayAsIcon:=False
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    
    If Range("A1").Value Is Null Then
        Range("A:A").Delete
    End If
    
    'select header row and make it as bold
    Cells(1, 1).EntireRow.Select
    Selection.Font.Bold = True
    
    'Autofit column width
    Range("A1").CurrentRegion.Select
    Selection.Columns.AutoFit
    
ClearClipboard

End Sub

Sub ClearClipboard()
    OpenClipboard (0&)
    EmptyClipboard
    CloseClipboard
End Sub
Sub Save_ActiveWorkbook()
'Working in Excel 2000-2010
    Dim fname As Variant
    Dim NewWb As Workbook
    Dim FileFormatValue As Long

    'Check the Excel version
    If Val(Application.Version) < 9 Then Exit Sub
    If Val(Application.Version) < 12 Then

        'Only choice in the "Save as type" dropdown is Excel files(xls)
        'because the Excel version is 2000-2003
        fname = Application.GetSaveAsFilename(InitialFileName:="", _
        filefilter:="Excel Files (*.xls), *.xls", _
        Title:="Save As the Workbook as ")

        If fname <> False Then
            'Copy the ActiveSheet to new workbook
            ActiveSheet.Copy
            Set NewWb = ActiveWorkbook

            'We use the 2000-2003 format xlWorkbookNormal here to save as xls
            NewWb.SaveAs fname, FileFormat:=-4143, CreateBackup:=False
            NewWb.Close False
            Set NewWb = Nothing

        End If
    Else
        'Give the user the choice to save in 2000-2003 format or in one of the
        'new formats. Use the "Save as type" dropdown to make a choice,Default =
        'Excel Macro Enabled Workbook. You can add or remove formats to/from the list
        
        fname = Application.GetSaveAsFilename(InitialFileName:="", filefilter:= _
        " Excel Macro Free Workbook (*.xlsx), *.xlsx," & _
        " Excel Macro Enabled Workbook (*.xlsm), *.xlsm," & _
        " Excel 2000-2003 Workbook (*.xls), *.xls," & _
        " Excel Binary Workbook (*.xlsb), *.xlsb", _
        FilterIndex:=1, Title:="Save As the Workbook as ")

        'Find the correct FileFormat that match the choice in the "Save as type" list
        If fname <> False Then
            Select Case LCase(Right(fname, Len(fname) - InStrRev(fname, ".", , 1)))
            Case "xls": FileFormatValue = 56
            Case "xlsx": FileFormatValue = 51
            Case "xlsm": FileFormatValue = 52
            Case "xlsb": FileFormatValue = 50
            Case Else: FileFormatValue = 0
            End Select

            'Now we can create/Save the file with the xlFileFormat parameter
            'value that match the file extension
            If FileFormatValue = 0 Then
                MsgBox "Sorry, unknown file extension"
            Else
                'Copies the ActiveSheet to new workbook
                Set NewWb = ActiveWorkbook

                'Save the file in the format you choose in the "Save as type" dropdown
                NewWb.SaveAs fname, FileFormat:= _
                             FileFormatValue, CreateBackup:=False

            End If
        End If
    End If
End Sub


Note: Please send your feedback and comments

September 09, 2010

Excel VBA: Multi-selection Listbox using pop-up window to display column values

Description:

We have following excel sheet with the two columns Names and Requirednames.
Names column has all the names
Required Names column should have some selected name(s)

Names Required Names
ABC,DEF,GHI  
   
PSR,DOT,COM  


What we can do other than copy and paste?

We can create a pop-up window which will display all the names by using list box and we can select the required names from that list box.

Procedure:
1.Go to Developer Tab -> Design Mode
2.Click on Insert and click -> CommandButton
3.Drag the cursor to create a button
4.Rename button with name "Show Names" in sheet
5.Assign a macro to it with name "DisplayNames"
6.Open VBEditor
7.Goto Insert -> User Form
8.We will get one form, Design the form as follows
9.
UserForm1



10.Change Caption to "Names Selection" in Form Properties
11.Change Caption to "List of Names" in Frame Properties
12.Change Caption to "Select the names and click OK" in Lable Properties
13.Change Name to "lbEmp", MultiSelect to 1-fmMultiSelectMulti in ListBox Properties
14.Change Name to "submit" and Caption to "OK" in Button1 Properties
15.Change Name to "close" and Caption to "Close" in Button2 Properties
16.Change Name to "reset" and Caption to "Reset" in Button3 Properties
17.Select Excel window, Go to Macros and Select "DisplayNames" macro(which is already assigned to the Button in Sheet), Click on Edit
18.Write the following code:
Dim rngEmp() As String
Dim emps As String
Dim i As Integer

Application.Sheets("Sheet1").Select
emps = ActiveCell.Offset(0, -1).Value
If emps = "" Then
MsgBox ("No Name(s) Available")
End
Else
rngEmp = Split(emps, ",")
End If

For i = LBound(rngEmp) To UBound(rngEmp)
UserForm1.lbEmp.AddItem rngEmp(i)
Next

UserForm1.Show
19.
Double-click on the UserForm1 from the Forms directory in VBEditor
20.
Double-click on any one of the button on the form to view code(shortcut: F7)
21.
Select all the code and delete it. Paste the following code

Private Sub close_Click()
Unload UserForm1
End Sub
Private Sub reset_Click()
UserForm1.lbEmp.Clear
End Sub
Private Sub submit_Click()
Dim emps As String
emps = ""
For i = 0 To UserForm1.lbEmp.ListCount - 1
If lbEmp.Selected(i) = True Then
'MsgBox lbEmp.List(i)
If emps = "" Then
emps = lbEmp.List(i)
ElseIf emps <> "" Then
emps = emps & "," & lbEmp.List(i)
End If
End If
Next i
ActiveCell.Value = emps
End Sub
21.Save and Close the VBEditor. Goto Excel sheet
22.Select the right adjacent Cell say B1 Cell
23.Click the button which we created on the sheet
24.Select the name(s) and Click Ok to see values in the selected cell
25.We can select Multiple Names at a time which will display names with the delimiter "," in the selected cell
26.If A's cell doesn't contain any value then it will display a message "No Name(s) Available"
27.We have to select Close to close the pop-up window
28.We can select Clear to clear list and then select close to cancel

You can see the sample output

Names Required Names
ABC,DEF,GHI ABC
   
PSR,DOT,COM PSR,COM

Note:
For any further queries and/or suggestions please contact psrdotcom@gmail.com

August 31, 2010

Finding Date Difference in Excel and by using Macro

Date Difference in Excel


We can use Days360 function to find the days difference

Syntax: 
=days360(startdate, enddate, true)

Example:

A1 B1 C1
3/20/2010 3/26/2010

Type the any one of the following in C1 

To find the days difference, use
 =days360(A1,B1,True)
=B1-A1


To find months difference, use Month(B1)-Month(A1)


To find years difference, use Year(B1)-Year(A1)

Then the sheet A1 and B1 contains the following values with the Date format
A1 B1 C1
3/20/2010 3/26/2010 6

Note: It will return integer value so don't format the resultant(C1) cell to Date.


Date difference by using macro

We can use the datediff function to find the days, months, years difference between two dates

Syntax:
Cell.Value = datediff(interval, Range("startdate_cell").Value, Range("enddate_cell).Value)

Note:
interval can be any one of the following
d - days, m - months, y - years, ym - months excluding years, yd - days excluding years, md - days excluding years and months

Example:
Range("C1").Value = datediff("d", Range("A1").Value, Range("B1").Value)

References:
 http://office.microsoft.com/en-au/excel-help/calculate-the-difference-between-two-dates-HP010070467.aspx

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

Excel Macros and Vba reference links

References:



While Loop Reference
http://www.exceltip.com/st/Using_Loops_in_VBA_in_Microsoft_Excel/628.html

Date and Time Reference
http://www.mvps.org/dmcritchie/excel/datetime.htm

Selecting cells/ranges
http://support.microsoft.com/kb/291308

Vba for excel
http://www.excel-vba.com/excel-vba-contents.htm

User Defined Functions
http://www.vertex42.com/ExcelArticles/user-defined-functions.html
http://www.exceltip.com/show_tip/Excel_Custom_Functions_using_VBA/Writing_Your_First_VBA_Function_in_Excel/631.html

Strings Reference
http://www.mvps.org/dmcritchie/excel/strings.htm

Using Ranges
http://msdn.microsoft.com/en-us/library/aa139976%28office.10%29.aspx

Using Sheets
http://www.mvps.org/dmcritchie/excel/sheets.htm

Searching and auto filing using macros in excel with in sheets

Description:

Sheet1 contains Employee details as follows
(Employee Name, Project, Skills, Role, Start Date, End Date)

Sheet2 contains the new modules/projects which need some more man power with these details
(Project, Skills, Role, Start Date, No. of Persons Required, No. of Persons available, Gap, Names Available)

Here is the Sheet1 in excel

Employee name
Project
Skills
Role
Start Date
End Date
Abc
P1
S1
R1
2-Feb-10
15-Oct-10
Def
P2
S2
R2
15-Mar-10
20-Sep-10
Ghi
P3
S2
R3


Jkl
P4
S1
R4
15-Jan-09
20-Dec-09
Mno
P3
S1
R1
15-Mar-10
15-Mar-12
PSR
P6
S2
R2
15-Mar-10
12-Dec-10
   

Sheet2 contains as follows

Project Name Skills Role Start Date No. Of Persons Required No. Of Persons Exist Gap Names Available
P5 S1 R2 16-Oct-10 5 3 2  
P1 S2 R1 2-Feb-10 6 6 0  
P6 S1 R1 1-Jan-11 2 1 1  
P3 S2 R2 15-Mar-10 4 3 1  
P7 S2 R3 21-Aug-10 5 3 2  
P6 S2 R2 1-Jan-11 7 3 4  

Now, we can write a macro which will fill the names available column with the specified skills and roles

Macro Code:



'Macro Code Starts Here

Sub Find_Gap()
    Dim names As String
    Dim startDate As Date
    Dim skillsVal As String
    Dim roleVal As String
   
    Dim currentCell As Range
   
    'Searching or Finding Value should be in Sheet2
    Sheets("Sheet2").Activate
   
    'Gap column should be in 'G' Column
    Set currentCell = Range("G2")
    currentCell.Select
    names = ""
    'MsgBox (currentCell)
   
    Do
        names = ""
        gapVal = ActiveCell.Value
    If gapVal > 0 Then
        'MsgBox (gapVal)
        'startdate column should be in 'D' Column i.e D-G=-3
        startDate = ActiveCell.Offset(0, -3).Value
       
        'Role column should be in 'C' Column i.e D-G=-4
        roleVal = ActiveCell.Offset(0, -4).Value
       
        'Skills column should be in 'B' Column i.e C-G=-5
        skillsVal = ActiveCell.Offset(0, -5).Value
       
        'MsgBox (startDate & skillsVal & roleVal)
        names = SearchPeople(startDate, skillsVal, roleVal)
    End If
    Sheets("Sheet2").Activate
    'MsgBox (names)
    If names <> "" Then
        currentCell.Offset(0, 1).Value = names
    Else
        currentCell.Offset(0, 1).Value = "-NA-"
    End If
   
    'Name Available Column should be next to Gap 'G' Column
    Set currentCell = currentCell.Offset(1, 0)
   
    currentCell.Select
   
    'Gap column Should be in 'G' Column
    Loop Until IsEmpty(ActiveCell.Offset(0, -6).Value)
   
End Sub




Function SearchPeople(startDate As Date, skillsVal As String, roleVal As String) As String
       
    'Employee Details should be in Sheet1
    Sheets("sheet1").Activate
   
    Dim names As String
    names = ""
   
    'Employee Name should be in 'A' Column
    Range("A2").Select
   
    Do
    'StartDate should be in 'E' Column and EndDate Should be in 'F' Column
        If ActiveCell.Offset(0, 4).Value <> Null Or ActiveCell.Offset(0, 5).Value < startDate Then
            'Skills column should be in 'C' Column and Roles in 'D' Column
            If ActiveCell.Offset(0, 2).Value = skillsVal And ActiveCell.Offset(0, 3).Value = roleVal Then
                If names <> "" Then
                    names = names & "," & ActiveCell.Value
                Else
                    names = ActiveCell.Value
                End If
            End If
        End If
        'MsgBox (names)
       
        ActiveCell.Offset(1, 0).Select
    Loop Until IsEmpty(ActiveCell.Value)
    SearchPeople = names
End Function

'Macro Code Ends Here


When you run the macro, the Names Available column will be filled as follows
Project Name Skills Role Start Date No. Of Persons Required No. Of Persons Exist Gap Names Available
P5 S1 R2 16-Oct-10 5 3 2 -NA-
P1 S2 R1 2-Feb-10 6 6 0 -NA-
P6 S1 R1 1-Jan-11 2 1 1 Abc
P3 S2 R2 15-Mar-10 4 3 1 -NA-
P7 S2 R3 21-Aug-10 5 3 2 Ghi
P6 S2 R2 1-Jan-11 7 3 4 Def,PSR

You can edit the macro according to your requirements.

August 27, 2010

Formatting table automatically in excel using macro and/or Visualbasic Editor

How to use macros in MicroSoft Excel 2007?

Follow these steps
  1. We need to enable Developer Toolbar with the following steps
    • Click the Office Button
    • Click Excel Options
    • Click Popular, select "Show Developer tab in the Ribbon" Checkbox
    Note: For reference you can use this link http://office.microsoft.com/en-us/excel-help/show-the-developer-tab-or-run-in-developer-mode-HA010173052.aspx  
  2. Edit Macro settings in Excel by doing the following steps
    • On the Developer tab, in the Code group, click Macro Security
      Note: If the Developer tab is not displayed, do step 1
    • In the Macro Settings category, under Macro Settings, click the option Disable all macros with Notification 
    Note: For reference you can use this link http://office.microsoft.com/en-us/excel-help/change-macro-security-settings-in-excel-HP010096919.aspx 
  3. Save the excel workbook
  4. Select Developer Ribbon Tab and Click on Visual Basic
  5. Microsoft Visual Basic Editor will be opened
  6. Click on Insert menu and then click on Module
  7. Copy and paste the following code
  8. Enter your data as a table format
  9. Select Developer Ribbon Tab and Click on Macros
  10. Now you can see one macro with the name Table_xls_Format
  11. Click on Run
  12. See the data now. It will be in table format with proper header and data alignment
  13. You can change the macro code by clicking edit button in macro window.
Macro Code:

Sub Table_Xls_Format()
    

    'Selecting Header Row
    Dim header_row As Range
    Set header_row = Range("a1", Range("a1").End(xlToRight))
  
    header_row.Select
  
    'Heading Bold, Aqua Color
    header_row.Font.Bold = True
    header_row.HorizontalAlignment = xlCenter
    header_row.Font.ColorIndex = 42
    header_row.Font.Italic = False
    header_row.Font.Underline = False
  
    'Selecting data

    Dim total_data As Range
    Set total_data = Range("A1").CurrentRegion
  
    total_data.Select
    

    total_data.Font.Bold = False
    total_data.Font.Italic = False
    total_data.Font.Underline = False
  
    'Font:Couriernew , 10
    total_data.Font.Name = "Courier New"
    total_data.Font.Size = 10
  
    'Full Border
    total_data.Borders.LineStyle = 1
  
    'Autofit Column Width
    Selection.Columns.AutoFit
  
    'Autosave the workbook
    ActiveWorkbook.Saved = True

End Sub

Featured Post

Java Introdcution

Please send your review and feedback to psrdotcom@gmail.com