November 5, 2009

How to Sort a CSV File

Filed under: Automation, Scripting — Marcus Tettmar @ 11:39 am

This morning, forum user hip asked how a script could sort a CSV file. Seems CSV files, sorting and Excel has become a bit of a hot topic here lately. Since Excel can read and save to CSV and also has a Sort function we might as well make use of it. Here’s a little VBScript function I put together which will sort a CSV file by a given column:

VBSTART
Sub SortCSVFile(file,sort_column)
  Set XLApp = CreateObject("Excel.Application")
  XLApp.Workbooks.Open(file)
  
  XLApp.ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
  Set SortCol = XLApp.Range(sort_column)
  XLApp.ActiveWorkbook.ActiveSheet.Sort.SortFields.Add(SortCol)
  Set Cell = XLApp.ActiveWorkbook.ActiveSheet.Cells.Find("*", XLApp.ActiveWorkbook.ActiveSheet.Cells(1, 1),,,,2)
  Set mYRange = XLApp.Range("A1", XLApp.ActiveWorkBook.ActiveSheet.Cells(Cell.Row, Cell.Column))
    
  XLApp.ActiveWorkbook.ActiveSheet.Sort.SetRange(mYRange)
  XLApp.ActiveWorkbook.ActiveSheet.Sort.Apply
  
  XLApp.ActiveWorkBook.Save
  XLApp.ActiveWorkBook.Close false
  XLApp.quit
End Sub
VBEND

The function opens the CSV file in Excel – without making Excel visible – then performs the sort, saves the file and closes Excel. You won’t see Excel appear on the screen.

Here’s how to use it. If you want to sort your file on column B and don’t have a header row, use:

VBRun>SortCSVFile,C:\Documents\my.csv,B1

To sort on column A and you DO have a header row use:

VBRun>SortCSVFile,C:\Documents\my.csv,A2

UPDATE: Here’s a simplified version which should work in Excel XP/2003 and should be able to detect whether or not your data has a header row:

VBSTART
Sub SortCSVFile(file,sort_column)
  Set XLApp = CreateObject("Excel.Application")
  XLApp.Workbooks.Open(file) 
  XLApp.ActiveWorkbook.ActiveSheet.Range("A1").Sort XLApp.ActiveWorkbook.ActiveSheet.Range(sort_column),,,,,,,0  
  XLApp.ActiveWorkBook.Save
  XLApp.ActiveWorkBook.Close false
  XLApp.quit
End Sub
VBEND

What if you don’t have Microsoft Excel?

As mentioned in my reply on the forum another method you could use is to open the CSV file as a recordset using DBQuery and apply an “ORDER BY” clause to your SQL statement. That would sort it into memory. Then you would need to loop through the array and write the data back out to a CSV file using WriteLn.

Something like:

//new file to write to
Let>new_file=%SCRIPT_DIR%\example_sorted.csv
IfFileExists>new_file
  DeleteFile>new_file
Endif

//set WriteLn NOT to add line breaks (we'll add those ourselves)
Let>WLN_NOCRLF=1
//The CSV delimiter
Let>comma=,

//Connect to and query the CSV using ORDER BY PRICE to sort on Price column
Let>ConStr=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%SCRIPT_DIR%;Extended Properties='text;HDR=YES;FMT=Delimited'
DBConnect>ConStr,dbH
DBQuery>dbH,select * from example.csv ORDER BY PRICE,fields,num_recs,num_fields

//If we have records, loop through records and fields, writing out to new file
If>num_recs>0
  //first need to copy the header record ...
  ReadLn>%SCRIPT_DIR%\example.csv,1,header_line
  WriteLn>new_file,wlnres,%header_line%%CRLF%

  //the loop
  Let>rec=0
  Repeat>rec
    Let>rec=rec+1
    Let>field=0
    Repeat>field
      Let>field=field+1
      Let>this_field=fields_%rec%_%field%
      //write the field out to the new file
      WriteLn>new_file,wlnres,this_field
      //add the comma delimiter if needed
      If>field<num_fields
        WriteLn>new_file,wlnres,comma
      Endif
    Until>field=num_fields
    //add CRLF at end of line
    WriteLn>new_file,wlnres,%CRLF%
  Until>rec=num_recs
Endif
DBClose>dbH

//if you want, delete the input file and replace with the new sorted one:
//DeleteFile>%SCRIPT_DIR%\example.csv
//RenameFile>%SCRIPT_DIR%\example_sorted.csv,%SCRIPT_DIR%\example.csv

November 2, 2009

October 30, 2009

Convert XML to CSV

Filed under: Automation, Scripting — Marcus Tettmar @ 12:27 pm

Earlier this month I wrote about how you can read and write data from/to CSV files as if they were database tables using DBQuery. Andrew asked if I knew of a way that XML files could be treated as database tables in the same way. I did find a couple of references to some ODBC drivers online but one was not yet available and the other was part of a larger commercial package so I was unable to try them.

Since then it has occurred to me that there is a way we can convert XML files to CSV (or XLS) files using Excel. Once the data is in CSV file format we can then retrieve it easily using DBQuery.

The more technically aware will probably ask why we can’t just use the MSXML.DomDocument object in VBScript to read in the XML and parse it. Well, while that is of course possible, many will find the ability to access the XML data in a tabular database-like format easier and more familiar.

So, without further ado, here’s my ConvertXMLtoCSV function:

VBSTART
Sub ConvertXMLtoCSV(xmlFile,csvFile)
    Set xlApp = CreateObject("Excel.Application")
    Set xlBook = xlApp.Workbooks.OpenXML(xmlFile,2)
    xlBook.SaveAs csvFile, 6
    xlBook.close false
    xlApp.quit
End Sub
VBEND

You will need Excel installed for this to work. Use the function like this:

VBRun>ConvertXMLtoCSV,c:\docs\my.xml,c:\docs\converted.csv

And now you can quickly read the data into an array using DBQuery.

The function works quietly in the background. You won’t see Excel open – just a short delay while the CSV file is created.

To convert to an Excel file rather than a CSV file change the code to:

VBSTART
Sub ConvertXMLtoXLS(xmlFile,xlsFile)
    Set xlApp = CreateObject("Excel.Application")
    Set xlBook = xlApp.Workbooks.OpenXML(xmlFile,2)
    xlBook.SaveAs xlsFile, 56
    xlBook.close false
    xlApp.quit
End Sub
VBEND

Please note I’m using Excel 2007 and haven’t tried this with earlier versions though I believe Excel 2003 can also read from XML files. Success may also depend on the format of your XML.

See:
Reading From CSV Files
More on Reading and Writing CSV Files
Retrieve Entire Excel Sheet Using DBQuery

October 29, 2009

Quick Sort Routine

Filed under: Uncategorized — Marcus Tettmar @ 8:00 am

Back in 2006 I posted an example of a Bubble Sort or Insert Sort algorithm. In this more recent forum post, azzkicker_9002 asks for help creating a Quicksort function which is faster for longer lists. So I took the example found here on the alogorithmist website and converted it to MacroScript. I tried to post the code here but it screwed up WordPress, so you’ll have to head on over to the forum to see it.

October 28, 2009

Randomly Shuffle an Array

Filed under: Scripting — Marcus Tettmar @ 9:00 am

I was recently asked how to get a list of files from a folder, and then randomly shuffle that list. The following code retrieves the list of files to an array using GetFileList and Separate and then loops through the array shuffling it randomly:

GetFileList>c:\docs\*.*,file_list
Separate>file_list,;,files_array
If>files_array_count>0
  //randomize the array
  Let>k=0
  Repeat>k
    Let>k=k+1
    Random>{%files_array_count%-1},random_index
    Let>random_index=random_index+1
    If>random_index<>k
        Let>Temp=files_array_%k%
        Let>files_array_%k%=files_array_%random_index%
        Let>files_array_%random_index%=Temp
    Endif
  Until>k=files_array_count
Endif

Edit: As pointed out in the comments this is somewhat naive and could cause an element to be swapped back to its original position. A better method is given in the comments.

October 27, 2009

I am not Clairvoyant and I don’t have a Crystal Ball

Filed under: General — Marcus Tettmar @ 10:33 am

Honestly, I keep trying to buy a Crystal Ball and I’ve asked all our preferred suppliers, but no one seems to have one. Printers, mice, monitors, disk drives, and SATA II RAID controllers are no problem. But no one sells a Crystal Ball.

One would make my life easier. I could then answer those support responses we get. You know, the one liners like:

“Script doesn’t work”.

If we had a crystall ball I might have an inkling as to which script doesn’t work, what the user tried, how far he got, what the expected outcome was, what the actual outcome was etc?

In the absence of fictional wizardry devices there is of course the Macro Scheduler Debugger. That has all the clues. While I certainly don’t expect every user to be expert at using the debugger it is encouraging when an attempt is made to use it. This kind of support query is far more useful:

“The script isn’t working as I would expect. The output file is not being generated. I’ve stepped through with the debugger to the point where the file is supposed to be generated but in every instance the script branches to the end at line 47 because the the value of gContinue is always False and I’m not sure why.”

Great, I have something to go on. The answer is probably there in the script or the watch list but at least I know where to focus my efforts and we can do away with a game of email tennis.

Something even closer to a crystal ball is a service called BeamYourScreen which allows us to view someone else’s desktop. We can help you debug your script using this amazing technology, but I much prefer it if the other person has had a go at it first. If you get someone else to do something for you all the time you’re never going to learn how to do it yourself, so I believe a little prompting in the right direction is beneficial.

Of course, our priority support customers have access to up to 2 hours a month of BeamYourScreen support or training, and we can also offer hourly one-one BeamYourScreen consultations or training separately.

But, as yet, no Crystal Ball or clairvoyant support staff. So if you wouldn’t mind giving us a few more clues when you email support that would be much appreciated. 🙂

These links might be helpful:
Use the Debugger
How to get Support – Help us Help You

October 22, 2009

Windows 7 is Here, So Long XP!

Filed under: General, Windows 7 — Marcus Tettmar @ 9:38 am

Windows 7 Front Runner

So, unless you’ve been sleeping under a rock you’ll probably be aware that today is the day that Windows Vista gets it’s official upgrade in the form of Windows 7. We got our hands on a beta copy as soon as it became available to MSDN subscribers and back in January I was able to report that Macro Scheduler 11 is compatible with the new operating system. In fact Macro Scheduler 11 is now listed as a “Windows 7 Front Runner” application. These are applications that already support Windows 7 on launch date.

I’ve actually been running Windows 7 on my main desktop since the RTM (Release to Manufacturing) version was made available in August. It was an easy upgrade from Vista. I like it. It feels more responsive than Vista (though I have no idea if it really is) and I’ve encountered no problems. The UAC prompts that gave Vista such a bad reputation can now be manually adjusted so rather than the two options – “Off and completely insecure” or “On but potentially very annoying” – you now have a sliding scale of annoyance. Personally I never had any problems with UAC and I’ve left Windows 7 running with the default options on my main desktop.

Compared to the horribly insecure default mode of XP that allows home users to unknowingly delete system files and install trojans; UAC in Vista and Windows 7 is a godsend. The trouble with XP was that if you did try and do the sensible thing and run in a restricted user account you’d find that so many things didn’t work. It was a pain to then switch to an Administrator account in order to install some software or make a system configuration change. The problem was self perpetuating in the sense that since most users ran in the default admin mode, developers of software assumed this was the case leading to software that only worked when run under an administrator user. This in turn lead to more people running as admin and not bothering to lock down their systems.

I think pretty much every home user I know who runs XP has at some point ended up with a virus or trojan on their computer. I’ve had to come to the rescue many a time. For friends and family with children in the household I’ve always encouraged the parents to only allow their children to use a restricted account, but found that they gave up because sites and software that the children wanted to use legitimately wouldn’t work easily without first changing their account to an administrator. Not surprisingly the parent got fed up with the hassle and gave up, or forgot to set the account back to restricted, and eventually I’d be called upon to fix yet another case of weird behaviour (of the computer, not the child or parent) which turned out to be due to a virus, trojan or some other system problem brought about because as an administrator anything can happen without the user’s knowledge.

That’s why I now encourage these families to upgrade to Windows 7. When administrator privileges are required – say to install a piece of software or browser plugin – the administrator password can be entered and the job is done. They should still make sure their kids are running in ordinary accounts though, because kids will probably still click YES on every UAC box they see! As an ordinary user, if the child does something that requires administrator privileges they will need to ask their parent or whoever is the administrator to approve it and enter the administrator password if they do. Otherwise no harm can be done.

In my view UAC therefore means LESS hassle and MORE security for families and end-users than XP offered. Sure, UAC might be annoying for advanced users who make configuration changes frequently, but they could switch it off in Vista or “turn it down” in Windows 7. But for general day-to-day use I would advise against it. I’d rather know that something wants Administrator access when it tries to do something, and I can purposefully choose to start something with Admin rights when I know that I’ll need it.

When I’m not in my office I use an Asus Eee PC 1000H Netbook. It’s a nifty little lightweight machine that has only 1gb RAM and came with XP installed. The Netbook trend has been for smaller, lighter machines with a long battery life and that generally means keeping the specification simple with a basic processor and small RAM. Traditionally PCs have been going in the opposite direction with Microsoft’s operating systems getting bulkier and more demanding. So the choice for Netbooks has so far been Linux, or XP if you wanted a Microsoft OS. But we can’t keep using XP forever and Microsoft needed to make sure their new operating system ran well on Netbooks and indeed claimed that Windows 7 would support them. I was interested to find out for myself how well Windows 7 would run on my Eee PC and was keen to ditch XP anyway. I now have Windows 7 running on my Netbook and I am very pleased. It boots up quickly, appears no less responsive than before and there is no appreciable difference in battery time.

So for me Vista was an improvement and Windows 7 is the polished version. Unfortunately it’s not possible to upgrade XP to Windows 7 without doing a clean installation. I wonder if that might slow down the adoption rate, although I see that Windows 7 is the biggest pre-order item at Amazon UK, beating Harry Potter! I’m not sure what that says, but after eight long years it’s definitely time to say bye bye to Windows XP.

October 9, 2009

Introducing Macro Scheduler Lite – With 10% Discount

Filed under: Announcements, Macro Recorder — Marcus Tettmar @ 12:28 pm

Today we have released a new entry-level edition of Macro Scheduler called Macro Scheduler Lite.

Over the last 12 years, Macro Scheduler has gone from strength to strength and grown in power and flexibility to become the fullest featured, most capable automation solution on the market today. But we want to bring Macro Scheduler to more people, and not everyone needs the power of Internet protocol functions, Image Recognition, Custom Dialogs or Screen Text Capture. So for those who just want the basics we can now offer Macro Scheduler Lite.

Still a very capable automation solution, Macro Scheduler Lite contains the core easy-to-use automation features of Macro Scheduler Standard, including an intelligent macro recorder; functions to send mouse and keystrokes to other windows and applications; window and object Control functions; file system functions and the same script control structures; loops and conditionals and more.

Macro Scheduler Lite is ideal for the user just getting started with Windows Automation, who needs the essential features of an automation tool to automate straightforward but mundane and time consuming computer tasks.

Click here to compare the different editions.

We’ve also made sure there is a simple and fair upgrade path through all editions. So if your needs grow with time, you can upgrade for just the difference in price.

Macro Scheduler Lite is priced at only $49 USD. And until the end of October we’re offering a further 10% discount with coupon code: LITEISHERE. If you’re already using Macro Scheduler you may want a copy of Macro Scheduler Lite for home use, or for a colleague, or even as a Christmas present for someone in your life who could benefit from speeding up some of their computer tasks. You can use the coupon code as many times as you like, but it is only valid until the end of October 2009.

More Info | Buy Now

October 8, 2009

T-Shirt Winners for September

Filed under: Announcements — Marcus Tettmar @ 2:52 pm

MJT Net T-Shirts

After a short hiatus where we had no new names emerging in the winners list I’m pleased to say that the following two forum users will be receiving a flashy new MJT Net logo T-shirt each for points rewarded in September:

gpulawski: 20 points received
Waldo: 5 points received

Thanks to both of you for your valuable contributions on the forums and for continuing to help others out.

Each month I send T-Shirts to the people receiving the most reputation points in the previous month. So if you’re not already active in the forums, get stuck in – you could win a T-Shirt.

October 6, 2009

Macro Scheduler 11.1.15 Update

Filed under: Announcements — Marcus Tettmar @ 10:04 am

Macro Scheduler 11.1.15 is now available with the following changes:

  • Fixed: Compiled macros with -NOSTOPKEY option running slower
  • Fixed: CompareBitmaps not correctly comparing full image
  • Fixed: Text added by Command Locator cannot be undone
  • Fixed: New line not added when text added by command locator

Registered Downloads/Upgrades | Evaluation Downloads | New License Sales