Wednesday, 12 August 2015

Code Today: Create a kml file with VBA

Hi, another nerdy post today. The other day I came across some code I had written that generates a .kml file that points to a street address. It is a little kludgy but it has worked for the last few years. First I will show the code, explain it, then I'll talk about what I'd do differently if I were to do it now.

Sub Create_kml()
    Dim Name, Details, Address As String
    'Get job details into RAM
    Name = Range("Q3") & Range("R3")
    Details = Range("M3")
    Address = Range("K4")
    'Open kml file
    Dim fso, tf
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set tf = fso.CreateTextFile("File Location" & Name & ".kml", True)
    'Write actual kml file
    tf.Writeline ("<?xml version=""1.0"" encoding=""UTF-8""?>")
    tf.Writeline ("<kml xmlns="""" xmlns:gx="""" xmlns:kml="""" xmlns:atom="""">")
    tf.Writeline ("<Document>")
    tf.Writeline ("    <Placemark>")
    tf.Writeline ("        <name>" & Name & "</name>")
    tf.Writeline ("        <description>" & Details & "</description>")
    tf.Writeline ("        <address>" & Address & "</address>")
    tf.Writeline ("        <styleUrl>#m_ylw-pushpin</styleUrl>")
    tf.Writeline ("    </Placemark>")
    tf.Writeline ("</Document>")
    tf.Writeline ("</kml>")
    'Clear buffer and finalise file
End Sub

So I may have to look into better ways of displaying code in Blogger. But I think you get the gist of this. The Name variable is used for the name of the waypoint in the kml. The Details variable is used for the description of the waypoint and the address is the street address for the pin to get put on. Looking at it you can probably omit the fso object as it is only used once so you would just have a longer command to set the text file object.

The tf object is created with a specified file. Then writing it is just a case of pushing lines to it. The only way I know of to use a template for writing a file like this is by coding it in place like this.

The biggest thing I would do differently knowing what I know now is that rather than hard coding the locations to get the variables (Name, Details & Address) from. I would pass them to the sub(or write it as a function) so I can copy the code and re-use it without any modification.

Any questions or comments are appreciated.

I hope this helps someone with a project somewhere along the line.