VBA and Git

We all know that we should be using source control, but many of us don’t. For those of us working with Visual Basic for Applications, our excuse is often, “I can’t. What am I supposed to do? Keep the whole document file in source control? Yeah.. right….”. The answer is an emphatic “No”.  We shouldn’t be keeping Excel workbooks or Access databases or Word documents under source control. We should be keeping our *.bas and *.cls files in a repository though.

This is easier said than done though. You may be aware that you can export and import files into a VBA Project. If you are, you are also aware that exporting and importing all of those files is going to be painful if you have more than a handful of classes or modules. Luckily, our old friend the Microsoft Visual Basic for Applications Extensibility 5.3 library is going to come to the rescue again. The VbComponents collection has a couple of really handy methods: Import and Remove.  We’ll find the Export method is part of the VbComponent class itself.  We’ll need to get all of the files out of our project so we can set up our repo, so let’s start with the export.

The following method will loop through all of the code modules in a VBA Project and export them to a specified file path.

Public Sub ExportSourceFiles(destPath As String)
    Dim component As VBComponent
    For Each component In Application.VBE.ActiveVBProject.VBComponents
        If component.Type = vbext_ct_ClassModule Or component.Type = vbext_ct_StdModule Then
            component.Export destPath & component.Name & ToFileExtension(component.Type)
        End If
End Sub

Private Function ToFileExtension(vbeComponentType As vbext_ComponentType) As String
    Select Case vbeComponentType
        Case vbext_ComponentType.vbext_ct_ClassModule
            ToFileExtension = ".cls"
        Case vbext_ComponentType.vbext_ct_StdModule
            ToFileExtension = ".bas"
        Case vbext_ComponentType.vbext_ct_MSForm
            ToFileExtension = ".frm"
        Case vbext_ComponentType.vbext_ct_ActiveXDesigner
        Case vbext_ComponentType.vbext_ct_Document
        Case Else
            ToFileExtension = vbNullString
    End Select
End Function

This will work for any office application, but we only export standard modules and classes. I do this because we can’t import the code behinds of Forms, Worksheets, and the “ThisWorkbook” class back in. This is a drawback, but I find it to be acceptable because it encourages the use of classes and the separation of concerns. There shouldn’t be very much code in a code behind to begin with. Not being able to place that code into version control actively encourages us to put important code in a class or module that can be. Take note that the ToFileExtension function returns an empty string for objects that aren’t supported for import.

Now we can export all of the code in our project from the Immediate Window, very much like using a command line tool. Just type the name of the sub into the window (intellisense works here) and supply it a file path to export to. Pressing the Enter key will run the subroutine.


ExportSourceFiles "C:\Users\UserId\documents\MyProject\" in the Immediate Window


Now you can use this directory to set up a new Git Repository.  Seriously. Follow the link. I’ll wait.

Okay. You’re back? Good. Now you have your initial project under source control. Congratulations! You’re half way there! We just need to add a few lines to the .gitignore file. The .gitignore file tells the repository which files not to track. By ignoring office document files, we can keep our project in the directory with the rest of our repo, without worrying about Git tracking the changes. Here are the entries I’ve been using in my .gitignore file.

## Microsoft Office


The next thing we need to be able to do is remove all of the code from our project. If we don’t remove the code before importing from our local repo, we’ll end up with doubles of all of the modules. Things with names like “Car(1)” and “Extensions(1)”. It’s ugly, but it’s pretty easy to clean our project out with a routine very similar to ExportSourceFiles. The important thing to note here is that we don’t want to remove the DevTools.bas module that contains the code for importing and exporting our other code. I don’t know what would happen if we removed the module that was currently running, but I’d rather not find out. If you’re feeling brave, please let me know what happens.

Public Sub RemoveAllModules()
    Dim project As VBProject
    Set project = Application.VBE.ActiveVBProject
    Dim comp As VBComponent
    For Each comp In project.VBComponents
        If Not comp.Name = "DevTools" And (comp.Type = vbext_ct_ClassModule Or comp.Type = vbext_ct_StdModule) Then
            project.VBComponents.Remove comp
        End If
End Sub

Finally, we’ll need some code to import modules back into our project after we’re pulled an update from our remote repository. Again, this is called from the Immediate Window and needs to be supplied the path to your local repo.

Public Sub ImportSourceFiles(sourcePath As String)
    Dim file As String
    file = Dir(sourcePath)
    While (file <> vbNullString)
        Application.VBE.ActiveVBProject.VBComponents.Import sourcePath & file
        file = Dir
End Sub

Of course, all of this code is available from my repo on GitHub. So you can download it and try it for yourself. Just import the DevTools.bas file manually, and you’ll be able to use the tools in this article to install the rest of the repository into any VBA Project. Hopefully now that it’s easy to get your code into and out of your repository, you’ll be more likely to use source control and code like a pro.

More Popular than Ever? Beards and Masculinity in History.

I found a fantastic (yet brief and incomplete) history of the beard. I’m a believer that the modern man should rock a well trimmed beard. It’s both stylish and manly. Oddly enough, or perhaps not so oddly, current trends in facial hair are having economic impacts. I hope you enjoy this as much as I did.

This week came the startling revelation that, in the past year, manufacturers of razors and related goods such as shaving foam, have seen a drop in sales of more than £72 million pounds. Market analysts IRI noted that men’s shopping habits were changing


Jitters, they’re not what you expect.

To those of you who read my drivel for the software stuff, I apologize. There will be no mention of code this week, other than that one. You see, I’m getting married to the funniest person I know two weeks from now. Needless to say, I have more important things on my mind.

My beautiful wife to be is giving me the best present a schmuck like me could get, two daughters. So, I’ve got the jitters, but they’ve nothing to do with getting married. My fiancé is my soulmate and there is no doubt in my mind when it comes to making her my wife. What has me nervous is the solitary question of, “Am I good (Step-)Dad?” I know; it’s cliché. Every parent wonders if they’re doing a good job of raising their kids, but that doesn’t make the question any easier to deal with.

The only Dad I ever knew was the man who married my mother and raised me as his own. Let me make this clear, he was not what I would call a good man, but he was an excellent Dad, while he was still around. Furthermore, he didn’t have to raise me as his own. He could have treated me like what I was, someone’s else’s child. He didn’t though, and that is his one true redeeming quality. He stepped up and did what should be done, instead of just doing what he had to do.

My girls are lucky enough to have their Dads in their lives, but that doesn’t mean that I don’t take my job very seriously. I treat them like my own because it’s what they deserve. Anything less just wouldn’t be right. I guess that’s what I’m here to say today. I’m here to challenge every man out there to do what’s right, to go above and beyond the call of duty, and to remember that your wife’s kids are your kids too, even if they aren’t.

They’re not always going to like you or listen to you, but you better damned well be there for them when they need you. I’m sure I’ll mess up along the way, but every parent does. After all, we’re all only human. If my Dad taught me anything though, it’s that being there is what matters most when it comes to children. That much I can do, so there’s nothing to fear. Some kids are lucky enough to have a father in their lives, mine are lucky enough to have two.

In the Zen Zone

I was reading a blog the other day about Zen Coding and it really just bummed me out. Zen Coding is a very real thing. You all know what I’m talking about, even if you don’t realize it. It’s when you’re just in it, completely in it. It’s when you don’t exist anymore, you’re in the zone and there’s just the code, nothing else. There’s just the code and you make the computer dance. You bend it to your whim and will. It’s the most beautiful thing that can happen to a programmer… and I have not had that experience in a very long time now.

What’s worse than not being able to experience the bliss of letting myself go, of losing myself in the meaningless lines of text in front of me that I give meaning to, is not understanding why I can’t find that place. It’s utterly frustrating. If I did not know this state of mind, this Zen Coding, I would not care. However I do know it and this knowledge is a burden, but rather than whine and bemoan my sad state of affairs, I would prefer to explore why this state of zen has eluded me. Perhaps more so, I want to explore how I can attain it more often.

The biggest road block to finding the zazen of programming is distraction. When the phone rings or someone comes into your office, you have just been kicked out of the zone. It will take you longer to figure out where you were than it will take to deal with the interruption. These kinds of distractions can not be stopped and they are hands down my worst nightmare. It’s never just one either. These distractions come in packs. One phone call takes you away to deal with an emergency, then just as you’re finishing up that one, the phone will ring again. To medigate the damage from this you must finish your current thought. Whatever it is, it can wait 30-60 seconds for you to wrap up your immediate thought. You’ll thank yourself later for having one less “what the fuck?” to cope with when trying to get back to what you were working on six hours ago.

Interruptions aren’t the only distraction though, oh no. Email is a huge culprit too. If you can, only check your mail a few times a day. Don’t jump to every little thing. They emailed you. They don’t expect an immediate response, so don’t give them one at the sacrifice of your concentration and focus. While you’re at it, turn off those “oh so helpful” desktop notifications. They catch your eye and take your mind away from the task at hand. The longer you spend consecutively focused on your task, the easier it will be to slip into Zen Coding.

What is the real problem though? Why is it so hard to just get in the zone? I have one word for you, stress. Fear is the mind killer and stress is its asshole cousin. In order to be productive, stress must be removed from the equation. Stress will scatter your mind like dandelion seeds in the wind. Do whatever you have to do to reduce and eliminate stress from your workday. Five minutes doing push-ups, or simply walking away from your desk, will buy you twice that time back. I promise.

There’s one more trap that I know I fall into far too often. I’m not enjoying myself. In order to be productive and happy, you must be enjoying yourself. There is no other way to be one with you code, but to want to be. Sometimes this means putting off a new feature and fixing that crap you wrote six months ago. You know the code I’m talking about. You wrote it in a hurry, or just didn’t really know what you were doing yet. It sits in your code base like a giant stinking turd taunting you every chance it gets. There’s never time to fix it, so it stays there just festering and driving you crazy. I’m telling you, take the time to polish that turd into something you’re proud of. The next thing you know, you’ll have refactored half of your code base because cleaning up that one method or class slipped you into zen mode. You’ve gotten your mojo back and each new change and feature will be that much easier to implement. You owe it to yourself. It will be cathartic. Just do it. Trust me on this one.

I’ve been slacking…

about writing here at least. In reality, it’s been a really busy summer. In between work, trips to the zoo, horse riding camps, volunteering some time at Code Review SE and (oh, yeah) getting ready for our wedding, I’ve not had much time to think about this blog. Which is okay, but I did promise myself I would write something at least once a month.

It’s important to me that I keep that promise to myself. Most Programmers think that their most important skill is the ability to write clear and concise code. I would challenge that. We should generalize that and work on being able to write clearly and concisely whether we’re writing in C#, VB, or English. If we can’t communicate with the business, we will not be effective programmers. If we can’t communicate with each other, we will not be effective programmers. If we can’t communicate with the non-programmers in our lives, we will not be effective human beings.

I know I’ve been absent for a while, but I kept my promise. I’ve accomplished a goal and I feel better for it.

Until next time, Semper Cogitet.

Very Cool Writer/Reader Library

I found this native vba file input/output library over at the CodeReview Stack Exchange site. I thought you all might appreciate taking a look at it.

If you’ve not been to SE’s code review beta, you should really check it out. The people are ubër friendly and there’s a lot to be learned by letting someone else dissect your code. It makes you really stop and think about what you’re doing with every line of code you type.

Until next time…
Semper Cogitet.