Excel VBA Topic 2.2 - Creating Your First VBA Macro

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

In order to assign the value 5 to cell A1 in Sheet3, you don't need to select either of them.
So, instead of:

Sheets("Sheet3").select
Range("A1").select
Activecell.value = 5


The following line of code would suffice:

= 5

This code is not only shorter: it also saves execution time.

meniporat
Автор

In newer versions of Excel, only "Sheet1" is automatically created for you when you open a new workbook. You should create "Sheet3" before running this program.

CPPMechEngTutorials
Автор

When programming, remember that the computer is not smart, it simply follows directions (and it does this very quickly).  Try to think thru your code as the computer does, and as Dr Nissenson does in the video, reading each line and imagining what you would do in the computer's place. This is a great programming and debugging tool, and also will enhance your understanding of programming.

ToddCoburn
Автор

So, the Sheets command tells VBA to look for a sheet, and the value in quotes and parentheses tells which sheet it looks for.  The portion of the command after the period tells what VBA will do with this sheet, in these two cases it will select it.  The Range command makes VBA look for a range of cells. In this case, VBA looks for a range that includes only a single cell, cell A3 & B2.  The second part of the command tells VBA to Select this range, making it active (the one VBA is "thinking" about).  The ActiveCell command says that it will do something with whatever cell or cells is/are active.  In this case, we just set the active cell using the Range().Select command.  The second part of the command tells VBA to do something with its "value", and the = sign tells VBA to set its value to 5 and then 62, respectively.  Cool, huh?

ToddCoburn
Автор

As a new programmer (this is what you are becoming with this class), you want to start developing good programming habits.  A good code is not only one that performs its function, but one that you can readily understand, debug, modify, and expand.  Comments give you a chance to make clear what each line or sequence of lines of code is doing.  If you intersperse comments throughout your code, you will find it easier to find mistakes (called debugging), and to make upgrades to your code.  It is also a good habit to use comments to identify the program author and the date created.  Try adding a comment 'by Joe Smoe for Dr Nissenson's MOOC on March xx, 2015', or something similar as your second line.

ToddCoburn
Автор

In Excel 2007, inserting a module adds the line 'Option Explicit' to the top of the code.

dhinaa
Автор

It doesn't run either way...
A run time error 9 appears. Subscript out of range. when I put it exactly like this:

Sub myfirstmacro()

Sheets("Sheet1").Select
Range("A1").Select
ActiveCell.Value = 5

End Sub

nomikikoutsoubari