Saturday, March 29, 2014

Video example of a VBA user interface to sort and color code a database

Excel Macro example: Sorting a database

- Format automatically a database
- Add sorting options 
- Organize by columns
- Add Macro call out Button
 - Friendly user interface 
- Data sorting by colors
- Simple controls to interact with database 
- Multi criteria sorting
- Export file on desktop




Friday, March 28, 2014

How to retrieve a manual selection of Excel in VBA and apply a color code to all cells of the selection

This VBA code below helps to apply a specific color coding formatting to a specific selection without using the conditional formatting of excel.
Note: in this example a user interface is used with the the userform command RefEdit to allow the user to manually select the range of cells he wants to apply the formatting on. 

Private Sub CommandButton1_Click() 'macro to release when the button "Put color" is pressed

Dim rng As Range
Dim c As Range

Set rng = Range(RefEdit1.Value) 'RefEdit1 refers to the textbox refedit of the userform

For Each c In rng 'loop to go through all the cells of the selected range

    On Error Resume Next
    If Application.WorksheetFunction.IsNumber(c.Value) And c.Value <> "" Then 'if the cell content is a number and not empty...
        If c.Value >= 0 Then 'then depending on its value, we apply a fill color
        c.Interior.ColorIndex = 43 'green
        Else
        c.Interior.ColorIndex = 46 'red
        End If
    ElseIf c.Value <> "" Then 'if the cell content is a text
        c.Interior.ColorIndex = 34 'blue
    Else 'if the cell is empty
        c.Interior.ColorIndex = 2
    End If

Next

End Sub

Before Macro (click on "color code macro"):



Userform opening:



Click on the cell selection button (control "refedit") and manual selection.



Click on "Put Color" button to apply specific color coding:
(green for positive values, red for negative values, blue for text, rest in white)





Created by DoMyExcel.com © | Excel & VBA Consulting | Customized Excel Solutions starting at 29 USD
Services provided to Individuals and Businesses | Free Quote: DoMyExcel@gmail.com

Tuesday, March 25, 2014

How to adjust the width of many columns or rows simultaneously in Excel

Excel tip: Adjust the width of a range of columns or rows

Before:
 
Select the range of columns (or rows) you want to arrange:
 


Place the mouse pointer on the grille in between two columns (or rows)


And double click to adjust the column width with the content of the column


Or click and drag to adjust the size of columns you want


 

How to organize your data in Excel to make a pivot table

How to organize your data to easily create a consistent pivot chart

The easiest way to organize your data if you want to use the powerful tool of pivot chart in Excel is to work by columns with titles on first row, such as the example below:
 
Example: Planning / tracking of an entertainment company. The company tracks the number of ticket sold depending of the type of event (show / concert), the location of the event (main stage / second stage) and by date.
 

1) Organization of data base

Instead of presenting the database like this for example:
 
 
Pick up the different variables of the spreadsheet (type of event, location, number of ticket sold, date) and organize the database by columns, with the titles of the different variables in first row:
 
 

2) Pivot chart creation

Simply select the entire table and click on "Pivot Chart" (Menu "Insert").
 
 
Then locate the cell you want the pivot table to be created (Note that a pivot chart is always based on a pivot table).
 

3) Set up of the pivot chart

Example 1: Display the sum of tickets sold by type of event:
 
 
 
 
Example 2: Display the sum of tickets sold by stage and by type of event: 
 
 

Monday, March 24, 2014

How to design a multiple clustered bar chart series in Excel

EXCEL - Multiple "bar chart" from multiple entries of two series each

Example: Showing actual (%) versus projected budget (%) month by month for five projects (A to E) all in same master chart:


1) Overall layout

The master chart is actually divided in five sub charts. Each sub chart has transparent background. They are all grouped and placed over a big black rectangle with gradient fill effect.

2) Data source

Each chart has two series: Actual and Budget, with same Axis label ( = Months) 


3) Chart type: overlapping cluster bars

Once plotted, select the charts and select "change chart type" to define format the combo of the two series.

4) Clustered bar width and format

 Select and modify the format of each series and set up the width & the series colors and fill you like.

5) Chart titles and axis values

Create text boxes with formula linked to the main table to have the titles and axes updated automatically when you modify the main table.

6) Chart axis

Add white lines with dash to make the axis.





Sunday, March 23, 2014

How to update Excel chart legend without showing zero legend entry values

If you do not wish to display the series names that don't have values in the chart legend (see pie chart example below), then you can use a similar code as this one below:

Sub update_legend()
chartname = "Mychart"
ActiveSheet.ChartObjects(chartname).Activate
On Error GoTo aa:     'code to delete the current legend if there is one    
ActiveChart.Legend.Select    
Selection.Delete
aa:    ActiveChart.SetElement (msoElementLegendRight) 'code to create a new legend on the right of the chart= 0
With ActiveChart.SeriesCollection(1)
ChartValues = .Values
    For i = 1 To .Points.Count 'loop to go through all the values of the chart
        If ChartValues(i) = "" Or ChartValues(i) = 0 Then 'if the value is zero or empty...
            ActiveSheet.ChartObjects(chartname).Chart.Legend.LegendEntries(i - a).Select
            a = a + 1
            Selection.Delete  '... then delete the corresponding legend entry.
        End If
    Next
End With
End Sub



Before macro run:


After macro run:


Created by DoMyExcel.com © | Excel & VBA Consulting | Customized Excel Solutions starting at 29 USD
Services provided to Individuals and Businesses | Free Quote: DoMyExcel@gmail.com

How to hide the zero percent labels in an Excel pie chart

Remove the 0% in an Excel pie chart: Change the number format code of the labels

1) Select your chart and go to "Format Data Label":

  • On Excel 2013: click on the "+" sign that appears on the top right of the chart and click on the arrow next to "Data Labels":

  • On Excel 2007: go to the menu "Chart tool" > "Format", select "Label format" and "Custom".
2) Go to the section "Number" and add a new "Format Code": Type:
0%;0%;;;



3) As a result, you won't see the 0% values in your chart:

There are many other things you can do with the "Number Format Code" like changing colors of the labels, changing label format, etc. More info here



Friday, March 21, 2014

How to change a shape color in Excel using a VBA macro

Change Excel shape interior color and border color using VBA ColorIndex


VBA:

Sub change_shape_color()
     Dim shp As Shape
     With ActiveSheet.Shapes("My_shape").OLEFormat.Object
         Select Case .Interior.ColorIndex
             Case 3
                 .Interior.ColorIndex = 43 'light green
                 .Border.ColorIndex = 10 'dark green
             Case 43
                 .Interior.ColorIndex = 45 'light orange
                 .Border.ColorIndex = 46 'dark orange
             Case Else
                 .Interior.ColorIndex = 3 'light red
                 .Border.ColorIndex = 30 'dark red
         End Select
     End With
 End Sub


Excel:

Assign macro to Excel shape: Right click > Assign_Macro... and select the macro "change_shape_color" written above.



Thursday, March 20, 2014

How to move a shape in Excel and retrieve its position using a macro VBA

VBA Code to move a shape in Excel and retrieve its location

 
Before the macro:
 
After the macro:
 
 

Sub MoveShape_down()

Dim s As Range

With ActiveSheet.Shapes("My_shape")  '= name of the shape you want to move in Excel
  Set s = .TopLeftCell 'current position of the shape
  .Top = s.Offset(1, 0).Top 'tell the shape to move 1 cell down
  .Left = s.Offset(0, 0).Left 'tell the shape to not move right or left
End With

Range("C3") = s.Row 'Write the current position of the shape (top left cell)
Range("C4") = s.Column

End Sub


How to anchor a shape to fit with an Excel cell


Control the size of the shape to match with cell size


When inserting a shape in an Excel spreadsheet (menu “Insert” > “Shapes”), hold “ALT” to lock in your shape within the multi cell selection.


Tuesday, March 18, 2014

How to work with named ranges in Excel and VBA macros

Managing multiple named ranges in Excel


Using named range is very useful to manage huge amount of data. The button “Name manager” in menu “Formulas” permits to control all the named range you created: you can edit, rename and delete them easily.

The following code example clears the content of all the 16 named range of the above spreadsheet (“CAT_1”, “CAT_2”, etc):

Sub clear_content_of_named_ranges()
For i = 1 To 16 'code to clear all the cells of the 16 named ranges of the Excel spreadsheet without modifying the cell format
Range("CAT_" & i).ClearContents
Next
End Sub



 

Sunday, March 16, 2014

How to display a wait message during an Excel calculation using a VBA macro

Wait message using a Userform in vbModeless & Freeze mode


Sub waiting_message()

UserForm_progress.Show vbModeless 'Will display the userform and continue to execute this current code
UserForm_progress.Repaint 'Bug of Excel: the label on userform won't be shown in vbModeless without this code line
Application.ScreenUpdating = False 'Freeze

'Code with long calculation time

UserForm_progress.Hide
DoEvents 'To do events in a Freeze mode
Application.ScreenUpdating = True 'Unfreeze

End Sub


How to display the progress of a VBA macro in the status bar of Excel

Display a progress status of your macro on the bottom left corner of Excel


Sub My_macro_status() 'To display a status to the user on the bottom left corner of Excel application

Application.StatusBar = "Macro in process: 0%"
'Code
Application.StatusBar = "Macro in process: 50%"
'Code
Application.StatusBar = "Macro in process: 100%"
'Code
Application.StatusBar = False

End Sub


How to lookup a specific word or value in a cell or an Excel database using the VBA function Instr()

Four examples to understand the function Instr() on VBA:


Example 1: Instr() return the position of a character in a word

Sub function_instr()
'Instr syntax: InStr( [start], string, substring, [compare] )
'VBA Excel search the position of a character in a word - integer
'ex 1: check at what position is the letter x contained in word "domyexcel.com"

result_ex1 = InStr("domyexcel.com""x")
MsgBox ("character x is at the " & result_ex1 & "th position in the world domyexcel.com")

End sub

Example 2: Instr() presence of a character in a word (True or False)

Sub function_instr()
'VBA Excel check if a letter is included in a word - true or false
'ex 2: check if yes or no the letter x contained in word "domyexcel.com"

If InStr("domyexcel.com""x"> 0 Then
result_ex2 = True
MsgBox ("letter x is included in domyexcel.com")
Else
result_ex2 = False
MsgBox ("letter x is not included in domyexcel.com")
End If

End Sub

Example 3: Instr() presence and location of a word in a database

Sub function_instr()
'VBA Excel search if a world is contained in a database:
'ex3: tell at which line of the database the world "domyexcel" was found

For i = 1 To 10
    If InStr(Cells(i, 1), "domyexcel.com"> 0 Then
    result_ex3 = i
    MsgBox ("The word domyexcel.com was found at row " & result_ex3)
    End If
Next

End Sub

Example 4: Instr() Highlight the cell in a database that contain a specific character or word

Sub function_instr()
'VBA Excel highlight the cells in a database that contained a specific word a/o character
'ex4: highlight in blue the cells that contain the character x

For i = 1 To 10
    If InStr(Cells(i, 4), "x"> 0 Then
    Cells(i, 4).Select
    Selection.Interior.Color = 16750899
    End If
Next

End Sub


Code syntax: charles.racaud.free.fr

How to populate a combobox located in a VBA userform using a named range in Excel

In Excel:


In VBA:

Sub populate_combobox() 'Procedure to populate a combobox located in a userform

Dim item As Range

With UserForm1.Controls("ComboBox1"'To access to properties of the userform before showing the userform
    .Clear 'Remove previous loaded values
    For Each item In Sheets(1).Range("Mycomboboxlist").Cells 'Go through all the cells of a named range
        .AddItem (item.Value) 'To populate the combobox with a value
    Next
End With

UserForm1.Show 'To display the userform

End Sub