PREFACE
These notes are from my course on analysis and modeling using Excel and it built-in programming language, Visual Basic for Applications (or “VBA”). They are designed for practicing engineers, scientists and others with an interest in leveraging the full power of Excel. The course is targeted toward intermediate to advanced Excel users, although no prior experience with VBA is assumed.
Excel has a rich set of features for calculation, visual display and user interaction that makes it a very good general tool for many engineering and other technical computations. With its built-in VBA programming environment, and the associated techniques taught in this course, it becomes a highly versatile platform.
There are many considerations when choosing an analysis or modeling tool for a given application. Excel VBA is well suited for computations requiring flexibility, customization, and parametric analysis. Its built-in math and optimization tools, and tailorable user interface, also make it ideal for rapid investigation and multidisciplinary models. In addition, the ubiquitous installed Excel user base enables broad sharing and co-development of analytical tools.
These course notes have been taught live to hundreds of participants over the past ten years. Hundreds more have purchased the notes in paperback and/or kindle format for self-study. The response has been overwhelmingly positive, and all the feedback received has been used to continually refine and tune the notes for optimal learning.
A three-step teaching methodology is used that addresses different learning styles and enhances retention. First, a realworld application is demonstrated that illustrates the topics to be covered in the upcoming section. Next, the fundamental concepts are introduced along with how to implement them in Excel, step-by-step. Finally, the newly learned material is immediately practiced with an integrated hands-on exercise.
My hope in publishing these notes is to help technical professionals make full use of the capabilities in the desktop version of Excel VBA. Best wishes in your learning journey!
Matt Moran
Kent, Ohio, USA
March 1, 2017
Engineering Analysis & Modeling with Excel-VBA v9.0.pdf
Below are the Excel files for the exercises in «Engineering Analysis & Modeling with Excel VBA: Course Notes». Download these files to your computer and use the desktop version of Excel to open them. Depending on your browser, it may take more than one step to get to the download option.
Be sure to enable macros in your Excel settings, and when asked by the opening dialog message. Otherwise, the VBA capabilities in the exercise files won’t function. It’s recommended to open the previous exercise from these files to work from for the next exercise, rather than building your own integrated file. This insures that you don’t inadvertently propagate undetected errors from excercise-to-exercise.
Ex1-Convection Sheet.xls
Ex2-Convection VBA.xls
Ex3-Fluid Properties.xls
Ex4-Condenser.xls
Ex5-Properties Userform.xls
Ex6-Pipe Design.xls
Ex7-Optimize Pipe.xls
Ex8-Condensing System.xls
“Good introduction and quick functioning using VBA was enabled by this course”, Michael R. Palis, Hybricon Corporation
“Gave me a lot to work with. Very helpful and hands on. [My favorite parts?]… It was all good”, Dale Folsom, Battelle
“Really enjoyed how much info was passed along in such a short and easily understandable method”, Will Rehlich, Noren Products
“Excellent… Good overview of VBA programming…”, John Yocom, General Dynamics
“Lots of useful information, and a good combination of lecture and hands-on”, Brent Warner, Goddard Space Flight Center
“I’ve been looking for a course like this for years! Matt was very knowledgeable and personable and walked his talk”, James McDonald, Crown Solutions
“Great detail… informative and responsive to questions. Offered lots of useful info to use beyond the class”, Sheleen Spencer, Naval Research Laboratory
«I worked through the course materials of ‘Engineering Analysis & Modeling w/Excel/VBA’ and would highly recommend it to other engineers.», Maury DuPont, University of Cincinnati
«…the exercises were very easy to understand… followed extremely well after the learning slides that came before them. The instructions were detailed enough to understand, but still left enough leeway for individual learning», Monica Guzik, Rose-Hulman Institute of Technology
INTRODUCTION
What is VBA?
Visual Basic for Applications (VBA) is the standard programming language for Microsoft Office products including Excel. VBA allows the user to automate Excel tasks by writing macros, subroutines, and functions
Why use VBA?
- Automate repetitive tasks
- Simplify complex Excel equations with Basic language code
- Reduce spreadsheet errors
- Make spreadsheets more maintainable
- Automate tasks in software programs such as SAP2000 or AutoCAD
Note: This post uses Excel 2013 but the concepts will apply to any recent version of Excel.
Do you use the built-in Excel LOOKUP functions? Do you use these functions to extract reinforcement data (area, diameter, weight, and etc.) from a range of cells? Yuck! I can never remember the syntax for the LOOKUP functions. Over the years I have made many errors with these convoluted functions. Not only are they error prone, but creating a range of reinforcement data is another possible source of errors.
Here are the functions that bridgeautomation uses to enter reinforcement data into Excel replacing the error prone LOOKUP functions.
Description
RebarArea, RebarDiameter, and RebarWeight returns the area, diameter, and weight in Imperial units respectively. The base units are inch and lb.
Syntax
=RebarArea(value)
=RebarDiameter(value)
=RebarWeight(value)
The RebarArea, RebarDiameter, and RebarWeight syntax has the following argument:
value – Rebar id. This is a string (i.e. #4, #5…….#18). This parameter must be enclosed in quotation marks (i.e. RebarArea(“#4”).
Start typing “Rebar” in a cell and a drop down box opens making it easy to remember the function name.
No LOOKUP tables or typing in reinforcement data into cells!
VBA Setup
Verify that the DEVELOPER menu item is visible.
If the DEVELOPER menu item is not visible navigate to the FILE / OPTIONS dialog box.
At the Options dialog box select Customize Ribbon and check the Developer checkbox and then press the OK button.
Hello World Example
Create a new Excel worksheet and save as an Excel Macro-Enabled Workbook (*.xlsm). From the main menu select the Developer menu item and then click on Visual Basic.
Select Insert and Module.
In the Project Tree in the left pane of the dialog box below click on Module 1. Enter the following code as shown below. You can either type the code in or copy and paste from code textbox below.
Source code for the HelloWorld function is below.
Public Function HelloWorld(flag As String)
If flag = 0 Then
MsgBox ("Hello World From Bridgeautomation")
HelloWorld = "0 passed-Hello From Bridgeautomation"
Else
HelloWorld = flag + " passed-Hello World From Bridgeautomation"
End If
End Function
Description
HelloWorld is a simple example function that shows how to pass parameters, return values, and use message boxes.
- A 0 value parameter opens a message box and returns a string message to the cell
- Any other numeric value parameter just returns a string message to the cell
- Non-numeric value parameter returns a #Value! error
Syntax
=HelloWorld(value)
The HelloWorld function syntax has the following argument:
value – Any numeric value.
The graphic below shows how to use the HelloWorld function. In the example below cell C3 is referenced for input. Entering the integer 100 as a parameter would have worked as well (=helloworld(100)).
The graphic below shows the final results in cell C5 for an input value of 3 in cell C3.
The Excel file can be found here: Example HelloWorld
References
- Microsoft, Excel VBA – https://docs.microsoft.com/en-us/office/vba/api/overview/excel
- Microsoft, VBA Concepts – https://docs.microsoft.com/en-us/office/vba/library-reference/concepts/getting-started-with-vba-in-office
The VBA programming language allows users to access functions beyond what is available in the MS Office applications. Users can also use VBA to customize applications to meet the specific needs of their business, such as creating user-defined functions, automating computer processes.
How is VBA Used?
VBA is used to perform different functions, and different types of users use the programming language for various functions. The following are the different parties that use VBA:
1. General users
Most users regularly use MS Office applications such as excel in their routine. VBA language is included in the MS Office package at no cost to the user. VBA is used to automate tasks and perform several other functions beyond creating and organizing spreadsheets.
For example, users require to automate some aspects of Excel, such as repetitive tasks, frequent tasks, generating reports, etc. The user can create a VBA program (macro) within Excel that generates, that can generate shear force diagram, bending moment diagram, autocad drawings etc.
2. Computer professionals
Computer professionals can use VBAs to perform more complex tasks that would otherwise take longer time and more resources to complete. For example, they can use VBAs to create custom add-ins for Excel that provide additional functionality to the application by introducing new functions that are not available in Excel.
VBA also helps computer professionals perform complex functions, such as replicating large lines of code, designing languages within MS Office applications, and merging the functions of two or more different programs.
3. Corporates
VBA is not only useful to individuals, but also to corporate users. Companies can use the VBA programming language to automate key business procedures and internal processes. Functions such as tracking minutes, processing of sales orders in real-time, calculating complex data, etc., can be implemented using VBA.
VBA can automate the abovementioned tasks to increase the efficiency of internal business processes. It also allows corporations to consolidate their data in the cloud to make it accessible from any location around the world.
This course is aimed for civil Engineer and detailed course content is given below
Visual Basic for Applications, otherwise known as VBA, is the coding platform attached to Excel; it’s clunky, archaic, inconsistent, and generally considered the feeble Grandad of the coding family or perhaps the runt of the litter.
So, with that introduction, it may appear like I am very wrong when I say every engineer should know how to use VBA, but hear me out…
Why is VBA the right choice for engineers?
The creation and upkeep of engineering products finds itself mostly driven by desk-jockeys. Whether your discipline is mechanical design, electronics design, FEA, lifecycle engineering, or another from the almost infinite number of roles, I am willing to bet that after your email client and any specialist software related to your role, Excel is your next most frequently used program.
In this post, I do not aim to cajole you into dropping your day job to become a VBA developer, but rather to highlight the three biggest reasons why I think it’s worth spending a days effort on becoming proficient enough to make those monotonous tasks we have come to accept in Excel disappear.
1. You already have it.
As mentioned above, VBA is part of Excel and is installed on your computer as part of Excel. Just strike ALT + F11 or show the developer tab and you will be able to start programming in VBA.
As VBA is so readily available to the masses, there is a huge community of people out there – this is great because any time you want to do anything you are unsure of, 99 times out of 100 you will find the solution in the first 5 Google results.
One copy and paste operation later and you can continue coding.
2. You already use it.
In software development, beyond the capability of the language to solve the problem, one of the biggest things the developer has to consider is the user interface.
For Visual Basic, Excel is the user interface.
And in most businesses, almost every employee is familiar with the program and knows how to use it.
For this reason, you can create something, pass it onto someone else to use and they will not have to pause and think about how to operate your creation. Excel is immediately familiar to them and therefore people can plug and play.
Imagine you have created a spreadsheet where you enter a few design parameters and it iterates to give you the best solution.
With VBA ANY user can easily enter the parameters and click a button to find the best solution. If you need to use ‘goal seeks’ for example without VBA the user would have to perform this manually, with VBA you can automate it all.
Not only can this save time with repeated use, but it can also, more importantly, reduce errors.
If you use a different programming language you would need to make it either interact with Excel or have an entirely different executable application.
3. You can save so much time.
Thirdly, and most importantly, the biggest reason I think you should take the time to learn some VBA is the ability to save yourself enormous amounts of time.
With only a small amount of the most basic VBA knowledge, you would be well equipped to save yourself so much time on boring and repetitive tasks.
The amount of time you can save from just a few lines of code is sometimes shocking and almost always embarrassing when you realise how much of your life you have wasted processing data.
Recently I was provided many CSV files which were not delimited. I needed to break this into multiple columns but the location at which to delimit was not consistent. Writing the code to automate this took me only a handful of minutes and the subsequent running of 30+ files took me no more than 20 mins.
VBA in the real world.
Earlier I mentioned how VBA can make painful jobs disappear quickly.
Take the example I gave when I had awkward CSV files that the basic excel tools could not handle.
The data looked like something similar to the raw data in the table below, where the timestamp was an inconsistent number of characters and the identifier was a fixed character length.
The task was to separate the raw data into two separate columns, one that contained the timestamp data and another that contained the identifier.
This can be solved by using formulas quite easily but when you have tens of thousands of data points per CSV it quickly becomes a boring and time-consuming task.
With VBA you can solve this problem once and apply it to all your data sets easily and quickly.
Below you can see all the code required to perform this task…
Sub example() Counter = 1 While Range(«A» & Counter) <> «» tempstr = Range(«A» & Counter) Range(«B» & Counter) = Right(tempstr, 3) Range(«A» & Counter) = Left(tempstr, Len(tempstr) — 3) Counter = Counter + 1 Wend End Sub |
It’s 12 lines, nine if you remove the blanks.
It’s simple coding and this is what I am pitching to you.
Not to be able to code The Matrix but instead with a basic understanding make your life simpler!
In word logic the code above effectively says “for each data point put the last 3 characters in column B and the rest in column A”.
It ran in 20.96 seconds for 63,000 data points!
You can see that when you need to repeat this task many times writing a few lines of code is certainly quicker than recreating and dragging down formulas. With a few more lines of slightly higher level coding, you could make this example run in just 2.23 seconds!
At the risk of sounding like a broken record, this is a very simple example of how one can implement VBA to make their life simpler and cut out the mundane Excel jobs which, at times, seem too common during the 9-5.
How hard is it to learn VBA?
The basics of VBA are FOR loops, WHILE loops, IF statements, and knowing how to interact into and out of Excel.
If you can already code in another language, you have a headstart as you will be familiar with the logic of various loops and statements.
If not, then you aren’t massively behind. The resources available to teach you how to become VBA proficient are almost indefinite and from my personal experience, I would recommend the WiseOwl tutorials.
Although there are a lot of videos in the playlists do not be discouraged. I found that after the first 15 or so I was equipped with the skillset to achieve most things and the rest was learned from Google.
If you’re keen to start learning, I recommend creating a copy of the spreadsheets and going through the video as the tutor covers it – but perhaps that is just my style of learning.
In conclusion
So, to wrap this up, you probably use Excel daily, VBA is already installed on your computer, good tutorials are free to watch, you can save time on boring tasks, and best of all you only need a basic understanding to start automating your boring tasks!
With all this being said, I hope I have made a strong enough case for you to at least think twice when you’re sat staring down the barrel of your next boring, monotonous, and repetitive task in Excel.
A final bit of advice would be if you do decide to learn VBA keep this as one of your closely guarded secrets!
When your colleagues find out about your new abilities you will forever be doing them favours and trust me from experience… I stopped counting the unrepaid favours a long time ago.