Archive for the ‘Visual Basic’ Tag

Convert Excel date value to SQL date

When creating SQL statements you’ll often need a date in the ISO 8601 standard format (e.g. 2010-03-26 12:34).

Of course you can change the format in Excel to show it as such, but that doesn’t give you the string you need, e.g. in an insert or update statement.

Here’s an Excel function to make an SQL date value, presuming the date value is in cell A1:

=TEXT(A1,”yyyy-mm-dd hh:MM:ss”)

This circumvents the use of complicated IF and date/time functions. Append a “Z” if you need to indicate the timezone as UTC (i.e. GMT) time.

Here’s a short VBA function to create this type of date

Function SQLDate(d)
SQLDate = WorksheetFunction.Text(d, "yyyy-mm-dd hh:MM:ss")
End Function

Put this code in a new module in your workbook to instantly start using the function in Excel like this: “=SQLDate(A1)”

SQL date in Excel

SQL date in Excel

More information:

Convert Excel Tables To Lists

note: please see the update on the bottom of this article for an even quicker way to convert a table

In a dark past I was an Excel instructor (among other things). I have trained countless people in the art of Excel number wizardry. I have then become a certified Excel VBA specialist, and I must say, in my years being a professional programmer, this is the skill that has set me apart from all other programmers around me. Sure, people can do Regular Expressions… So can I. Sure, people can do Object Orientation. So can I. But what programmer fancies dumb jumbling of data, and programming a language that has the word ‘basic’ in it? Right. Most programmers I knew were Linux shell companies (pun intended) that had no idea something good was hidden up the sleeve of Microsoft. But ok, sometimes I was able to show them some awesome things, and they would instantly recognize that their world view (Excell is for end-users) was a grave mistake.

What fun it was to teach people Excel, and more so, VBA! To me, it’s the tool of all tools, and it can greatly help anyone who ever works with data (ehm, anyone). So in this first part of a long, long series (I hope) I will show you, the humble ignorant user how to convert an Excel table to a list.

Why? Many times I have gone to companies and helped them with some particular problem. Usually it started out with an analyst/marketer/ceo showing me a bunch of data. The data was always presented as a table, with column headings and row headings, with the data in the middle. That seems like a nice way to present data, yes, it is in fact. The first thing I would do is then convert this table to an ugly list.

So why would you convert it to a list?

Because Excel is in love with lists. Excel craves lists, it’s like Access’ little brother, but it can speak five languages and juggle 4 balls. It’s no database tool (maximum of 65535 rows, 1M in Excel 2007)… but it can transform any list into a deep, deep analysis.

The way this analysis is done later on is with Pivot Tables. I wrote those capitals on purpose. Pivot Tables are so powerful that you can basically give it any data list and it can tell you what’s missing, what’s wrong, what’s unique, what’s the total, what’s the average, you name it. But more on that later on.

Let’s convert!

Warning: code ahead…

A table consists of three parts:

  1. The row headings (left)
  2. The column headings (top)
  3. The data (center)

We will loop through the data cell by cell, and create a row in a new list for each. That’s the basic idea (pun intended).

Before we start, we check some preconditions. We have to make sure that we are inside a set of data, formed into a table. All we do is just check if we have at least two rows and two columns (not the ultimate, but it works).

Sub TableToList()
If ActiveCell.CurrentRegion.Rows.Count < 2 Then
Exit Sub
End If
If ActiveCell.CurrentRegion.Columns.Count < 2 Then
Exit Sub
End If

Then we will need some variables to refer to the various sections of the table

Dim table As Range
Dim rngColHead As Range
Dim rngRowHead As Range
Dim rngData As Range
Dim rngCurrCell As Range

Next. we will need some variables for the data itself

Dim rowVal As Variant
Dim colVal As Variant
Dim val As Variant

Now, we will start pointing our variables to the data, row headings and column headings, like so

Set table = ActiveCell.CurrentRegion
Set rngColHead = table.Rows(1)
Set rngRowHead = table.Columns(1)
Set rngData = table.Offset(1, 1)
Set rngData = rngData.Resize(rngData.Rows.Count - 1, rngData.Columns.Count - 1)

Note that “currentregion” is a handy tool that expands any cell into a surrounding of non-empty cells. So this way your selected cell could be anywhere inside the table when you run the macro. The data part is a bit harder, line 4 and 5 together shift and resize the original table to form the right bottom part, where all the data resides.


Next, we create a new sheet in the workbook, to hold the list.

ActiveCell.Value = "Row#"
ActiveCell.Offset(0, 1).Value = "RowValue"
ActiveCell.Offset(0, 2).Value = "ColValue"
ActiveCell.Offset(0, 3).Value = "Data"
ActiveCell.Offset(1, 0).Select

In this sheet, we create a first row, “manually”, where we name the column headings for our list. These column headings are very important for sorting, analysis, pivot tables, export and such. The last statement instantly moves the current cell selection one row down. Notice we’re inserting a special column for Row Number. This is not always necessary, but it doesn’t hurt, and it helps you to always be able to restore the original order of the list.

Now it’s time for the actual grunt work, looping through the table

Dim n As Long
For Each rngCurrCell In rngData
colVal = rngColHead.Cells(rngCurrCell.Column - table.Column + 1)
rowVal = rngRowHead.Cells(rngCurrCell.Row - table.Row + 1)

The “for each rngCurrCell in” is a real beauty in VBA. It just runs through any selection, without worries of overflows, row and column numbers, or calculations. In the loop, we set the value of the current column and row. Note that the rngCurrCell.column and rngCurrCell.row are not relative, it’s the actual number of the column/row. So if the tables starts at C3, the first cel is having column=3 and row=3.

n = n + 1
ActiveCell.Value = n

Here, we upped counter ‘n’ and put it in the list.

ActiveCell.Offset(0, 1).Value = rowVal
ActiveCell.Offset(0, 2).Value = colVal
ActiveCell.Offset(0, 3).Value = rngCurrCell.Value
ActiveCell.Offset(1, 0).Select

We do the same trick again to put a new row in the data list on our new sheet. As you can see this part of code is repeated from the part where we created the header. A small improvement would be to create a function named ‘newRow(n, rv, cv, dv)’ to insert a new row with these values.

If, instead of actual values, you prefer to link to the original cell, you can use

ActiveCell.Offset(0, 3).Value = "=" & rngCurrCell.Worksheet.Name & "!" & rngCurrCell.Address

Finish the loop with:

End Sub

Well, that’s it!

Running your code

Make sure to have a table setup in Excel, and click inside the table, it will be automatically selected.

  • Press ALT+F8
  • Select TableToList
  • Click Run

In Office 2003 you can add a shape to your worksheet, right click, and choose assign macro.

  1. Choose Tools > Customize
  2. Choose Macros > Custom menu item -> drag to toolbar
  3. Right click item
  4. Choose Assign macro…
  5. Choose TableToList

Since Office 2007 this option is not available anymore, but you can still right click the ribbon and choose ‘customize quick access toolbar’. From there you can pick the Macro’s category and add the macro.

A new sheet will be created. Take a look at the list. You can try sorting, filtering, analyzing, totalling, and… pivot tables. A pivot table is a dynamically updating table which automatically totals values from a list, and presents them in… a table. Here’s how to re-create the original table from the list:”

  1. Choose Data > Pivot Table
  2. Choose Finish
  3. Drag ColumnValues to the ‘column fields’
  4. Drag RowValues to the ‘row fields’
  5. Drag Data into ‘Drop data items here’

Voila, the list is back. That is, if it was a list of numbers. Pivot Tables are for numeric operations, if you had text in there, it won’t show anything (anything good).


Download the file here:


How to install:

  1. Office 2003: to install an XLA you need to go to Tools > AddIns and select the file with the browse button. Make sure the checkbox is enabled.
  2. Office 2007: Click on the Office Button in the left top, then Excel Options, then Add-Ins. Now select Manage… Excel Addins and click Go. Again browse and enable the addin.

You may wish to copy the file to the suggested Add-Ins folder. If you are on a network and wish to share the add-in with others, make sure to keep it on a network drive.

Once the Add-in is enabled you will see a new button that runs the macro. In Office 2007 the button is under the Add-Ins ribbon tab. You can also press ALT+F8, then type ‘Table2List.xla!TableToList’. The macro will be hidden in the XLA file, so you cannot select it.

An even quicker solution

Abu Yahya (see comments) gave me an even quicker solution. All kudos go to him for this.

First, start the pivot table wizard. Now in Excel 2007 and up you may have a hard time finding it! So, right click the quick access toolbar (it’s the bar with tiny icons on the top). Then choose Customize… and select Choose commands from: Commands not in the ribbon. Now find “pivottable and pivotchart wizard” in the list, and add it to the list on the right. You will see a tiny pivottable icon in the toolbar now.

Go on and click that icon, and then:

Step 1. Choose multiple consolidation ranges
Step 2. Choose I will create the page fields
Step 2b. Select Range of the table then Add to
Step 3. Choose New Worksheet
Step 4. Click Finish
Step 5. on the new sheet – Pivot table field list –> uncheck [ ] Row and [ ] Column
Step 6. There will be one value exactly in your pivottable. Double click it.

You will now see a new sheet with a list built up of the columns Row, Column and Value.

Step 7 (optional). Create a pivottable from this list to analyze your data.

One important note: you can have exactly 1 field that will show up in your data next to your row and column fields. That field has to be in the far left column of the data you select before consolidating. If you need more data in your final analysis you can combine fields with the “&” operator, using a formula like cell C2:  =A2 & B2.

How to create a Class

It’s three articles (1 2) now, it’s almost a book! Here’s how to create a class in my three favorite languages:


Method 1: standard

The advantage of this method is it’s obvious portability to other (e.g. compiled) languages. If you add getters and setters the link to java is easily made.

class Cube {
  var $colors;
  var $size;
  var $brand;
$c->colors = 'red,green,blue,yellow,white,orange';
$c->size = 4;
$c->brand = 'rubiks';

foreach (get_object_vars($c) as $property=>$value)
	print_r($property . ' = ' . $value . ', ');

Method 2: instant class

The advantage of this method is the fact that properties (any method or attribute) can me created on the fly, even using variables, e.g. ‘price’, ‘new’ . ‘price’ or even ‘new’ . ‘price’ . $date. So in the example below we are defining the class, but not even giving it any properties (though it could have some of course).

class Cube {}
$c = new Cube;

$prop = $colors;
$c->$prop = 'red,green,blue,yellow,white,orange';

$prop = 'size';
$c->$prop = 4;

$prop = 'brand';
$c->$prop = 'rubiks';

foreach (get_object_vars($c) as $property=>$value)
	print_r($property . ' = ' . $value . '

Method 3: instant object

The advantage of this method is that the object doesn’t actually have a class. Because of that properties can be invented at will, and they don’t have to be variables, shortening the code to a form that looks like the class actually was defined. Be careful with this though, other people who read your code will frantically look for the class definition and won’t find it if they don’t know about the use of stdClass. An equivalent, but not as nice looking, is to cast null to an object, as in “$c = (object) null;”

$c = new stdClass();
$c->colors = 'red,green,blue,yellow,white,orange';
$c->size = 4;
$c->brand = 'rubiks';

foreach (get_object_vars($c) as $property=>$value)
	print_r($property . ' = ' . $value . '


In javascript there are plenty of possibilities for creating objects. Classes however do not exist (not in a practical sense anyway). Any object you create is a ‘class’ in itself, and can be copied or extended on the fly.

Note how javascript’s actually iterates over all property names (not the values as you might expect).

var c = new Object;
c.colors = 'red,green,blue,yellow,white,orange';
c.size = 4;
c.brand = 'rubiks';

for (property in c)
	alert(property + "=" + c[property]);

Though it is correct that arrays and functions are both objects, and it seems an easy way of providing php’s foreach construct, the is not suitable for this. An array with 10 elements, with index 0..9 cannot be iterated this way, since the array is also a ‘Class’ and all its properties, e.g. the length property, will also be iterated. In the example below, if we added a method ‘show’, we would see the definition of the function, converted to a string. That’s right, the full source code of the method.

r = Array('red','green','blue'); = function() { alert(this); }
for (property in r)
    alert(property + "=" + r[property]);

(Visual) Basic

I will not consider VB.Net, since in .NET every program is object oriented (supposedly) and thus classes are at the base of the language. Anyway, it’s not more difficult than choosing “add item > class”, and almost all the code is created for you.

In Visual Basic it gets more interesting, since it’s not an OO language in itself. Again, just like in JavaScript, objects are more considered ‘containers for variables and functions’. The concept of subclassing does not exist in VB. OK, here it goes. I am assuming you have created a Standard Exe project. First, choose Project > Add Class Module. You’ll see a new module created named ‘Class1’. You can just rename that in the properties pane to Cube. Now add the code:

' method 1: public members
Public colors As String
Public size As Integer
Public brand As String

This is not the preferred way, we should actually create getters and setters for these. This is easy using Tools > Add Procedure. Name it colors e.g. and you will get the following code

Public Property Get colors() As Variant
End Property
Public Property Let colors(ByVal vNewValue As Variant)
End Property

To this you’d still have to add a private variable, such as m_colors, which would be used in your Get and Let methods. You can create a new Cube object from within a form or a module using “set c=new Cube”.

In VBA (Visual Basic for Applications) the procedure is exactly the same, though you don’t have to create a new executable. You can start by e.g. pressing ALT+F11 in Excel and you will be able to add a class module.

Finally, in VBScript you could either create a class definition as in VB (without the type names though)… or use the ExecuteGlobal method to evaluate code and, again, generate classes on the fly.