Wordle: 1

Wednesday 29 April 2015

Folders directory Scripting.FileSystemObject Method


Sub TestListFolders()
   
    Application.ScreenUpdating = False
   
     'create a new workbook for the folder list
   
     'commented out by dr
     'Workbooks.Add
   
     'line added by dr to clear old data
    Cells.Delete
   
     ' add headers
    With Range("A1")
        .Formula = "Folder contents:"
        .Font.Bold = True
        .Font.Size = 12
    End With
   
    Range("A3").Formula = "Folder Path:"
    Range("B3").Formula = "Folder Name:"
    Range("C3").Formula = "Size:"
    Range("D3").Formula = "Subfolders:"
    Range("E3").Formula = "Files:"
    Range("F3").Formula = "Short Name:"
    Range("G3").Formula = "Short Path:"
    Range("A3:G3").Font.Bold = True
   
     'ENTER START FOLDER HERE
     ' and include subfolders (true/false)
    ListFolders "C:\Users\MAA\Desktop\Access to Excel\", True
   
    Application.ScreenUpdating = True
   
End Sub





Thursday 12 March 2015

TOP FIVE MOST COMMON VBA ERRORS AND THEIR SOLUTIONS

Here are the five most common errors I have found (and made) while programming in VBA. Most errors are as valid in Excel VBA as they are in Microsoft Access VBA.

Still debugging while in production.

Congratulation, you are now in production. Are you really? You have still left some debugging tools active in your production code. How do I know? You have left some command such as STOP,  Debug.Print and Debug.Assert.

Although very useful when construction is on, you should always take them off after launch for the same reason you don't let your scaffolds out after you finished painting your ceilings.
Breakpoints should all be removed too.

1) 'Case Else' is missing. 

Select Case are a convenient way to handle several different values. It is also much more efficient than several imbricated IF...elseif...elseif...
If an unexpected value appears, the following  Select Case statement has no effect.
  x = 10
  Select Case x
    Case 1 To 5
      'Statement
    Case 6 To 9
      'Statement
  End Select

 
Always use a Case Else branch to ensure that all possible scenarios in your code are considered. 
 
  x = 10
  Select Case x
    Case 1 To 5
      'Statement
    Case 6 To 9
      'Statement
    Case Else
      MsgBox "Unexpected value:" & x
  End Select
Personally, I always declare the base structure as
 
Select Case x
     Case else
    'oops
    ...
End Select

2) Variable, constant or function declared without a data type. 

You should never declare a variable, a constant or a function without specifying its data type. In such cases, the default Variant data type is used. Using variant is usually sign of sloppy design (you don't know yet what you will get) and also slow on execution.
Avoid declaring variables using the declaration data type char, it is nearly as bad as not declaring anything.
          %                 Integer
          &                 Long
          !                 Single
          #                 Double
          $                 String
          @                 Currency
Instead of:
Dim strSQL$
Dim recNumber&
be specific: 
Dim strSQL as String
Dim recNumber as Long

3) Handle your errors like a great programmer, not like a rookie!

Even after year of experiences and in a simple code, there will be errors. If you didn't include error handling in your procedure, when you have a runtime error, the program will stop and display an error message. There are many ways to handle that, here is my way:
Function Display2Char(ByVal AsciiCode As String) As Boolean
   Dim strText As String
   On Error GoTo Display2Char_Error '<< first instruction: engage error management
   ' Function body goes here
   ' ...
Display2Char_Error: '<< we always check for error before leaving
   Select Case Err.Number
      Case Is = 0:
         ' do nothing since there is no error
      Case Is = 513:
         ' Invalid ascii char
         '...
         Resume Next
      Case Else:
           MsgBox "Error " & Err.Number & " (" & Err.Description & _
               ") in Sub Display2Char of Module Demo"
   End Select   
   On Error GoTo 0 '<< Release Error Management
End Function

And the number-one problem is...
 

4) Option Explicit is missing.

The statement "Option Explicit" should always be the first line of all VBA modules. I have stopped counting the number of problems I avoided since I use that instruction. It forces you to declare all your variables before you use them. Besides the advantage of having a cleaner program with declared variables, doing so (and most importantly) prevents you from making typos in variable name.
For example, if you have a declared variable named MyAccessKey, you will get compilation error when you later  try to use a variable mistakenly written MyAccesKey (missing one "s") or MyAccessKeys (one "s" too many).

So those were the top five most common errors in VBA. If you liked ... What? You see really four problems instead of five? Let me check that... Ok, I see where you are going with that: The number one problem partially encompassed problem number 3. So, because I am a great soul, and because I don't want to look cheap, I will give you,  free of charge, an extra problem #3 and its solution.

5) Parameter not explicitly declared with either ByVal or ByRef

By default, all parameters are passed as reference (ByRef). It means that the variable passed to a procedure can be changed, even accidentally, and will now appear changed from the calling procedure. It is usually not a good idea to do that but life can be full of surprises... Most of the time, when we pass a variable as a parameter, really want to pass its value (ByVal) instead of the variable itself. So, in order to pass the right thing, we should always clearly specify whether we want to pass a variable ByVal or ByRef.

Sub x()
    klm As Double
    = 5
    klm, "Start x"
   Call y(klm)
    klm, "end x."
End Sub
Sub y(ByVal wzk As Double) <-- nbsp="" span="" style="background-color: plum; box-sizing: border-box;">ByVal 
is added, or not, in the tests below.
    wzk, "Start y"
   wzk = wzk * 2
    wzk, "end y."
End Sub
Results WITHOUT specifying ByVal (ByRef by default)
5           Start x
       5    Start y
      10    end y.
10          end x.
 <-- nbsp="" span="" style="box-sizing: border-box; text-decoration: underline;" sub="" to="" unknown="" value="" x="">WAS 
changed.
Results WITH ByVal specified.
5           Start x
       5    Start y
      10    end y.
5           end x. 
<-- p="" remains="" subroutine="" to="" unchanged="" value="" x.="">

That really conclude my top five most common VBA error's countdown. Do you have other errors? Let me know.

Excel is Fun.

Sunday 4 January 2015

Using conditional formatting to highlight dates in Excel

Using conditional formatting to highlight dates in Excel....

Date functions in Excel make it is possible to perform date calculations, like addition or subtraction, resulting in automated or semi-automated worksheets. The NOW function, which calculates values based on the current date and time, is a great example of this.
Taking this functionality a step further, when you mix date functions with conditional formatting, you can create spreadsheets that display date alerts automatically when a deadline is near or differentiates between types of days, like weekends and weekdays.
The basics of conditional formatting for dates
To find conditional formatting for dates, go to

Home > Conditional Formatting > Highlight Cell Rules > A Date Occuring.

You can select the following date options, ranging from yesterday to next month:


These 10 date options generate rules based on the current date. If you need to create rules for other dates (e.g., greater than a month from the current date), you can create your own new rule.
Below are step-by-step instructions for a few of my favorite conditional formats for dates.
Highlighting weekends

When you design an automated calendar you don’t need to color the weekends yourself. With the conditional formatting tool, you can automatically change the colors of weekends by basing the format on the WEEKDAY function.  Assume that you have the date table–a calendar without conditional formatting:


To change the color of the weekends, open the menu Conditional Formatting > New Rule

In the next dialog box, select the menu Use a formula to determine which cell to format.

In the text box Format values where this formula is true, enter the following WEEKDAY formula to determine whether the cell is a Saturday (6) or Sunday (7):
=WEEKDAY(B$5,2)>5

The parameter 2 means Saturday = 6 and Sunday = 7. This parameter is very useful to test for weekends.


Note: In this case, you must lock the reference of the row so that the conditional format will work correctly in the other cells in this table.

Then, customize the format of your condition by clicking on the Format button and you choose a fill color (orange in this example).


Click OK, then open Conditional Formatting> Manage Rules



Select This Worksheet to see the worksheet rules instead of the default selectionIn Applies to, change the range that corresponds to your initial selection when creating your rules to extend it to the whole column.

Now you will see a different color for the weekends. Note: This example shows the result in the Excel Web App.

Highlighting holidays
To enrich the previous workbook, you could also color-code holidays. To do that, you need a column with the holidays you’d like to highlight in your workbook (but not necessarily in the same sheet). In our example, we have US public holidays in column AH (as related to the year in the cell B2).

Again, open the menu Conditional Formatting > New Rule. In this case, we use the formula COUNTIF in order to count if the number of public holidays in the current month is greater than 1.
=COUNTIF($AH$4:$AH$16,B$5)>1
Then, in the dialog box Manage Rules, select the range B4:AF11. If you want to highlight the holidays over the weekends, you move the public holiday rule to the top of the list.

This example in the Excel Web App below shows the result. Change the value of the month and the year to see how the calendar has a different format. 
Highlighting delays
In case we want to change the color of cells based on our approach on a date again, we will use conditional formatting to make it work for us.
In the following example, we show:
  • yellow dates between 1 and 2 months
  • orange dates between 2 and 3 months
  • purple dates more than 3 months
We then construct three rules conditional formatting using formula DATEDIF . Respectively for the three cases the following formulas:
=DATEDIF($B2,$E$2,”m”)>0
=DATEDIF($B2,$E$2,”m”)>1
=DATEDIF($B2,$E$2,”m”)>2

In the Excel Web App below, try changing some dates to experiment with the result.
Color scales
Rather than choose a different color set for each period in our timeframe, we will work with the option of color scales to color our cells.
First, go into a new column (column E), calculate the difference in number of days in a year again with the DATEDIF formula and the parameter “yd”.
=DATEDIF($D2,TODAY(),”yd”)
Then choose the menu Conditional Formatting> New Rule option Format all cells based on their value and choose the following options:
  • Scale = 3 colors
  • Minimum = 0 red
  • Midpoint = 10 yellow
  • Maximum = 30 white


The result is a gradient color scale with nuances from white to red through yellow.  The closer to 0, the more red it will have, the closer to 10 the more yellow, and the closer to 30 the more white.  In the Web App below, try changing some dates to experiment with the result.

Excel is Fun...


MS Excel Quiz - 1

 1. You can auto fit the width of column by

 A) double clicking on the column name on column header
 B) Double click on the cell pointer in worksheet
 C) Double clicking on column right border on column header
 D) Double clicking on the column left border of column header


2. Long text can be broken down into many lines within a cell. You can do this through

 A) Wrap Text in Format >> Cells
 B) Justify in Edit >> Cells
 C) Text Wraping in Format >> Cells, Layout tab
 D) All of above


3. MS Excel provides the default value for step in Fill Series dialog box

 A) 0
 B) 1
 C) 5
 D) 10


4. When a row of data is to be converted into columns

 A) Copy the cells in row, select the same number of cells in row and paste
 B) Copy the cells in column then choose Edit >> Paste Special, then click Transpose and OK
 C) Copy the cells then go to Format >> Cells then on Alignment tab click Transpose check box and click OK
 D) Select the cells then place the cell pointer on new cell and choose Edit >> Paste Special, mark Transpose check box and click OK.


5. Ctrl + D shortcut key in Excel will

 A) Open the font dialog box
 B) Apply double underline for the active cell
 C) Fill down in the selection
 D) None of above


6. The short cut key Ctrl + R is used in Excel to


 A) Right align the content of cell
 B) Remove the cell contents of selected cells
 C) Fill the selection with active cells to the right
 D) None of above


7. The command Edit >> Fill Across Worksheet is active only when


 A) One sheet is selected
 B) When many sheets are selected
 C) When no sheet is selected
 D) None of above


8. Which of the following series type is not valid for Fill Series dialog box?

 A) Linear
 B) Growth
 C) Autofill
 D) Time


9. Which of the following you can paste selectively using Paste Special command?


 A) Validation
 B) Formats
 C) Formulas
 D) All of above


10. Paste Special allows some operation while you paste to new cell. Which of the following operation is valid?

 A) Square
 B) Percentage
 C) Goal Seek
 D) Divide


11. Edit >> Delete command

 A) Deletes the content of a cell
 B) Deletes Formats of cell
 C) Deletes the comment of cell
 D) Deletes selected cells


12. To remove the content of selected cells you must issue ______ command

 A) Edit >> Delete
 B) Edit >> Clear >> Contents
 C) Edit >> Clear >> All
 D) Data >> Delete


13. The Delete key of keyboard is assigned to which command in Excel?


 A) Edit >> Clear >> Contents
 B) Edit >> Clear >> All
 C) Edit >> Delete
 D) All of above


14. If you need to remove only the formatting done in a range (numbers and formula typed there should not be removed), you must 

 A) From Edit menu choose Clear and then Formats
 B) From Edit menu choose Delete
 C) Click on Remove Formatting tool on Standard Toolbar
 D) Double click the Format Painter and then press Esc key in keyboard


15. By default Excel provides 3 worksheets. You need only two of them, how will you delete the third one?

 A) Right click on Sheet Tab of third sheet and choose Delete from the context menu
 B) Click on Sheet 3 and from Edit menu choose Delete
 C) Both of above
 D) None of above


16. Which of the following action removes a sheet from workbook?

 A) Select the sheet, then choose Edit >> Delete Sheet
 B) Select the sheet then choose Format >> Sheet >> Hide
 C) Both of above
 D) None of above


17. While Finding and Replacing some data in Excel, which of the following statement is valid?

 A) You can Find and Replace within the sheet or workbook
 B) Excel does not have option to match case for find
 C) Both are valid
 D) None are valid


18. Which of the following is not true about Find and Replace in Excel

 A) You can search for bold and replace with italics
 B) You can decide whether to look for the whole word or not
 C) You can search in formula too
 D) You can search by rows or columns or sheets


19. You can move a sheet from one workbook into new book by

 A) From Edit menu choose Move or Copy sheet, mark the Create a ccopy and Click OK
 B) From Edit menu choose Move of Copy then choose (Move to end) and click OK
 C) From Edit menu choose Move or Copy then select (new book) from To Book list and click OK
 D) None of above


20. What is the short cut key to replace a data with another in sheet?

 A) Ctrl + R
 B) Ctrl + Shift + R
 C) Ctrl + H
 D) Ctrl + F


Answers

1-C, 2-A, 3-B, 4-D, 5-C, 6-C, 7-B, 8-D, 9-D, 10-D, 11-D, 12-B, 13-A, 14-A, 15-A, 16-A, 17-A, 18-D, 19-C, 20-C

Saturday 13 December 2014

Daily Useful VBA Codes


Description
VBA Code
Selecting
'==Select 3 rows down, 2 columns right:
ActiveCell.Offset(3, 2).Select

'==Select from active cell to last row of list:
Range(Selection, Selection.End(xlDown)).Select

'==Select from current cell to last column of list:
Range(Selection, Selection.End(xlToRight)).Select

'==Select last cell of worksheet:
Selection.SpecialCells(xlLastCell).Select
Pasting
'==Paste formula value, not formula:
Range("A3").Copy
Range("D26").PasteSpecial Paste:=xlValues

'==Paste into a cell and move its original contents to the next cell:
Selection.Insert Shift:=xlToRight
Columns and Rows
'==Hide a column:
Selection.EntireColumn.Hidden = True

'==Insert a column:
Columns("N:N").Insert

'==Delete columns:
Columns("B:E").EntireColumn.Delete

'==Insert a new row at current cell:
Selection.EntireRow.Insert

'==Delete row of current cell:
Selection.EntireRow.Delete

'==Set column width:
Selection.EntireColumn.ColumnWidth = 10

'==Set row height:
Selection.RowHeight = 26.25

'==Set row height to size of contents:
Selection.Rows.AutoFit
Cell Formatting
'==Text not wrapped:
Selection.WrapText = False

'==Remove color:
Selection.Interior.ColorIndex = xlNone

'==Set font size:
Selection.Font.Size = 8

'==Date and time format:
Selection.NumberFormat = "mm-dd-yyyy hh:mm AM/PM"

'==Number format with comma:
Selection.NumberFormat = "#,##0"

'==Left aligned:
Selection.HorizontalAlignment = xlLeft

'==Bottom aligned:
Selection.VerticalAlignment = xlBottom

'==Indented text:
Selection.IndentLevel = 3

'==Delete contents but not formatting:
Selection.ClearContents

'==Delete contents and formatting:
Selection.Clear
Display
'==Hide activity while macro runs:
Application.ScreenUpdating = False

'==Turn off automatic alerts:
Application.DisplayAlerts = False

'==Freeze  panes:
ActiveWindow.FreezePanes = True

'==Show how long macro runs:
Dim strTime1 as String, strTime2 as String
strTime1 = Format(Now(), "mm-dd-yyyy hh:MM:ss")
[put other macro code here]
strTime2 = Format(Now(), "mm-dd-yyyy hh:MM:ss")
MsgBox "Elapsed Time = " & DateDiff("n", strTime1, strTime2)
Range Names
'==Add a range name:
ActiveWorkbook.Names.Add Name:="Groups", RefersTo:=Selection

'==Go to a named range:
Range("Groups").Select

'==Delete all range names in workbook:
Dim n as Object
For Each n In ActiveWorkbook.Names
         n.Delete
Next
Path/File Name
'==Insert path/file name into a cell:
ActiveCell.Value = ActiveWorkbook.FullName

'==Insert path/file name into a footer:
ActiveSheet.PageSetup.CenterFooter = ActiveWorkbook.FullName
Pivot Tables
'===Remove unused items in pivot tables when data has changed:

Dim pt As PivotTable, ws As Worksheet
  For Each ws In ActiveWorkbook.Worksheets
          For Each pt In ws.PivotTables
                      pt.PivotCache.MissingItemsLimit =   
                     xlMissingItemsNone
          Next pt
 Next ws
Worksheets
'==Add date to title of each worksheet:


Dim sht As Worksheet

For Each sht In ActiveWorkbook.Worksheets

            sht.Select
            Range("A1").Value = Range("A1").Value & "   
            through " & strDate


Next sht