Showing posts with label Excel. Show all posts
Showing posts with label Excel. Show all posts

Wednesday, 31 October 2012

A Simple Example Of How To Manage Dates With Excel And VBA

Dates can sometimes present a problem to those new to Excel. It's usually not enough to simply record the date of something; you probably need to know things like an elapsed interval, the day of the week and various other items of information that VBA can easily deliver.
A Case Study Of Using Dates Effectively
One way of understanding dates in Excel is to look at a real life situation.
Managing customers can sometimes be a nightmare, but creating a customer contact schedule based on some simple rules is simple. An overview of customers and contact dates might look something like this:

Customer, Last Contact, Next Contact (weeks)

a, 20-Jul,6
b, 21-Aug, 4
c, 2-Jun, 3
d, 5-Apr, 5
e, 24-Aug, 7
f, 5-Mar, 4
You know the customer, the date of the last contact and when the next contact should be made. But how would you turn that data into solid business information? In a real life situation you'll have more information like the contact person, what was discussed and products purchased, but we'll just focus on the issues for managing dates.
We're going to create a contact schedule which tells us which customers need to be contacted based on the "next contact" schedule that we've set up. Luckily for us, Excel and VBA make it easy to work with dates.
You'll need two worksheets set up; one called "work" to hold the information above and another called "schedule" where we'll record the customers that need to be contacted.
How VBA Date Functions Can Help In Working With Dates
There are a few different date functions in VBA but the one we'll look at is the dateDiff function. Applying this command returns to us the difference between two dates, which is all we need to create a work schedule.
1. Select the data
Range("A2").Activate
last = ActiveCell.End(xlDown).Row
2. Loop through the data and assign variables
ct=ct+1
For x = 2 To last
With ActiveCell
customer =.Value
lastContact =.Offset(0, 1).Value
nextContact =.Offset(0, 2).Value
End With
3. Work out how many weeks have elapsed since the last contact

due = DateDiff("w", lastContact, Now())
4. If more weeks has elapsed since the scheduled contact then copy the customer to a new worksheet called "schedule"
If due > nextContact Then
ct = ct + 1
Sheets("work").Range("a" & x).EntireRow.Copy _
Sheets("schedule").Range("a" & ct)
End If
5. Go to the next customer
ActiveCell.Offset(1, 0).Activate
Next
The VBA code creates a current work schedule; a listing of customers that need to be contacted and the worksheet can be printed out or emailed to the relevant staff member to take action.
Enhancements To The VBA Code
In a real life situation you could easily add more functionality to form the basis of a fully functioning work schedule:
Include the last comments and the name of the salespersonCreate a heading for the newly created scheduleList any products purchased
Summary
It's one thing to record data in a spreadsheet; the tricky bit is to turn that data into information that can become a business asset. With a little planning and knowledge of Excel and VBA, you'll have the tools needed to become more efficient and professional in whatever you're doing.




Tuesday, 23 October 2012

Finding Duplicates In An Excel Spreadsheet With VBA

If you've ever been confronted with an Excel spreadsheet that has duplicate entries, you'll know that some care is required. You don't want to delete what might be genuine unique entries, or miss out on other entries that might be duplicates but have slipped through.
Some duplicates might hold information that you need to retain or transfer to a new entryYou might need to add data to new or existing entries, for example to add a unique keySome entries may be partial duplicates requiring further investigation
Excel Tools for Finding Duplicates
Excel has some good tools for identifying and removing identical entries but these can be a little inflexible if you're wanting to do something slightly different with your data:
Conditional formatting enables highlighting of possible duplicates and is a quick way to find repeated entriesThe remove duplicates tool is a blunt instrument which deletes the offending entries and reports on the number of items removedVarious worksheet formulas can identify duplicate entries
But sometimes the standard tools won't quite do the job and it's good to know what to do if you need something just a little more complicated. With a little knowledge and planning you can write your own VBA code to find duplicate entries.
Finding Duplicates With VBA
We're going to write some VBA code that will identify duplicate entries and copy them to a new worksheet. This might be a common task in business as you might want to review the possible duplicates rather than just delete them.
A good example might be a customer list which you suspect might have repeated entries. We want our code to search the phone numbers looking for duplicate records; if a phone number is repeated there's a good chance the entries are duplicates.
Select the sheet and cells to search

Sheets("allData").Activate
dupsCol = "e1"
Range(dupsCol).Activate
lastCell = ActiveCell.End(xlDown).Address
allCells = ActiveCell.Address & ":" & lastCell
Range(allCells).Select
Now we'll loop through the data and compare each cell to the total data set. If we find a duplicate we'll copy the row to the "duplicates" worksheet.

ct = 0
For Each c In Selection
curCell = c.Value
If Application.WorksheetFunction.CountIf(Range(allCells), curCell) > 1 Then
ct = ct + 1
Sheets("alldata").Range("a" & c.Row).EntireRow.Copy Sheets("duplicates").Range("a" & ct)
End If
Next

Now we'll sort the duplicates to make them easier to work with.

Sheets("duplicates").Activate
Range("A1").CurrentRegion.Select
Selection.Sort Key1:=Range(dupsCol)
Summary
With a little planning and knowledge it can be easy to improve the standard tools that come with every version of MS Excel. Learning a little about VBA and how it can improve your spreadsheet processes will pay dividends both in saving time and improving productivity.




Tuesday, 18 September 2012

How To Use VBA To Import Data From Another Excel File

Sometimes you'll want to access another spreadsheet from an existing Excel file. If you're adding data from another file on a regular basis this process might be an ideal candidate for automation with VBA.
An example might be a weekly report from your sales staff and you want to add the new data to an existing file called total sales
. Here's what you might be doing manually once a week:
Open the total sales
fileFind and open the latest weekly reportCopy and add the data into the total sales spreadsheet
VBA can be used to automate the entire process, but you do need to consider various issues that might be unique to your own situation.
Is the weekly report file in the same folder as the total sales
file?Will the weekly report have the same name every time you import it?Are the fields in the main file consistent with the new data?Where will you put the new data in the main file?
Opening Another File And Importing The Contents
It's fairly straight forward to open another file in VBA, but you do need to specify the location; you can access this through the activeWorkbook.path
function which returns the folder address of the current workbook.

' open the file
weeklyFile = ActiveWorkbook.Path & "\20aug2012Sales.xls"
Workbooks.Open Filename:=weeklyFile
Range("A1").CurrentRegion.Select
' copy and paste the contents
Application.DisplayAlerts = False
Selection.Copy
ActiveWindow.Close
Range("A1").End(xlDown).Offset(1, 0).Select
ActiveSheet.Paste
Although this is a fairly simple code snippet, you might need to adjust it slightly for your own situation:
1. Application.DisplayAlerts=false
This line not really needed; it just asks the user if the application should keep the copied data on the clipboard before closing the weekly file and the default response is yes. Alternatively we could have kept the weekly file open until after pasting the data.
2. Location of the weekly file
If the weekly sales data is in a different folder to the main file the location needs to be specified directly. The logical idea would be to keep the new files in a separate folder:


totalsales.xsl
weeklysales/20Aug2012Sales.xls

2. The name of the weekly sales files
As you might get a new sales file each week the name could be constantly changing but if the file is named in a consistent format you can use an input box to ask for the file name:

weeklySales = InputBox("Sales File for Week ending:")
weeklySales=weeklySales & "Sales.xls"
In this case we've just asked the user for the date, instead of typing in the full file name; if you know the naming convention will always be the same, this can be elegant solution.
Summary
You've seen how just 8 lines of code will open an Excel spreadsheet and import the data into an existing spreadsheet. With a little thought applied to your own situation this is another example of how VBA can make your own work with Excel much more efficient and productive.



Wednesday, 12 September 2012

Replacing Unwanted Characters In Excel Data Using VBA

If you've ever been given an Excel spreadsheet file to analyze or extract information from you'll know how frustrating it can be if the data is not in a consistent format. Unfortunately this is a common occurrence, especially if the data has been entered by different staff members over a period of time.
This article will show you how to remove unwanted characters from Excel worksheets with just a few lines of VBA code.
Examples Of Inconsistent Format
Types of unwanted characters include abbreviations, bracketing of cities and states; and also phone numbers containing non-numeric characters. The following represent examples of inconsistent formats which might create problems later on.


07-526-2025
(021) 5262065
AZ
NY
(New York)
04 526 2065
021-526-2065.
Arizona.

The problem with using different formats is that you never know what the data may be used for in the future. Perhaps a dialling function on a customer management program might be relying on phone numbers that are in a pure numerical format. Or someone might be doing a search for customers in "Arizona" but the search won't be looking for "AZ".
Without instruction, some data entry staff tend to enter information in what they see as a user-friendly format. Each staff member might have a different view on the best data format but computers think differently from human beings and need information in a predictable format.
Using VBA To Clean Up Your Data
We're going to write a short routine to clean a list of phone numbers - removing unwanted characters and making the data searchable and computer-friendly. Excel has various in-built formulas to replace or substitute characters in a string, but the problem is that an entry may contain several different non-numeric characters and we want to remove them all.
Our VBA code will combine several techniques to ensure each phone number contains numeric values only.

Select the data range


Range("a1").CurrentRegion.Columns(1).Select
Loop through the selected data and

Assign the value of each cell into a temporary variable that
we'll use to find non-numeric characters
For Each c In Selection
txt = c.Text
Check each character in the entry to make sure it's numeric and

if it isn't, remove the character from the cell value
For x = 1 To Len(txt)
chkChar = Mid(txt, x, 1)
if Not IsNumeric(chkChar) Then
c.Value = Replace(c.Value, chkChar, "",)
End If
Next
Go to the next cell to check

Next
Once the phone numbers are purely numerical, your data can be a lot more useful. For example it could be imported into a database which requires numerical entries or be used as a search "key" when looking for duplicates.
Summary
You've seen how VBA can help clean up your data - although the best idea is to have solid business rules to prevent inconsistent formatting to begin with.
A good idea is to take the time to develop good processes before even beginning data entry but it's nice to know there are simple techniques available to make the best use of your business information whatever state it might be in.