Sie sind auf Seite 1von 30

Hi there.

I'm going to show you how to use relative versus absolute referencing
mode when you're recording a macro. So I'm here in the Developer tab. I've got some data here and
I've just put some random numbers in. I've copied and
pasted this onto a second sheet just to make it easier when I
start to make modifications. I can easily copy and paste back here. So let's go ahead and
click into this cell. And right now it's in absolute referencing
mode which means it's going to record the absolute references, B5 and so on that
I click, and not the relative references. So let's go ahead and record a macro. So right now start with B5,
record a macro, so I name this absolute. Now what I'm going to do
is the cell to the right, I'm going to make yellow and
the cell below it, I'm going to make bold. And then what I'm going to do is I'm
going to delete three columns over which is column E. I'm going to right click on that
column heading and do delete. Now, I'm going to return the cursor,
the active cell, back to B5. I'm going to go to Developer and
I'm going to stop recording. Now, you notice, if I go to Visual Basic
and I open up the modules here, that we have the code there. So, this is what the macro
recorder recorded. This is the code. You notice that a lot of these things
are absolute references, right? Range C5 is an absolute reference, B6. Column E is a absolute reference. So let's go back
to Excel. And I'm going to just go back
to my second sheet here. And I'm going to copy, and I'm going to
paste and let's test our macro. So let's put it back in B5 and let's go
to our macros and run the absolute macro. You see, it did exactly what
we had wanted it to, right. It deleted column E and
formated those cells like we wanted. Now let's reset it once again. And now instead of starting in cell B5, I'm going to
start maybe
somewhere else before I run it. So I'm going to do Macro Absolute and
we're going to run. And it does the exact same thing. It didn't start in the active cell. It skipped back to those
absolute references B5 and so on. Let's reset this once again and we're going to record a Macro
in relative referencing mode. So I'm going to start with the cursor
again and the active cell in B5. I'm going to click on
Use Relative References. Let's go ahead and record a macro. Let's just call this relative and do the same thing, where in
the cell to
the right we're going to make yellow, the cell below we're going to make bold. I'm going to right-click on column E and
delete that, and then return the active cell to B5. And then we are going to stop recording. So let's first look at the code.
We go here, and you see that it has
a Sub Relative, and everything here. You don't see in terms
of absolute references. You do see absolute references
with respect to here. But it's always this,
when you have a dot and then something, this is a sub object of an object. So really this is offsetting
the active cell by three columns and then it's column AA of that
active cell which really corresponds to E in this case
if we started in column B. So let's go back to Excel and I'm going to reset, Ctrl+C. I'm going to paste it here and
let's first make sure it works in B5. So we run the relative and it does the
same thing, you see it deleted Column E. And so it's working fine. But now if we start in
a different active cell, so maybe I start down here,
-4, and we run this. It does everything in terms
of relative references. And you see instead of, so
we have a 6 at the top there. Instead of deleting Column E, because we started in Column C it deleted
three columns over, one, two, three. So that's sort of the difference between
absolute and relative referencing. Now let's do one more thing. I'm going to do sort of a mixed referencing mode
because you can change
the referencing mode during a recording. So let's go ahead and reset everything. I'm going to start in B5. Now this works
from my experience. It doesn't really work that well going
from absolute to relative during a recording, but
you can go from relative to absolute. So let's go ahead and start with B5. And I'm going to record a macro,
let's call this just mixed. And again same thing, so
we're going to highlight to the right, bold in the cell below it. And now I'm going to switch midway through
the recording, I'm going to unclick that and I'm going to right-click on, so
now we're in absolute referencing. I'm going to right click on E and
delete that. And then, let's go back to our cell
here and let's stop the recording. If we go back to our Visual Basic editor, you see in our mixed macro,
you see some, this active cell, this is a relative reference,
this is a relative reference. But now we switch to absolute and now
we have an absolute references here and then absolute reference there. So instead of returning
back to the original cell, it should return always to B5. It should always instead
of deleting three columns over like we did with the relative,
it's always going to delete Column E. So let's go ahead and
see what happens when you run this. So Ctrl copy and paste and now let's
start here like we've been doing. Let's go ahead and run the mixed. So this should do exactly
what we've been doing. So I deleted Column E. But now if we run this
starting in a different cell. So for example C7, the first part of our mixed macro
was run in relative referencing. So we should highlight D7. We should bolden C8. But then we switched into absolute.
So we should, instead of deleting three
columns over, one, two, three, so we deleted this column with our relative
referencing when we started on C7. We're going to delete Column E,
because it's an absolute reference. So let's go to our macros and we're going to run the mixed and
that's exactly what happens. Instead of this active cell returning
to the original cell when I recorded, because I was still in
absolute referencing, it goes back to B5,
which is what I had when I recorded. All right,
now you're going to have a quiz question. So you're starting here and
I'm going to record a macro. So watch the screen clipping,
the video and then I'm going to ask you,
which cell is highlighted yellow, if I ran the macro, starting with cell B3. And which cell is going to be bold?
In this screencast, I'm going to explain the difference between the two procedures that are inherent in Visual Basic,
Subroutines and Functions. Subs can be executed by running it from Excel. So you can do that straight from excel in the
developer tab, or you can associate a button with the different Subs. You can also run it from the Visual Basic Editor, or
it can be "called" by another VBA subprogram. Subs can be created with the macro recorder or you can type it in from
scratch. Subs can have zero arguments. Ninety nine percent of ubs do have zero arguments, that provide for values to be
input or output from the sub. The syntax for subs in VBA starts with just sub, and you have your name, and you have
your optional arguments. And again 99 percent of the time the optional arguments, this is just going to be empty left and
right parentheses. And then we end the Sub with End Sub. So let's go through an example. We're going to just create a
simple VBA Sub, that's going to ask the user for a number, and then it's going to square the number in a message box.
So I'm over here in Excel now, and to bring up the Editor, you've got to make sure you have the developer tab. So we
click on the developer tab and you go Visual Basic, or alternatively you can do Alt-F11. I've already been working with
some things here that I'm going to go over later in the screencast. But for now, let's go ahead and insert a module. You
always want to be putting your code in a module, and this is where we're going to put the code. So I'm just going to
name it Sub SquareNumber. You notice when I press enter, it automatically puts the empty brackets there, because all
subs need that. We're going to do something called Dimming, which you'll learn more about in subsequent screencast.
But dimming is essentially declaring that there are variables in our program. So I've dimmed two variables. I've dimmed
X as a double, Y is also a double, so it's double precision. Double essentially means that it's a real number. The next line
I've typed in X equals InputBox ( "Enter a number : "), so the user can provide the number X in something called an
input box. Next, we're going to calculate a new variable Y which is X squared. And finally, we're going to output the
square in a message box. So we've got an input box to obtain information, we've got a message box to output
information. Now very important, you never want to use input boxes and message boxes in functions, they're only
reserved for subs. So we're going to square the number, we're going to output that. You notice the formatting here, so I
have the square of your number is with the space here. This is a string in quotations, you can concatenate strings with
numbers using the ampersand. So let's go ahead and run this. I'm going to press F8 to step through this. You can press
F8 to run line by line. Alternatively, I could just run it all using this run button or F5, but I like to have the locals
window up. If you don't have the locals window, you can go to View locals window. This kind of shows you exactly
what's going on inside of your program. So I'm going to press F8, brings up enter a number, so I can put in five, I press
OK. And now, you see that it's taken in that five. We now run the next line using F8. We squared that to calculate new
variable Y which is 25. And then finally, we output that in a message box. And then we can end the Sub. So this is an
example of just a very basic Sub. So functions are the second type of procedure in VBA. It's a VBA Subprogram that
can be executed by using its name in a VBA expression or in an Excel formula. So on the sheet, you can type in, or in a
cell and you can type in equals with your user defined function name with your arguments. So, functions return values
in place of their names. Functions cannot be recorded, but must be typed into the editor. Functions can have zero-to-
several input arguments. In contrast to Subs, 99 percent of functions do have arguments and they're only, it's very rare to
have functions without arguments. But some of you might be familiar with the Pi function, which doesn't have any
arguments for the NOW function in Excel, which also does not have any arguments. Syntax looks like Function instead
of sub and we have End Function, and you have the name of your function, and your optional arguments. Let's go
through an example. Let's create a Function called savings, that will calculate the total savings given the principal
interest rate in time, in years. What we want to be able to do in Excel, is to type in a cell equal savings and we have the
three arguments: we have the principle, the interest and the number of years, and it gives us the amount, the savings at
the end of n years. So I've typed this into the editor, we have Function Savings. And the way that you dim or declare
variables, you don't have Dim statements inside functions. Instead, the arguments you, and you don't use the dim
statement, you say P as double, i as double, so those are real numbers P and i. N is only going to be integers, so you can
dim it as an integer, takes up a little less space. And then the output Savings, the output that's going to be provided by
the function is a double, so we put it at the end. You put the equation here, so the output of a Function is always the
name of a Function and that's equal to the equation P times one plus i to the n. And I can put this into a cell on the
spreadsheet. Just like you would another Function, a built in function to Excel and it ends up, we get our result. So just a
little bit of a de-brief here on Functions, User-Defined Functions. All functions begin with function. The function above
in Excel, you call it in Excel by typing in the Function. P, i and n are internal space holder variables, when I write this in
the editor, they're only using the VBA code. I could have just as easily written a, b, and c as long as I replaced that, I
have a, b, and c here. They're just used internally in that function. The value assigned to savings is output in the
spreadsheet cell when the function is called. Functions don't have to be simple, they can be super complex with loops,
if-then statements and so on. Every open macro-enabled workbook can use Functions and any other open macro-enabled
workbook. Real quick, I wanted to show you an example of a function with no arguments. This would be similar to Pi.
The golden ratio is something is equal to the square root of five minus one divided by two, it's just sort of a number. I
can define a Function GR, which will just give us the number, so point six one eight. I've also got a more complex
example here of a sub that has arguments. So this is a Sub that has arguments and that's what this is going to do is it's
going to delete rows on a spreadsheet. So I could say I want delete rows four through seven. This sub needs to know
where to start. So it's going to start at the fourth row. It's going to finish at the seventh row. And we have a sub here,
RunDeleteRows that's going to call the delete rows, Sub up here starting with row three and let's go through seven. So if
I run this sub using F8, you'll see that it jumps into the delete rows. We've passed arguments three and seven into this
sub on the spreadsheet. We're selecting rows three to seven and then we can delete those rows. So that's an example of a
sub that might have arguments. All right. Hope you enjoyed this screencast and thank you for watching.
Hello, there. This screencast is going to outline the OptionExplicit statement. Some of you may have been wondering
why on a lot of my, well, on all of my modules, I have an OptionExplicit statement at the top. So I will demonstrate why
that's important here. You notice here, I do not have the OptionExplicit statement. Just to show you something, I've got
to Sub here, I've defined a variable = 10. And I'm just going to do a MsgBox Variable + 2, so obviously, that should be
12. Then another MsgBox, that should display 14. And finally, another one with 16. So if I go through this using F8, we
set my, look in the locals window, I've got that as it should be. Then I press F8 again, and we get my MsgBox or my
Variable + 2 which is expected, Variable + 4 which is expected. And finally, the Variable + 16 which is expected. So it's
all fine and dandy, when you do everything correctly. However, what if I accidentally- spelling errors are quite
common, what if I accidentally spell this ai instead of ia? Then we run through this, and it doesn't detect that there any
problem, so we MsgBox the 12, we MsgBox the 14, and look what happens now? In MsgBox is 6 instead of 16. So
obviously, there's an error here and you wouldn't otherwise know because you haven't told the editor to look for errors
and declare all variables which is what the OptionExplicit statement does. So you wouldn't know better and if this was
in some sort of calculation, you would just assume that everything was fine and dandy. So to eliminate this problem,
what we do is we write the OptionExplicit statement at the top. And now when we run this, we notice that, first of all,
you need to define or declare all variables. So we're going to go ahead and do that first and we do that with the dim
statements that we've talked about a little bit and we will talk about more. So we dim our variable, in this case, which is
going to take an integer value, so I m just going to dim it as an integer. And now we try to run this and it's going to catch
those spelling mistakes or it's going to catch things that we haven't dimmed. Mainly, it's for spelling mistakes. So then
we would go in there and we'd say, "Okay. I'm gonna go ahead and switch this back to variable and now everything
should work fine." We do the 12, we do the 14, and finally the 16. Instead of having to write this every time, the
OptionExplicit statement, you can go up here to tools, and you can go into options. And if you go into the editor there,
there's a required variable declaration, just make sure that's clicked on. By default, it's clicked off. So just click that on
and it might not take place right away, but the next time you open up the editor or Excel, OptionExplicit statement
should be there. All right. So this sort of clarifies why you need to use that OptionExplicit and how to make it automatic
on all of your procedures.
Hi there. I'm going to kind of explain how to declare variables and I'm going to talk about data types and the scope of
variables in this screencast. So, I'm sure a lot of you have wondered what it means to have Dim statements, and so for
example, we have a Dim statement here, we're dimming all these different things as doubles. So, I'm going to kind of
talk about what those are, all variables if you have the Option Explicit need to be declared, that's what dim means, dim
is for dimensionalize, you basically set aside space for it. So the most common type of data in VBA is a double, that's
used for numbers with decimal fractions and high precision exponents extended range. This is essentially, you can think
of it double as a real number. The precision is 15 to 16 significant figures, integers another common data type. Strings
are also quite common, we're going to have a whole module just on working with strings. Single used to be one of the
most common types before because it uses only half the memory as doubles. Long which goes from negative two billion
to two billion, they're integers. Booleans are a data type where it's just true or false. If you don't do dim, the default is
variant and it's sort of adjust accordingly, so it sort of detects what it is. And then, another common one would be range.
You can also dim things as currency, as dates, as, you know, there's all sorts of data types. Let's talk real quick about the
scope of a variable and that is how far is the reach of the variable and where it can be seen. So, you can make it, so it's
only within a single procedure, so it's local to either a sub or a function. And this is declared using a dim or static
statement within the procedure. Or it can be within the current module. So you can dim something and you can declare a
variable and it will be available throughout the entire module. So I've got an example on that. You can also use the
public statement to demit in all procedures in all modules open in the current workbook. So just kind of as an example,
we might have a workbook this blue, square, rectangle might have two modules. If you dim k outside of the module,
then that means k here is going to be available to both sub one and two this funky function. Why, here is only going to
be available to the funky function. It's not going to be able to be seen anywhere else. We've got this public R, if you
make it public, then this is going to be available to anything in the workbook not just in module two. So, we could
reference that, we wouldn't have to re-dim it in any of these modules. J here is only in sub two. And when you're making
functions, so the argument of the function is only within it's just local to that function. So let's work through an example.
I've got a sub here we just calculate pi, four times the R tangent of one, we get the radius of a sphere in an input box, we
calculate the surface area, we output that in the message box and then I subcontract out the work of calculating the
volume to this sphere volume function. So let's go in step through this using F8, we obtain this in an input box, we
calculate the area, we message box that. The surface area is 314. And now into the sub, sorry, into the function. But you
notice that we have a problem here, because pi hasn't been declared within the sphere volume function. So to bypass
that, you could dim pi as a double. We also need to define what pi is separately in this function. So now, when we do
this, when we run the sphere, enter a radius of five, it displays the area, and it also displays the volume. However, if we
wanted to, we can dim pi outside at the modular level, so I'm going to just eliminate this. I'm going to delete pi here and
the pi here, I'm going to dim outside of the procedures. This is that the modular level. You notice that I'm using pi here
and assuming we defined it in kind of a stepwise fashion, when we jump into the function here it's already going to have
the value of pi because pi is at the modular level. So let's go ahead and run this. We get five and get the surface area, and
also, the volume. So, we don't have that error that we did when we dimmed pi inside the module. So, what if this
function we're in a different module. So in module two, if that's the case, it's not going to work because dimming pi
outside of the procedure here, this is only going to be available to all procedures in module one. So to bypass this, we
can use the public statements. So now pi is going to be available to everything in the workbook, so any module in this
workbook including module two, in which we have pi. So, we can see when we step through this, that it goes in to the
function on module two, but we still have the value of pi and we message box that and that's exactly what we got earlier.
So, if you're working with procedures that are in different modules and you want to be able to pass the value without
redeeming, then this is how you can do it. And it's tremendously useful if you know what you're doing. All right, real
quick, I wanted to explain what this static statement is. So, here I just have a non-static example. This sub I'm dimming
d an integer and I'm just saying d is equal to d plus one and I messagebox that. So let me show you what that does.
Rerun the non-static. And so I run it. It gives us a message box of one. We run it, it's one, we run again, it's one. All
right. So, it basically resets the variable every time you run it. However, there is if you static, if you insert a dim you can
write static d as integer. It's exactly the same as the sub up here, but let me show you what happens. So that's this run
static. We run it once, and it displays one, run it again, it's two, so it keeps the value and we're adding one every time. If
you close the file and reopen it, it's reset to zero, but this is how you can remember the value of a parameter. So here's
kind of a cool example of some more complex things we can do with this static variable. This sub is the same as it was.
I've added this optional reset as boolean and I have another line here. If reset, if that's true, then d equals zero. So there's
this optional argument to a sub and it's boolean. So if it's true, so if reset is true, then we're going to reset d to zero. All
right, so this is how we can reset a static variable back to zero. And we have to run the reset from another subroutine.
So, all this does is it runs the static example and passes the argument if true through here. So when we run this sub, it's
going to pass through, it's going to then reset d to zero. So let's go ahead and show you what happens and we're still
running the static one, two, three, four, five, and so on. And now, when I do reset, it resets d to zero, but in the first line
is to increment it by one and we get the message box. So I hope you learned a lot about declaration of variables, data
types, and the scope of variables. Thanks for watching.
Hi there, this screen cast is
going to go over how to debug and to step through lines of your code. I've got a pretty complicated example
here that calculates the exponents of a number and
this is in a file called debugging.xlsm. So if you want to pluck
this off of the course site then you can work along with me. So I've got this sub,
got some kind of advanced programming structures here
that you haven't learned yet. Regardless, I wanted to kind of
explain what happens when you debug. So the most important thing is to
have this locals window open which is down here on the bottom. To make that open,
you go up here to the view menu, and you do locals windows to
make sure that that's open. And that's really important,
this is kind of where we see. So we're into the brains of the editor and
what's going on inside of its head. So I'm going to step through line by line. There's this debug drop down menu up here,
and you notice that there's
a step into which is F8. So I just press F8. I put my cursor inside the procedure
somewhere and then I'm going to press F8. So I press F8 and
we're going through here. You notice when I just executed
this x equals 2.1 line. Down here in the locals window you
can see what the editors has for all those different values. And this is an invaluable way to look,
to kind of troubleshoot and to see what's going on
inside your program. So I'm going to press F8 a couple
more times and we go through. You noticed that in this line
here I've got another function. So in this sub, it's jumping out
of that into another function. And then we go through that function,
and it outputs and now we can look at the value of s here at
this point in the code is equal to one, and now I press F8 again,
we increment I by one and so on. So this is how you can kind
of go through your code. I wanted to show you some other things
that you can do while you're debugging. Now let's say I'm pretty certain that my
factorial function is working properly, and it's sort of a pain
how it steps into here and you just have to keep
pressing F8 a bunch of times. So if I wanted to step over is what
it's called when I execute this line, I want to go straight from
this line to the next I line without jumping down into the MyFactorial. While on the debug there is
a Step Over which is Shift-F8. So I'm just going to when I'm back over
here I'm just going to do shift-F8, and we Step Over any other procedures that
are on that line like a function here. If we do go into a sub
procedure like this and I want to step out of,
we can go up here to Debug. And you can go Step Out. You can click on that or
I can do Ctrl+Shift+F8. So here if I do Ctrl+Shift+F8,
I step out of that other procedure. Another thing I wanted to show you
is let's go back into this function. Now maybe I just want to
run to a certain line. I can put my cursor here, and
I can do Debug, Run to Cursor. Alternatively, you can set your cursor and
you can just do Ctrl+F8. So you'll learn these key
combinations as you go. Now, another thing I want to show you. Let's go ahead and
reset this up here with that reset button. There's a couple other
interesting things you can do. One thing, if you just want to
run until a certain point, you just want to stop when it gets
somewhere, I can put a break point. So I'm going to put
a break point right here. You just left-click in this side bar and
then you can run using F5 or pressing this Run button and it will just
run until the code hits that breakpoint, It's basically like a stop sign. And then you can kind of look at
your code to see what's going on. And then you can debug from there. Or you can press F8 to do line by line. And in this
case,
that just finishes this up. Or you can just run again to
the end of the procedure. And then to remove a break point
you just left click again. There's also some things that you can do. There's something known as
the Debug.Assert function, so you can put this inside your code,
you actually got the right align of code, and
it's sort of counter intuitive, but what if I wanted to
debug until s becomes five. Now it's counterintuitive, because
it's going to go until this is false. So it's going to go, and go, and go. And then as soon as this is false, meaning
s is equal to or greater than five. It's going to enter into debug mode. So if I just run from here, press that
run button or I'm going to press F5. [SOUND] See how it ran, and
now 5.3 is no longer less than five, so this is false and
now we're in debug mode. So then you can do F5 from there. Another thing we can do, and let me
delete this line, this Debug Assert line. Another thing we can do is,
you add a watch. So I'm going to go up here to the Debug
menu and I'm going to add a watch. And this is similar to the Debug.Assert. Except you're going to break when, and the
example I'm going to use is
break when the value is true. So I'm going to say,
I'm going to break when i = 4. So I'm going to go, we're going to run
this, and as soon as i = 4 it's going to go into break mode then we can
press F8 to debug through. So down here in the watch type, there's a couple of them I want to do
when break when the value is true. So when value,
i = 4 we're going to go into break mode. And then I'll go ahead and press okay. You'll notice that there's
a watch down here. So now I put my cursor back into that and
I run. You see that we broke when i = 4,
so we've gone until i = 4. This is just an advanced
debugging technique. And then I can press F8 to keep going. All right, I really encourage you to become familiar
with these debugging techniques. They're really going to help you out
especially as you get to more complicated things in DBA. Thanks for watching.
In week two, we're going to do the following. So we've got six main objectives, and they all sort of relate to user-
defined functions, more or less. The first objective is to write proper VBA expressions. So there is a proper way to write
syntax in VBA. It's a lot like Excel or how you would write it on a programming calculator. So I think many of you
have prior experience already that can relate directly to writing VBA expressions. The second objective is to write code
that borrows Excel functions. There are built-in VBA functions that you'll learn about, but there's also ways that you can
borrow Excel functions. So VBA can borrow Excel functions, and I'll show you how to do that. The third objective,
create your own user-defined functions. So maybe you're working with some equation or some sort of function that isn't
already built into VBA or Excel. You can create your own user-defined functions and use those in VBA subs and other
functions and also in cells of the Excel spreadsheet. Four, you're going to learn to troubleshoot user-defined functions.
Troubleshooting, stepping through is not quite like it is for functions as it is for subroutines. So you'll learn about how to
troubleshoot functions. Five, you're going to write code that calls other subroutines in the same or other files. So you can
call subroutines that are in the same file, or you can open up other files and run those subroutines. And six, you're going
to design a subroutine that uses a modular programming approach. So I'll talk about how you can take standalone
subroutines that individually work by themselves, and you can kind of combine those into a modular program. So let's
go ahead and get started with week two.
All right. I'm going to just go through the VBA operators that we used to construct code, how we multiply and divide
and do different functions in VBA. It's a lot like you do in Excel, so if you're quite familiar with Excel, it's almost the
same. There are a few differences and also if you have experience working with a programming calculator, sort of the
same thing where you working with the order of operations. Shown here on this slide, we have the order of operations,
exponentiation comes first. That's in contrast to Excel. Excel actually is unique in that it does negation first. So if you
did -3^2 in Excel, it would give you 9, which is a little bit counterintuitive, but it negates first. Whereas in VBA, it does
the exponentiation first and then does the negation. So in VBA, -3^2 would be -9. Multiplication, division or the asterisk
and the forward slash you can do integer division using backslash. There's a really popular function called, at least in
this course it's popular it's called Mod. So that's the remainder. For example, if we did five mod three that would give us
two right. So it's going to be used quite a bit in this course. Addition and subtraction plus and minus, if you're joining
two strings or a string with a number you can use the ampersand which is this symbol and that's joining two strings or
joining a string in a number. It's used a lot in message boxes and input boxes. Relational operators we have >, <, >=, <=,
=. And this is <>. So this is the equivalent of the not equal we'll do some logical examples here in this course. We also
have the not, so not true is false, not false is true, and meaning it'll give you a true like if a and b are both true, so
whatever comes before it and after it has to both be true or means one or the other or both have to be true in order for the
combination to be true and then something XOr something means exclusively or meaning you have to have a true and
false or false and true but you can't have both trues it has to be one has to be true one has to be false. VBA has got a lot
of built in functions. Some of the most common ones are shown down here as I'm going to show in a future screen cast
and one of the other screen cast is how you can use excel's built in functions, so in VBA there's a lot of these common
functions we have the absolute value, the square root exponential very importantly the Log function in VBA is the
natural Log, some others the message box function, input box function are really important of you prior to seeing some
of those and some examples that I've already gone through some of the screencast in this module. Let's go through a
couple examples of how you would put this into VBA syntax. If we had y plus 2 point times X minus 2 over this
denominator, the way you do that in VBA, you would write it like this. And the way that VBA interprets it is it always
does functions first. So it calculates the square root, returns an answer to that position. It then starts with parentheses
order of operations so computes the Y result. Then it computes the X minus to result it multiplies those two to get a
numerator- result and then it starts with the left on the denominator calculates the X squared result, and it computes the
X times Y result and adds up all three in the denominator and then it divides the numerator result by the denominator
result to get the final answer. So that's sort of how VBA calculates these different things it's a lot like your programming
calculator word kind of works left to right. Alright, let's go through a couple more examples. We have pi squared over
for L. There is no built in PI function. So, a good way to denote pi in VBA is to do four times the Archangel one. The
tangent of pi over 4 is equal to 1 so you can use that property to define that as Pi. So we can either write it like this to
this expression on the right on the left would be written like that or if we don't use parentheses in the bottom we can
divide twice because the left to right the way that VBA reads syntax is left to right so we can do that. This one we would
have t minus t l divide by quantity a Times quantity th minus tl. So you can denote you can force the order of operations
using parentheses and if we didn't want to use these outer parentheses here, you can always do the same thing like we
did above where you divide by and then take that result and divide by th minus tl. Another example that there's an error
in this and I want you to try to figure out what's the error in this. So what we don't have is an asterisk right there. So
there should be an asterisk between the two and the left parentheses. What about if you want to take the sign of 45
degrees, could we just use sin of 45? Be careful because in VBA, the sin, the trig functions, the arguments have to be in
radians so if you wanted to do the sin of 45 degrees, you'd have to first convert it to radians. What about logarithms and
exponents? Well, the natural log of Y. So we could take the exponential both sides of this equation and we get the right
hand side. So remember that property. The natural log is the log function so if you're wanting to use natural log it's just
LOG, the exponential function is just the exp(x), if you want to write this. We could do just some properties you could
take ten to the both sides of this equation. This is Antons equation some of you may recognize and to write this in VBA,
we would have to do it change of base, take log of the number divided by the base and that is equal to In this case log 10
of P we could write this expression 10 carat in parentheses A minus B divided by quantity T plus C. So that's it for basic
expressions in VBA. Thanks for watching.
There are a lots of built
in functions in Excel. For example,
I can write in the square root, there's the square root built in function. There is the average function,
there's lots of these. So in this screencast,
I'm going to show you how we can make a user-defined function, so
a custom function in Excel using VBA. So we have a cone here and we want to
compute the volume of this cone. We want to be able to type
in something like ConVol and type in the radius of maybe 4,
and the height of maybe 6. Press Enter and it'll compute
the volume using this formula. So right now there is no built-in
function in Excel to do that. So let me show you how to do that. I'm going to go ahead and insert a module. Just like
subs, functions are placed
in new modules, so I'm going to. And they don't have to be new modules,
they're just placed in modules. You can have multiple procedures
within the same module. So I'm going to call
this function ConeVol. It's going to have three arguments. It's going to have R, h, sorry,
it's only going to have two arguments. So it's going to have R and h. Now you don't Dim your arguments inside
the function as you do in subroutines. Instead, in parentheses here,
in the ConeVol function, this is where you deem things. This is where we declare
the radius as a Double. We could also do the same thing for
the height as a Double. And then the output of the ConeVol
function, we want that to be a Double. So we can put Double at the end. So the output's going to be double. And you
don't ReDim,
some people are tempted to write Dim R as Double inside the function. But that actually wont work and
it'll give you an error. And if at the end of this screencast, I'll
show you what happens when you do that. But if you need to define new
variables inside the function. For example,
I have pi in my cone volume function.. I can do that here, so
just like we would in a subroutine. So Dim pi as Double. And I'm going to, for now, I'm going to define pi as equal
to 4 times arctangent of 1. There is no built-in function for
pi, like there is in Excel. You can borrow the pi function as
I'll show in a subsequent screencast, you can borrow it from Excel. But for now,
4 * Atn(1) is a good way to get pi. The output of a function is
always the name of the function. So whatever you want to
be output in the cell, that we type the formula in in Excel,
that has to be named, there has to be a variable named
ConVol inside of our ConeVol function. So I can do ConeVol equals, now this is where I'm going to put the
right-hand side of the volume equation. This is just equal to our pi,
that we've defined, * R squared * h,
that's input by the user, / 3. And there is our cone volume function. Now I can go over here and
I can type in ConVol of, let's say radius of 4 and a height of 6. And when I press Enter, it'll calculate
the volume using this formula. So this works just like
other functions in Excel. I could do a case study using it,
I can drag it just like other formulas. I can name this cell Rad for
radius, then I can go up here and I can type in my ConeVol function with
the radius that I've defined down here. I want to keep a constant radius of 4, but I want to do a case study on
the height changing from 0.5 to 4. The second argument I can just use as my
height there and I can press Enter and then I can drag this down, just like
you would other formulas in Excel. So let me show you what happens if
we Dim R inside of the function. Some people think that they
have to ReDim the arguments, as I alluded to earlier, Dim R As Double. But when we try to do that then,
let me go back over here and press Enter. [SOUND] It gives us an error that says
duplicate declaration in current scope. So you can't ReDim the arguments
that you put into the function. So we need to go ahead and delete that. So this is how you make just a basic
user-defined function in VBA.
All right, I'm going to work through an example here of a user-defined function in VBA, fuel efficiency of an 18-
wheeler. So, the fuel efficiency of miles per gallon is highly dependent on the speed in mile per hour as well as the
weight of the truck in pounds for obvious reasons. So, the efficiency is given by this expression here, where we have the
weights in pounds, and we have the speed in miles per hour. And our goal is to create a VBA function called efficiency
with arguments of weight and speed that outputs the fuel efficiency of a truck miles per gallon of the truck of weight w
traveling at the speed of s. So, I'm over here now in Excel, I've just copied and pasted my formula. So, we're going to
develop this user-defined function, and then, we're going to use it and test it to determine the efficiency in miles per
gallon of a truck that weighs 60,000 pounds traveling at 80 miles an hour. Let's go ahead and go into the editor. We're
going to insert a module, and I'm going to name this function efficiency. It's going to have arguments w and s, and w is
going to be dimmed as a double, the speed can be double, and the output we want to be as double. So, let's just go back,
Alt F11 and we got this function here. So, I'm just going to type it in as an expression. So, I typed this in, and noticed,
I've got the output of the function, just the name of the function. I'm not using a message box. You never use message
boxes in functions. So, I've got efficiency equals all that stuff, that was in our equation. So, that should work. Now, let's
go ahead and go back here, and we can take that in. So, efficiency is the name of our function, and we want to calculate
the efficiency with a truck weight of 60,000 pounds and a speed at 80 miles an hour, so I just put those two arguments in
and I press enter. And this means then, trucks don't get that, get of gas mileage, but the miles per gallon of that truck is
going to be four point nine five, and I'm just going to decrease decimal a little bit. We could also look at the effect of
increasing the weight, obviously you should decrease that. If we drive a lot slower, we have a lot less wind resistance,
which goes as it's an exponential of the speed. So, we get better gas mileage. I hope that gives you kind of an idea of
how we can use user-defined functions to create custom made functions in Excel.
All right. I'm going to revisit an example that I've got a screencast on just another example of a user defined function in
VBA. It's related to the efficiency of a semi truck of weight W and traveling at a speed of S. So what we going to do in
this screencast is convert a user-defined function. If I go back to the editor, we have made a efficiency function, user-
defined function but we want to convert this into something more akin to a built-in function where we want to be able to
use it in all workbooks on our computer without having to bring in that function. The code for it into each of those
workbooks. We want to be able to create it such that we can use that efficiency function for all workbooks that we ever
use on this computer much like a built in function. Some of you might know that you can add in different types of things
into Excel for example I have already added this in, there's a solver add in and there's a data analysis tool pack. To add
those into Excel you go to the file menu options and you can do add-ins, and then you can click go down here. These are
some of the things that you can select from and this is how you would select the analysis tool pack and the solver add-in
for example. So we're going to convert this our efficiency function into an Excel add-in that you can then add in and use
it for all of your workbooks. To do this you go to- we're going to save this. We're going to save this file. The one that
has our efficiency function. So we're going to save that as something known as an X Lamme file or Excel add-in. So I'm
just going to navigate to someplace where I know I can find. So I'm going to navigate to the desktop. I'm going to save
this as just efficiency instead of being a macro enabled workbook I'm going to save it as an Excel add-in, so that's kind
of down here at the bottom. So we can, for some reason change my path, so desktop efficiency and I'm going to save
that on the desktop. So this is known as an XLAM file. So now I'm going to insert a new workbook and I'm actually
going to close down my other file and it doesn't matter what file we are doing this on but I just want to open up a new
file just to show you that this works on any workbook. So we can go to File, Options, just like we would add in the
solver tool pack or the data analysis tool pack, I can click on Add-ins and if it's not shown here, a lot of times it won't be
shown here, the efficiency is the one that we want to add in. So I'm going to hit down here to go and then browse. So we
can browse then to the desktop and we can click efficiency. I was already working with another one earlier, but I can
browse for efficiency and now I can click on- make sure that's clicked and I can click Okay and it brings it in. And now
any workbook that I have, this is a brand new workbook has nothing to do with that other file that had the efficiency
function within it. And I can type in efficiency and you can see as I start to type that in, it's got that. So I could put in I
think it was the weights and then the speed something like 65 miles an hour. This will tell us our gas mileage. So that's
how you can then use- you can convert essentially a user-defined function into a built-in function using the techniques
in VBA and Excel.
All right. I'm going to show you in this screencast how we can borrow Excel functions in VBA to create user-defined
function. Unfortunately, in just regular Microsoft Excel, there is no range function to calculate the range of data array.
For example, the max minus the min. So in this case, the max is 10 and the min is negative nine. So we would like to be
able to easily tell that the range is 19. Fortunately, there's the min function which will tell you the minimum of a range
and the maximum function. So, we can borrow those. Just like we can borrow all sorts of Excel functions, we can
borrow those mini, max functions to create a user-defined function called range. So, I'm over here in Excel. I'm going to
go ahead and bring up a module, and let's go ahead and insert a new module. So I've named this range. I've dimmed my
range as a range, and range is going to be a double. So there is no max function built-in to VBA but what we can do is
we can borrow Excel's max function and Excel's min function. And when I do that, we end up with the output of the
function, which is range is, now I'm using Application.WorksheetFunction.Max of the range. The range is the argument
to the range function. So rng is the argument, minus the min. So we're borrowing that from Excel when we do
Application.WorksheetFunction. You could also just leave off the application. So that works since we're just associated
with Excel, which is the application. So either with or without the application, regardless, we create the range. So, let's
go ahead and see if this works. I'm going to type in range of this array and we end up with 19. So that's how you can
borrow Excel functions. You can borrow all sorts of Excel functions. Excel has all built-in functions that you can, not all
of them, but a lot of them you can borrow when you're in VBA. Let's do another quick example here. Earlier, we had, in
one of my screencast, I created a user-defined function cone volume to calculate the volume of this. And in so doing, I
had to find pi in terms of four times the arctangent of one which is a good way to define what pi is. Alternatively, what I
can do is I can use the worksheet function pi, and we're going to get exactly the same thing that we did earlier but
instead of defining pi as four times the arctangent of one, we have just used the worksheet function. Finally, I just want
to let you know how you can deal with logarithms in VBA. So, log, L-O-G, in VBA is the natural log. So if you want to
calculate something like the base 10 log of something, so the log of a number, I'm just going to call this B, or let's do
just X. The way you would do that in VBA is to calculate the change of base theorem. So, the change of base theorem:
the log base b of X is any logarithm of the number divided by the logarithm of the base. Since L-O-G in VBA means
natural log, we could just say the log of X divided by the log of the base. So if we have this term X, we could calculate
the log base 10 using VBA. Alternatively, we can use the WorksheetFunction.log10. So we can just borrow the log 10
function from Microsoft Excel. So that's how you can borrow Excel functions in VBA.
All right, this is just going to be
a real quick screencast on how to debug functions. So I've got an example that I showed in
the screen cast on making user defined functions in VBA. I'm just going to go back
over here to the editor. I'm going to click on
the code that we created. Now, you notice that, if I press F8,
[SOUND] there is a chiming sound. You can't F8 through functions,
like you can subs. Instead, what you do is if you're
interested in seeing what's going on while your function is going,
while it's executing. And you don't know why it's not working,
you can put a break point here on this bar by left clicking,
it just toggles it on or off. And then you can go into your function,
and you can type in the function and press Enter, and it jumps into break mode. And then from here, you can use F8,
and you can kind of see what's
going on in the editor. So that's how you can debug functions. I've got a more complicated one here. This is the
bisection method,
which we might be doing later on in the course, so
I can put a break point there. And I can, wherever I want to run that,
I can place my cursor there press Enter. And now the break point, usually you
put the break point at the first line of executable code,
right after the dim statements. And then I can go through using F8,
just like you would a normal subroutine. So that's how you can step through and
debug user-defined functions.
All right, a real quick one to
show you why you never ever, ever use input boxes or
message boxes in a user-defined function. Input boxes and message boxes are reserved
for just regular subroutines, so you never want to put them
in user-defined functions. Let's just say we wanted to do a case study on the volume. And maybe I've got
the radius defined as 4, so I'm just going to go ahead and
type in Rad there to name that. And we're doing a case study on volume or on height ranging from maybe 0.5 up to, I
don't know, to do 5, all right? And I can use my Cone Volume function,
just like I would others. So I'm going to use the Radius
as my radius, right, that's an absolute reference
because I named it. And then I'm going to be
referencing the height. And right now, it's working great. So we can double-click down, and
we real quickly fill that in. Let me just delete this, and let me show you what happens when people
try to put input boxes or message boxes. In my example,
I'm going to use a message box. So a lot of times,
instead of doing this output here, the cone volume function,
somebody will, let me just go here. Instead of outputting it using
the proper way for a function, which is the name of the function, they'll
just do something like message box. Message box is the answer, right? So this is the volume, and
we want to put that in a message box. And it kind of makes sense when you're
learning these subroutines where we've used input boxes and message boxes. But let me show you what
happens when we try to do that. So if I type in my cone volume
function with the radius and the corresponding height, and I do that. It says, that outputs that in
the message box, which is fine. And I guess it's okay for
if you have one, and you just click OK. First of all, it doesn't give
you the answer in the cell. In order to leave that answer in the cell,
it needs to be the name of the function. That's why here,
you need cone volume equals the result. But also maybe you have
a hundred of these and you drag down that formula into all these
different cells, look what happens. You either got a message box to click,
OK, OK, OK, OK, and so on. And obviously, you don't want
the user to be having to do that. And it doesn't even give
you the right answer there. So that's why you never, ever, ever
want to use message boxes in a function, a user-defined function. And similarly,
you don't want to use input boxes.
Hi, there. In this screencast, I'm going to cover modular programming. Now, a lot of the code that I'm going to show is
quite complicated and you haven't really learned a lot of it. But I wanted to just kind of show you modular learning
programming how to program in a modular fashion. Now, let's say you are writing a lot of lines of code and you're
doing the same thing in a lot of different procedures. So you're using parts of the code quite often. What you can do is
you can make kind of these contracted subs. For example, this SomeSub1, you could write by itself. So this thing is sort
of a standalone sub. Similarly, this call or this SomeSub2 would be a standalone sub that maybe you're using quite often,
and then maybe you have a function. And so, essentially, what you've got is you've got these different subroutines that
you can call on. So you have your main flow here. You go into your SomeSub and you contract out your first sub. You
contract out to the next sub and then maybe you have a calculation where you're contracting out to some function. So
each of these functions and subs, these procedures, works on its own and then you kind of put them together into a
modular program. So I've got an example here. I've got some data, and we're going to develop a modular program for
this. I've got a bunch of data just 25 data points. And unfortunately, some students over at school of mine got a hold of
this and they messed it up. Occasionally, we've got nine, nine, nine, nines in there and then we've got some words that
have just been typed in there. What I'm trying to do is make a modular program called AnalyzeData. It's going to, first,
subcontract out some work to this Remove9999 sub, and then it's going to eliminate the text. So wherever I have words,
it's going to eliminate that and just replace it with blanks. And then, the next thing I'm going to do is I'm going to
remove the outliers. This is a statistical method. And then, finally, we're going to calculate the statistics, in particular the
average and the standard deviation and then we're going to output that in the message box. So, each of these subs is a
standalone sub that can work on its own. And then, we can put that together into our AnalyzeData subroutine. So, I've
written all the code here and again this is a little bit more complicated than I would expect you to know at this point in
the course. We're just getting started. But the main thing is I've got my main sub here. This sub contracts out to the
Remove9999. So it will actually go into here. You subcontract out those different subs using the call statement. So we
eliminate the text and we return back to the main flow. This line here is a special statement that just removes any row
that has a blank in column AA, in this case. And then, we're going to remove outliers so we call RemoveOutliers
subroutine. It's going to remove any outliers that sort of don't fit in with the other data points. And then, finally, we're
going to call calculate steps after we've eliminated the other nine, nine, nine, nines, all the text in our original selection
and then remove the outliers. We're going to calculate the average and standard deviation of the data. So I want to show
you how each of the different subs that are in our modular program work independently. So, first of all, let's play the
Remove9999, so I make that selection. And I'm going to remove the nine, nine, nine, nines. So it eliminates the nine,
nine, nine, nines. Let's also run the removed or the EliminateText. So that one works by itself. And then, finally, the
RemoveOutliers. So you notice that I have got some data here and the two here and the 19 are actually outliers, so we
run the RemoveOutliers and we eliminate those. And finally then, on the remaining, if we have some data here, I can do
CalculateStatistics and run that and it'll give me the average of the remaining data. So the filtered data with the outliers
removed and the standard deviation. So, we can put it all together then because we have a bunch of modules. I've got the
code here, and let me just zoom out. So I'm going to select all that data. And now if I just run the AnalyzeData, so that's
the one that has them all together, it just does everything in one fell swoop. All right. So it filters the data and spits out
the average and standard deviation. So that's how you can orient or design your programming to be modular. So think in
terms of different snippets of code that can stand by themselves, that you can use for other applications. Thanks for
watching.
I've shown you how you can run
subroutines that are in the same file. You can use the call statement, so
they can either be in the same module or in a different module. But what I wanted to show you here, is how you can run
subroutines
that are in different files. So I've got two files open. I've got this main one, and
then I've got one called RunMe. I'm just going to show you
have you can run the module. So, if I open up the module in RunMe, it's just a very simple subroutine that
just going to do message box hello. So back in the main file,
which I call application.run example. You can use this application.run method,
and you can put the file name here,
with an exclamation point, with the name of the sub in that file. And importantly, this is pretty important, if your file has
spaces in it,
then you need to have apostrophes here. If you didn't have any apostrophes in
your file, you can just delete those and it will then just being
close in the quotations. But since I have a space in Run space Me,
then I need single apostrophes there. And this is similar to other things
that you do with files in VBA. So when I run this up it's going to
run the RunMe sub in this file. So it's going to go into this file and
run it, all right? Now importantly, this file, the file that
is referenced using the application.run. This file does not have to be open, so
I'm going to go ahead and close that. So I'm going to go ahead and close RunMe. And now let's go back and
I'm going to run it. So I'm going to press F8
to skip through this. It opens up the RunMe file, and
runs the RunMe sub, all right? Now you notice though, unfortunately,
it leaves you with the RunMe file open. So I'm going to go ahead and close that. Now let me show you how
we can change that. I've modified the code quite a bit,
so this is all just so that the file when it opens
it'll be closed again. So I'm going to Dim FileName As String,
aWB As Workbook, this is sort of more complex VBA stuff. But I wanted to just point it out now, while we're talking
about how to open up
subs and other modules and workbooks. Then you can say FileName,
there's a Application.GetOpenFilename, and I'll show you what
that is in a minute. It kind of brings up a pop-up box, where you can select the file
that you want to run. So that's going to be the file
that has our RunMe sub in it, and then we open that workbook. So we open the workbook that we select,
we set this variable, that's dimmed, that's a workbook equal
to the active workbook. We need do that because we are going
to be closing that and then we run, so this is the single line I
was in the previous example. Then after running that we can close
the active workbook that we set up here. And we're going to save
changes equals false. So we're not going to save any
changes that by chance were made. So let's go ahead and run through this. And again, if you don't really understand
what's going on here, that's just fine. I kind of wanted to just include this for
your reference. So let's go ahead and do F8. That brings up this get open file name. So I'm going to choose where
that subroutine is located and then it runs that file. So I click OK, and then it'll
actually close the file, all right? So it doesn't leave it open like
the first thing I did result in. So that's just another way
that you can run a subroutine. In this case,
in a different file altogether.
There are four main week three
objectives outlined here. The first one, explain the relationship
between objects, propertied, methods and events. So these are all pretty
important in VBA and we can kind of describe
the relationship between them. They're going to be useful in pretty
much everything we do in the rest of the course. Second objective, apply VBA statements
to make reference to the common objects, properties, and methods in VBA. These primarily include range,
selection, active cells, cells, offsets, row, columns, count, select and activate. Number three, write basic subroutines that
a obtain input from the spreadsheet or from an input box. B perform a calculation. And C output the result to
the spreadsheet or a message box. And four write code that will
effectively handle errors. So a lot of times if you provide
something professionally to a client or a coworker,
you don't want errors to occur. Because it pops up the VBA editor,
the Visual Basic editor. Which is kind of intimidating to the user
and they don't know what to do and it's quite unprofessional. So let's go ahead and
start with week three.
Now, they've had some introductory
experiencedmaking some simple subs in VBA, and you've been exposed to
creating user defined functions. I wanted to delve deeper into
the object hierarchy structure in VBA. We're going to talk about properties and
methods and events in this screencast, so just kind of want to show you
an example of Object Hierarchy in VBA. It starts with the application
which is Excel, and Excel has a bunch of
objects associated with it. For example, you can have
an Addin like the Solver Addin or the Data Analysis toolpak, or
maybe you can make your own Addin. There's also Windows that pop up,
Workbooks, WorksheetFunctions. So, each of these objects has sub-objects. For example, inside of a Workbook
you might have Charts, the workbook has a Name,
you can have Visual Basic Projects. Those are like,
when you bring up the editor, you're working in the project that's
associated with the workbook. The workbook can have Windows,
the workbook obviously has Worksheets. And if we zoom in on the Worksheet object,
it's got sub-objects so it's got a Comment, there are Hyperlinks, you can have Names to a worksheet,
obviously it has to be named. The PageSetup, and one of the most
common is the Range object. So, we're going to talk a lot
about the Range object. You can also have
Object Collections like Workbooks. Instead of just workbook,
you can have with an s there, that corresponds the all
currently open workbook objects. You can have Charts. You can have a collection
of all the Worksheets. So, for example to referring to
a worksheet called ("Main"). That's how you would refer
to the Main Worksheet. Maybe you have a Chart
that's named ("XY"). That's how you can refer to
that of the collection Charts. The complete object references
really include everything from the application down to the specific
thing that you're referring to. So, for example, Application.Workbooks. The Excel application, you're talking
about ("Project6") in the workbooks. Of ("Project6") here,
referring to the ("Main") worksheet and then Range("B16") on
the ("Main") worksheet. A lot of times the application
can be dropped. If you've only got one project open,
you can drop the workbook name and you can just use Worksheets.("Main"). If you only have one worksheet
working with, you can drop that and just refer to Range. But if, maybe your workbook has multiple
worksheets and if that's the case, you need to make sure that you're properly
activating the different worksheets, as you go back and forth between them. So, in that case we'd use
Worksheets.Range to refer to those. So, let's talk about Properties,
Methods, and Events. Properties are attributes of objects. Methods are actions to
be taken on objects. And events are happenings
that objects respond to. So just some simple examples and
in our subsequent screencast, I'm going to show you some
more examples of these. An example of a Property
would be Range("A1"), so that's cell ("A1") Width, so
that is the width of cell ("A1"). A method is an action that
is taken on an object, so, Range("B2").Clear is clearing
everything in Range("B2"). An Event, for example when
a workbook is opened, maybe when a worksheet is activated or when
a workbook is closed, so those are events. So there's lots of these, there's
literary, thousands of these, and I wanted to kind of show you how these, how you
can find more information about these. If you're more interested,
you can go into the editor, and, let me start with this close, cause this
is sort of the initial view that you might have, you go up here to this
object browser or you can click F2. This sort of brings up all
the different associations between the different objects and
properties, methods and so on. So, for example, let's look at Range. So, Range is one of the most common ones. So you
can click on Range here. This tells you all of the different
things that apply to Range, for example there's a Activate here, and you have this little symbol here
which denotes that it's a method. You can also have a Range Address, so
that's a property, so this icon is for properties. You can Clear, that's a method. You can Copy, that's a method. Some
other things if you had a cell maybe
like the Interior is another property. You can have the ColorIndex. You can create a Pattern, and so on. So, this is how
you can get more
information on all of the different associations between the objects,
properties, methods and events. Let's take a closer look at
the Range Object properties. The Range Object can have a value,
actually that's what's stored in the cell. It can have Text, and over here you see if
you can read/write it, or just read-only. Value of the ones shown here,
is the only thing that you can change. You can also change things like the color
and I'll show you how we can do that. Count, you can count the number
of cells in a range. If the range is a single cell, you can
get the Column index and the Row index. You can also get the Address of
a particular range, and there's Others. So for example,
if I've got some data over here and I just do MsgBox Range ("A1"),
just kind of a little test. When I run this,
it's going to spit out 4, by the way, if you leave off a dot something on
range the default property is value, so you could if you want to just type in
value or you can just leave it off because value is the most common by far
of all the properties of range. If you want to maybe look at the color, so maybe we go over here,
and we make this orange. And I wanted to,
I can type in Interior.ColorIndex, andwe're going to MsgBox
that when I run this. So the orange has a ColorIndex of 44. ColorIndex is something
that you can write to. I can swap this around to write to
that property, so the ColorIndex, I could say, it's equal to 50. And when I run this, it's going to
change that to a green which is, which corresponds to the ColorIndex of 50. And in subsequent screencast, in through
just different examples in this course, you're going to get experience using
a lot of these other properties. Select, so you can select the cells and
arrange the cells. You can Copy and Paste. So, if you did Range("C1").Copy, the second position here is
where you're going to paste it. You can also erase using .Clear,
and you can Delete. So, you can delete and
that shifts other cells into place. Let me just show you
a couple examples here. This first one, Selection.Clear
is a method on our selection. So, this is our selection,
when I run this using F5, it's going to clear the selections,
so that's a method. And maybe for this second one, this is
also a method, we're going to copy, so we have Range("A1:A4").Copy, then this second position here is
where we're going to paste it. So, I don't need to start with a selection
because the object is the range, and when I run this Its just going to
copy that and paste it over there. So, let's just sort of just start
an introduction to Objects, Properties, Methods and Events, we'll talk more
about these in the next screencast.
This screencast is perhaps going to be one of the most important screencasts as far as teaching you the basics of
interfacing between Excel and VBA. I'm going to introduce you to objects, properties, and methods, the most common
ones that we'll be working with in this course. So the range object, the selection property, the active cell, which is a
property, the cells, offset, rows, columns, count, these are all properties that are tremendously useful. And then we have
two methods which are the select and activate. Let's start out with the range object. If you just want to refer to cell D22,
you can use Range("D22"), in quotations. If you want to refer to a range of cells, you can put A1:B5, for example. If
you have a named cell, some of you might know that in Excel, you can click on a cell and then up here in the name box,
you can type in a name for that cell. So now, it's named Pressure. You can refer to it in terms of Range("Pressure").
Range("D:D") refers to the entire column D. You can also select multiple columns. Range("3:3") is the entire row three.
You can also use rows. There are other ways to identify range objects. One of the most common is the cells property.
Cells by itself refers to all the cells on the spreadsheet, so cells (4,5), remember it's always rows then columns, that also
corresponds to cell D5. There's an offset property. Got a couple examples of this in a in a few minutes. If we had a cell
named Temperature, then Range("Temp").Offset(1,1), that uses Temp as a base cell and move over one column and
down one row. So let me show you a couple of examples. We can the select. We can select Range("A2:C6"). So if I run
this Range("A2:C6").Select, you notice that it selects that region. This by the way, is almost the same as
Range("A2:C6").Activate. I going to show you the main difference between select and activate. Ranges can also have a
range property. This, we're going to use Range("A2:C6"), but then we're taking Range("B2") of that range. So let me
show you this. I'm just going to put that in the message box. So Range("A2:C6") would be this region. Range("B2")
means Range("B2") of that range. So, you can imagine the region I have selected here is its own new spreadsheet, in
Range("B2") then of A2 to C6 would be that cell. So, I can run this and it outputs negative two. The selection property
is also really useful. So we can refer to Selection.Cells(3,2). We recall that cells refers to all the cells on the spreadsheet.
So we can kind of do a sub-property of a property, which means that we are referring to cells row three, column two of
our selection. So in order to run this, I need to start with the selections, and then I'm going to do F8. We're going to
MsgBox Selecetion.Cells(3, 2). So I have my selection, the third row and the second column. By the way, we don't have
to use cells. You can always just use Selection(3,2) and in that case, if this is my selection, it's going to messagebox the
third row and the second column. Next, we can always have a range property of the selection. So if I choose this as my
selection, and just to reiterate, a range is a fixed range, but a selection can change every time you run the sub. So if I
have a selection here and I run this, it's going to messagebox Range("B2"). So this is Range("B2") of my selection
which again, you can imagine the selection being its own little spreadsheets and we're looking at B2 of that selection, so
that's five. Next, we can use the method select. So what this is going to do is it's going to take Range("B2:C3") of the
selection, right? So this is like a sub property of a property, and it's going to select that. So let me show you what this
does. Now when I do this, whenever you have a method, it's not output. It's just you don't have an output to it so I'm
going to delete the message box there and let's run this. It's going to get Range("B2:C3") of the selection. So that would
be cell C4 to D5. When you run that, it selects that region. So let me just, real quick, show you the difference between
activate and select. So let me run the select first. So I've got my selection. Selection.Cells(2,3) B cells, row two, column
three, so that's this five, and then I'm going to select that. So look what happens when I run this. It selects that. So that's
the new selection. But when I replace it with activate, starting with the same selection, but now when I run this, I'm
going to activate that. So you see how I didn't change the selection like I did when this was a select? But instead, I
changed the active cell to C3 which is Cells(2,3) of the selection. Active cell is that single active cell that's kind of
highlighted on the spreadsheet. And a lot of times, we use this with the offset property and it's an output. So you need
either to message box it or to assign it to a variable. If this is my active cell, this is going to message box whatever cell
is plus one row and plus one column, and that'll be 10. So when you run this, it should display 10, which it does. I like
to use the offset select. So what this does, we have to, this is a method, so we're not outputting anything. What this does
is it uses our active cell as a base. It offsets minus four rows. If I start with a minus six, this is going to select the cell
that's offset minus four rows. So, one, two, three, four, and two columns, so it's going to go one, two, so she can get the
nine. And it's going to select that. So we run that and it selects the nine. We can also use the count property. We can
count the number of cells in A1 to C3. This doesn't tell you how many cells have numbers in them. It just counts the
number of cells. We can use the rows property along with the count properties. We could also do the same for columns.
So here, I've got it set up. I dim two integers. Dim number rows as integer, and numbers see number of columns as
integer, and R then is your Range.Rows.Count. So how many rows are in that range? Number columns? Would give us
the number of columns in range A1 to C5. Because it's not a selection, I can have my cursor anywhere. And we're going
to go ahead and run this. And I haven't message boxed anything so we'll just look down here in the locals window to
make sure that those are working. And I'll bring this up. So a number of rows is five, and then I execute the next line
and we counted the number of columns. Similarly, I can just change the range object to the selection property. This will
depend upon your selection before running the sub every time. So let's just do an example here. I'm going to step
through. And again, I don't have a message box so we can look down here in the locals window. It counted four columns
and four rows. These, because they're not methods, these are properties, they always output something. So you're going
to need a message box or they need to be on the right side of an equality. You can't just write Selection.Count on it's
own or it'll give you an error because this is returning a value. I want to show you something quite useful. If you don't
know, going into the sub, what the row and the column are going to be, so the row number and the column letter, you
can always obtain that from the user. So in this example, I'm dimming row index as an integer but then call as a string
because that's going to be a letter. Let's just put in row three, click OK, it's going to ask us then for the letter. So let's just
do C, and then that should be C3. It should be five. And a message box is that value. So that's how you can obtain from
the user the row and column, and do something with that.
Okay, I'm pretty excited. Now, we're done with some of the tedious stuff for this module, getting through all that object
stuff and properties and methods. So now, we get to move into some examples. A lot of what I'm going to be covering
in this screen cast, we're just going to be working through examples. I've got examples in this screen cast and then also
in a subsequent one. So to start us off, what I'm talking about here really only pertains to subroutines. We're not going to
be using the same type of stuffing functions, user-defined functions. User-defined functions never use input boxes or
message boxes, and they don't use active cells nor selection. Instead, they use range objects as the arguments to the
function or just simple numbers as arguments. So, in subroutines, there's a couple different ways that you can normally
get information. So this is importing information into the VBA subroutine, such that you can do calculations. We can do
this through the use of an input box, the active cell. So this is chosen before the sub is run. Whatever the active cell is,
we can use that value. We can use a selection, or you can have a fixed range. As far as outputting things back to Excel,
what do you do with the result? We can output things in a message box, into an active cell, which is chosen before the
sub is run. And we can also output stuff to a selection, and we can output to a fixed range. So I've got an example here.
I've got two examples we're going to work through. How would you make a VBA sub that would take a value from an
input box and A, display the square root in a message box; B, Display the square root in the active cell; and C, display
the square root in cell C3? So I'm real big on flowcharts, and I'm going to be drawing a lot of flowcharts in this course.
This flowchart's going to be very simple, but I wanted to just sort of introduce you guys to flowcharts and kind of
explain as we go along. Flowcharts are going to get more and more complicated. But I, whenever I'm making any sort of
program, I make a flowchart to begin with. Flowcharts always start with an oval that says start, so that's where we begin.
We then draw arrows into the different operations. So the first thing we're going to do here is we're going to get a
number that I'm going to define as x. So we get x. Whenever we're interfacing with the user, we write this as sort of this
parallelograms. So we get the x. This can either be in an input box or some other way. I also like to keep track of the
things that we need to dim. So we're going to have to dim x, and that's going to be likely as a double. Next, we're going
to calculate y. Actually, it's not the square. It's a square root, the square root of x. We also need to dim y then. Then we
output y, that's we're interfacing with the user. So that's typically a parallelogram. And then we end. So this is a basic
flowchart for this process. So let's go ahead and write the code for this. So in all three cases, we're going to take a value
from an input box, that's going to be x. We're going to calculate the square root of x to calculate y, and then we're either
going to display it in a message box, the active cell, or in cell C3. So I've named this cell, SquareRoot. I write my dim
statements for x and y, both as doubles. We obtain x in an input box. We calculate the square root of x and assign that to
the variable y. And finally, we output the result y in a message box. The square root of your number is y. So let's run
through this using F8. We obtain a number in the input box. I'll put in seven. We then take the square root. You can look
down here in the locals window to make sure that things are being calculated as expected, which they are. And then I'll
put that in a message box. Now, you notice all the sig figs, we had it as double. So we had 15 or 16 significant figures.
We can change that by using the format number function. Now, instead of just outputting y, I put FormatNumber y,2
which will truncate it to the hundredths place. And when we run it, I put in seven, and it truncates it to the hundredths
place. The second part, B, is display the square root in the active cell. The only change we have to make here is, instead
of outputting in a message box, we output to the active cell, which here is B2. So everything else is the same, except we
have active cell equal FormatNumber y,2. So I can put my active cell wherever, and I run this using a five, enter a
number eight, and outputs it to the active cell. And finally, if we want to display the square root in cell C3, regardless of
where the active cell is when we start this subroutine, it'll always be placed in cell C3. We can just make a few
modifications. We replaced active cell with just range C3. So regardless of where the active cell is when we begin this
sub, it'll place the answer into cell C3. Okay, so we just completed example one. Now, example two is similar. How
would you make a VBA sub that would take the value in cell A1? So instead of us obtaining x from an input box, we're
just going to obtain it from the value in cell A1. And we're going to do the same thing. We're going to display the square
root in the message box, active cell, or C3. So instead of x being acquired in an input box, it's just going to be equal to
range A1. So, now, when I run this, it's going to take seven. Regardless of where my active cell is, it's going to always
take range A1. So I run this, and it outputs it in a message box, or for part B, into the active cell. So I run that, my active
cells is C5. So let's run that. Okay. And finally, in cell C3, which will range C3. So that's regardless of where we start
with the active cell, it will place it always in cell C3. So we run that, and we place it there. All right. The next screen
cast is going to go through another couple of examples.
Okay, we're continuing on
with a couple more examples. I've got three more examples here. Create a VBA Sub that will square
cell (2,2) of a current selection. So when you read that,
you should think Selection.Cells(2, 2), and place it in cell A1. So we're going to square that variable. I'm going to import
that as a variable x. Then we're going to say
y equals x squared. And then we're going to
place y into cell A1. First step is to dim our two variables,
x and y in my case. You could use a and
b or whatever you want. Then we obtain x as Selection.Cells(2, 2). In order for this to work,
I need to have a selection of. We then square x to define our variable y. And actually, the goal is to
place the result in cell A1, so I'm just going to shift this down so
we're not covering up A1. And finally, we now take y and
we put it into range A1. And we can run this using F5. And we take the (2,
2) position of the selection, which is 5. We square it and place it into cell A1. Example 4, create a VBA sub
that will display the rows and columns of a selection and
display in a message box. So the first step is to dim two variables
as integers, the number of rows and the number of columns. Then we count the number of rows and
the number of columns of our selection. And I need to make sure
that I have a selection. And then we output that in a message box. Your selection has space nr,
number of rows space rows and space and quotation and
number of columns, columns. So when I run this,
now I'll do line by line. We count the number rows, 4,
count the number columns, 3, and then we output that
in a nice message box. Your selection has 4 rows and 3 columns. Finally, example 5, create a VBA Sub that
asks the user for a number with an input box, then adds that number to the current
active cell and places the result in a cell that is 2 cells right and
2 cells down from the current active cell. So I'm going to obtain the input
box number, that's going to be x. The number in the current
active cell is going to be y. Then I'm going to create a third
variable z that's going to add x and y. And that's going to be placed into
an offset of the current active cell, 2 cells right and 2 cells down. So 2 rows down, 2 columns over. The first step is to
dim x, y, and z. The next step is to obtain
x using an input box. y will just be obtained
from the ActiveCell. And I'm going to just change this up
a little, put a 6 here as the ActiveCell. So that's the ActiveCell. z is just x + y. And finally,
we say the ActiveCell.Offset(2, 2). So 2 rows down, 2 columns over,
that should be D8 will be equal to z. So let's go ahead and
make sure that this works. I'm going to step through this. Let's add a number 7, so
that it obtained x as 7. We run the next line,
that's the ActiveCell value y is 6. And then we create z,
which is just the sum of those two. And finally, we put that into the
ActiveCell offset, 2 rows and 2 columns, which would be in cell C8. Now some of you might be wondering or
might be thinking that it's a lot easier. You can consolidate this into just,
you could remove these two lines of code. And in fact, you can do that. So let me remove y and
z from being dimmed, and I can just consolidate this ActiveCell. Instead of z, I can say, ActiveCell + x, right, and I can
delete these. And now,
I only have a couple rows fewer, and this works exactly the same. I can add 8 plus 6 into
the ActiveCell offset there. However, while you're learning VBA,
I would advise against doing this. It's better to have more variables. Because down in the Locals window,
you can see more of what's going on. Here, you only have one variable. So you can't really tell, if you're making
a mistake, you can't tell where it is. So while you're learning VBA, the more variables is fine,
more lines of code is just fine. And then maybe later on when
you get more comfortable, you can start consolidating lines of code. All right, that's it for
the second set of examples. Thanks for watching.
I'm going to show you one more example of how we can work with properties. So, in this example, I've got a value in
cell A1. And what we want to do, is we want to add the cell that's in A1 to a value X that's input by the user in an input
box. So, X will be the value input by the user, Y is going to be equal to the value in cell A1. In this case, that's two.
Then we're going to calculate Z, which is just the sum of those two. And then, we're going to ask the user for a range. So
for example, a cell like B3 or it can also be a multiple cell range like B3 to C7. And in that range, we're going to place
Z. So let's go through this. Let me show you how this works. We press F8 we get a value X from the user, I'll say seven.
Then, we get Y from range A1. So that's equal to two. Bring up the locals window here so we can see. Then we ask the
user for the range. Please enter the cell to place the result in, I'll just say B3. So it accepts that as a range which is you
have to dim it as a string. And now, we place into that range, we placed the sum of X and Y which is Z. And that goes
into cell B3. We can also do this on multiple cells in range. So let's do four and then we add those two, four plus two is
six. We're going to ask the user for a range, so I'll say in this case A4 to C7. And it's going to then place into that range
the sum of X and Y which is Z. So this just another example of how you can work with different ranges, how you can
obtain input from the user, and how you can export it back to the spreadsheet.
I want to just give you a kind of basic
understanding of how to deal with errors. So far you've learned just
some real basic stuff. But I want to just give you an idea of how
we can protect your subs against errors. So I've made a simple sub routine here. I've got x dimmed as a double. We
obtain x in an input box so this is going to be the volume
that the user is going to input. And we have a message box. Whatever they put in for gallons,
it's going to convert it to cubic feet. I have this format number with two
after the comma in the parenthesis. And that means we round it
to the hundreds place, and that's where we're going to present. So if I run this and I've assigned a button, to assign a
button
you go up to the Developer tab, Insert. And there's a button here,
the top left, you can click that and then it'll ask you what macro
to assign the button to. So I have assigned this to
that macro I just made. So I can run this and
I can put in something like 167 gallons, and it will convert it to cubic feet. However, there's a problem and
that is if the user clicks here and a couple of things, if they just
put in a string and they press OK. Then what it does is it brings up
this debug box, this error box, and if the Visual Basic editor was closed,
it will actually open that. And this is very unprofessional and
you don't want this happening, especially if you are providing
this to somebody. Also, if the user clicks this and
they click Cancel, it also has an error. So we want to make it so that if they
press Cancel, then it just closes the box. So I'm going to make just
a couple of quick adjustments. The first one you can
put On Error GoTo Here. Here x has a bookmark. If there's any sort of error in here,
it's just going to jump right to here and it's going to display a message box. So now if I run these and I do something
like Cancel, it say's there was an error. However we have another problem because
if I put in something reasonable 167, it tell us the answer but
then it also says that there was an error. The reason for that is I have my here
we had an error and I went to here. But then we just resume to the next line. So what I have to do is, before
the bookmark, I have to put Exit Sub. So if it goes through normally, we convert
it to cubic feet, and then we Exit Sub. If there's an error, we skip all that
other stuff, and we go to here, and we display the message box. So now it's working a lot better. If I just press OK or if I
press Cancel,
this says that there was an error. If I press OK, it says there was an error. If I try to close,
it says there was an error. If I put in a string it
says there was an error. So it's really protected now against
opening up that error box and the Visual Basic editor.

Das könnte Ihnen auch gefallen