Create a program with excel

Перейти к содержимому

Один из наиболее часто задаваемых вопросов задаваемых начинающими пользователями звучит так: «Как создать программу в «Excel» и возможно ли это сделать в принципе?»

Ответ на него не так прост.

Создать полноценную программу или продвинутую игру инструментами «Эксель» практически невозможно.

С другой стороны «Excel» обладает достаточным набором инструментов (активные элементы Activx, ViBA и т.д.), позволяющими создавать достаточно функциональные приложения внутри самих экселевских документах — макросы.

Опытные программисты при помощи макросов написанных на языке VBA даже создают примитивные игры популярные в начале 90-х прошлого столетия: тетрис, змейка, пинг-понг и т.д.tetris

Рассмотрим азы создания программ в VBA Excel.

Самый первый этап создания программы — это написание алгоритма ее работы.
Необходимо определить для себя какие данные будут вноситься пользователем, какие данные будут константой, какой результат должна выдавать программа.
Когда определились с основными принципами работы программы, следует составить блок-схему ее работы, используя условные обозначения:block shema

Второй этап подготовка программы «Excel» к написанию макросов: включить макросы, отобразить панель разработчика и т.д.
Подробно подготовка к написанию простого макроса описана в статье:

Как написать простой макрос в программе Excel

Третий этап — при помощи языка программирования VBA «оцифровываем» блок схему. Делаем ее понятной для компьютера. То есть пишем сам код на языке программирования VBA.макрос в панели макросов

Некоторые варианты кодов макросов опубликованы на нашем сайте в разделе Макросы и VBA.

Explore the 40 most popular pages in this section. Below you can find a description of each page. Happy learning!

1 Run Code from a Module: As a beginner to Excel VBA, you might find it difficult to decide where to put your VBA code. This example teaches you how to run code from a module.

2 Macro Recorder: The Macro Recorder, a very useful tool included in Excel VBA, records every task you perform with Excel. All you have to do is record a specific task once. Next, you can execute the task over and over with the click of a button.

3 Add a Macro to the Toolbar: If you use an Excel macro frequently, you can add it to the Quick Access Toolbar. This way you can quickly access your macro.

4 InputBox Function: You can use the InputBox function in Excel VBA to prompt the user to enter a value.

5 Close and Open: The Close and Open Method in Excel VBA can be used to close and open workbooks. Remember, the Workbooks collection contains all the Workbook objects that are currently open.

6 Files in a Directory: Use Excel VBA to loop through all closed workbooks and worksheets in a directory and display all the names.

7 Import Sheets: In this example, we will create a VBA macro that imports sheets from other Excel files into one Excel file.

8 Programming Charts: Use Excel VBA to create two programs. One program loops through all charts on a sheet and changes each chart to a pie chart. The other program changes some properties of the first chart.

9 CurrentRegion: You can use the CurrentRegion property in Excel VBA to return the range bounded by any combination of blank rows and blank columns.

10 Entire Rows and Columns: This example teaches you how to select entire rows and columns in Excel VBA. Are you ready?

11 Offset: The Offset property in Excel VBA takes the range which is a particular number of rows and columns away from a certain range.

12 From Active Cell to Last Entry: This example illustrates the End property of the Range object in Excel VBA. We will use this property to select the range from the Active Cell to the last entry in a column.

13 Background Colors: Changing background colors in Excel VBA is easy. Use the Interior property to return an Interior object. Then use the ColorIndex property of the Interior object to set the background color of a cell.

14 Compare Ranges: Learn how to create a program in Excel VBA that compares randomly selected ranges and highlights cells that are unique.

15 Option Explicit: We strongly recommend to use Option Explicit at the start of your Excel VBA code. Using Option Explicit forces you to declare all your variables.

16 Logical Operators: The three most used logical operators in Excel VBA are: And, Or and Not. As always, we will use easy examples to make things more clear.

17 Select Case: Instead of multiple If Then statements in Excel VBA, you can use the Select Case structure.

18 Mod Operator: The Mod operator in Excel VBA gives the remainder of a division.

19 Delete Blank Cells: In this example, we will create a VBA macro that deletes blank cells. First, we declare two variables of type Integer.

20 Loop through Defined Range: Use Excel VBA to loop through a defined range. For example, when we want to square the numbers in the range A1:A3.

21 Do Until Loop: VBA code placed between Do Until and Loop will be repeated until the part after Do Until is true.

22 Sort Numbers: In this example, we will create a VBA macro that sorts numbers. First, we declare three variables of type Integer and one Range object.

23 Remove Duplicates: Use Excel VBA to remove duplicates. In column A we have 10 numbers. We want to remove the duplicates from these numbers and place the unique numbers in column B.

24 Debugging: This example teaches you how to debug code in Excel VBA.

25 Error Handling: Use Excel VBA to create two programs. One program simply ignores errors. The other program continues execution at a specified line upon hitting an error.

26 Subscript Out of Range: The ‘subscript out of range’ error in Excel VBA occurs when you refer to a nonexistent collection member or a nonexistent array element.

27 Separate Strings: Let’s create a program in Excel VBA that separates strings. Place a command button on your worksheet and add the following code lines.

28 Instr: Use Instr in Excel VBA to find the position of a substring in a string. The Instr function is quite versatile.

29 Compare Dates and Times: This example teaches you how to compare dates and times in Excel VBA.

30 DateDiff Function: The DateDiff function in Excel VBA can be used to get the number of days, weeks, months or years between two dates.

31 Highlight Active Cell: Learn how to create a program in Excel VBA that highlights the row and column of the Active Cell (selected cell). This program will amaze and impress your boss.

32 Dynamic Array: If the size of your array increases and you don’t want to fix the size of the array, you can use the ReDim keyword. Excel VBA then changes the size of the array automatically.

33 User Defined Function: Excel has a large collection of functions. In most situations, those functions are sufficient to get the job done. If not, you can use Excel VBA to create your own function.

34 Read Data from Text File: Use Excel VBA to read data from a text file. This file contains some geographical coordinates we want to import into Excel.

35 Vlookup: Use the WorksheetFunction property in Excel VBA to access the VLOOKUP function. All you need is a single code line.

36 List Box: Use Excel VBA to place a list box on your worksheet. A list box is a list from where a user can select an item.

37 Check Box: A check box is a field which can be checked to store information. To create a check box in Excel VBA, execute the following steps.

38 Loan Calculator: This page teaches you how to create a simple loan calculator in Excel VBA. The worksheet contains the following ActiveX controls: two scrollbars and two option buttons.

39 Currency Converter: Use Excel VBA to create a Userform that converts any amount from one currency into another.

40 Progress Indicator: Learn how to create a progress indicator in Excel VBA. We’ve kept the progress indicator as simple as possible, yet it looks professional. Are you ready?

Check out all 300 examples.

Содержание

  1. Building programs in excel
  2. Most Popular
  3. Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic
  4. Introduction
  5. Prerequisites
  6. Learning Objectives
  7. Important Concepts
  8. What is VBA?
  9. Why use VBA in Excel?
  10. Getting Set Up to Write VBA in Excel
  11. Developer Tab
  12. VBA Editor
  13. Excel VBA Examples
  14. Example #1: Display a Message when Users Open the Excel Workbook
  15. How is it doing that?
  16. When could I use this?
  17. Real World Examples
  18. Example #2: Allow User to Execute another Procedure
  19. How is it doing that?
  20. When could I use this?
  21. Real World Examples
  22. Example #3: Add Numbers to a Range with a For-Next Loop
  23. How is it doing that?
  24. When could I use this?
  25. Real World Examples
  26. Conclusion

Building programs in excel

VBA (Visual Basic for Applications) is the programming language of Excel and other Office programs.

1 Create a Macro: With Excel VBA you can automate tasks in Excel by writing so called macros. In this chapter, learn how to create a simple macro.

2 MsgBox: The MsgBox is a dialog box in Excel VBA you can use to inform the users of your program.

3 Workbook and Worksheet Object: Learn more about the Workbook and Worksheet object in Excel VBA.

4 Range Object: The Range object, which is the representation of a cell (or cells) on your worksheet, is the most important object of Excel VBA.

5 Variables: This chapter teaches you how to declare, initialize and display a variable in Excel VBA.

6 If Then Statement: Use the If Then statement in Excel VBA to execute code lines if a specific condition is met.

7 Loop: Looping is one of the most powerful programming techniques. A loop in Excel VBA enables you to loop through a range of cells with just a few codes lines.

8 Macro Errors: This chapter teaches you how to deal with macro errors in Excel.

9 String Manipulation: In this chapter, you’ll find the most important functions to manipulate strings in Excel VBA.

10 Date and Time: Learn how to work with dates and times in Excel VBA.

11 Events: Events are actions performed by users which trigger Excel VBA to execute code.

12 Array: An array is a group of variables. In Excel VBA, you can refer to a specific variable (element) of an array by using the array name and the index number.

13 Function and Sub: In Excel VBA, a function can return a value while a sub cannot.

14 Application Object: The mother of all objects is Excel itself. We call it the Application object. The application object gives access to a lot of Excel related options.

15 ActiveX Controls: Learn how to create ActiveX controls, such as command buttons, text boxes, list boxes etc.

16 Userform: This chapter teaches you how to create an Excel VBA Userform.

Become an Excel VBA pro! You can find related examples and features on the right side of each chapter at the bottom of each chapter . Below you can find an overview.

Most Popular

Here are the most popular pages in this section, excluding the chapters. Happy learning!

1 Run Code from a Module: As a beginner to Excel VBA, you might find it difficult to decide where to put your VBA code. This example teaches you how to run code from a module.

2 Macro Recorder: The Macro Recorder, a very useful tool included in Excel VBA, records every task you perform with Excel. All you have to do is record a specific task once. Next, you can execute the task over and over with the click of a button.

3 Add a Macro to the Toolbar: If you use an Excel macro frequently, you can add it to the Quick Access Toolbar. This way you can quickly access your macro.

4 InputBox Function: You can use the InputBox function in Excel VBA to prompt the user to enter a value.

5 Close and Open: The Close and Open Method in Excel VBA can be used to close and open workbooks. Remember, the Workbooks collection contains all the Workbook objects that are currently open.

6 Files in a Directory: Use Excel VBA to loop through all closed workbooks and worksheets in a directory and display all the names.

7 Import Sheets: In this example, we will create a VBA macro that imports sheets from other Excel files into one Excel file.

8 Programming Charts: Use Excel VBA to create two programs. One program loops through all charts on a sheet and changes each chart to a pie chart. The other program changes some properties of the first chart.

9 CurrentRegion: You can use the CurrentRegion property in Excel VBA to return the range bounded by any combination of blank rows and blank columns.

10 Entire Rows and Columns: This example teaches you how to select entire rows and columns in Excel VBA. Are you ready?

11 Offset: The Offset property in Excel VBA takes the range which is a particular number of rows and columns away from a certain range.

12 From Active Cell to Last Entry: This example illustrates the End property of the Range object in Excel VBA. We will use this property to select the range from the Active Cell to the last entry in a column.

13 Background Colors: Changing background colors in Excel VBA is easy. Use the Interior property to return an Interior object. Then use the ColorIndex property of the Interior object to set the background color of a cell.

14 Compare Ranges: Learn how to create a program in Excel VBA that compares randomly selected ranges and highlights cells that are unique.

15 Option Explicit: We strongly recommend to use Option Explicit at the start of your Excel VBA code. Using Option Explicit forces you to declare all your variables.

16 Logical Operators: The three most used logical operators in Excel VBA are: And, Or and Not. As always, we will use easy examples to make things more clear.

17 Select Case: Instead of multiple If Then statements in Excel VBA, you can use the Select Case structure.

18 Mod Operator: The Mod operator in Excel VBA gives the remainder of a division.

19 Delete Blank Cells: In this example, we will create a VBA macro that deletes blank cells. First, we declare two variables of type Integer.

20 Loop through Defined Range: Use Excel VBA to loop through a defined range. For example, when we want to square the numbers in the range A1:A3.

21 Do Until Loop: VBA code placed between Do Until and Loop will be repeated until the part after Do Until is true.

22 Sort Numbers: In this example, we will create a VBA macro that sorts numbers. First, we declare three variables of type Integer and one Range object.

23 Remove Duplicates: Use Excel VBA to remove duplicates. In column A we have 10 numbers. We want to remove the duplicates from these numbers and place the unique numbers in column B.

24 Debugging: This example teaches you how to debug code in Excel VBA.

25 Error Handling: Use Excel VBA to create two programs. One program simply ignores errors. The other program continues execution at a specified line upon hitting an error.

26 Subscript Out of Range: The ‘subscript out of range’ error in Excel VBA occurs when you refer to a nonexistent collection member or a nonexistent array element.

27 Separate Strings: Let’s create a program in Excel VBA that separates strings. Place a command button on your worksheet and add the following code lines.

28 Instr: Use Instr in Excel VBA to find the position of a substring in a string. The Instr function is quite versatile.

29 Compare Dates and Times: This example teaches you how to compare dates and times in Excel VBA.

30 DateDiff Function: The DateDiff function in Excel VBA can be used to get the number of days between two dates.

31 Highlight Active Cell: Learn how to create a program in Excel VBA that highlights the row and column of the Active Cell (selected cell). This program will amaze and impress your boss.

32 Dynamic Array: If the size of your array increases and you don’t want to fix the size of the array, you can use the ReDim keyword. Excel VBA then changes the size of the array automatically.

33 User Defined Function: Excel has a large collection of functions. In most situations, those functions are sufficient to get the job done. If not, you can use Excel VBA to create your own function.

34 Read Data from Text File: Use Excel VBA to read data from a text file. This file contains some geographical coordinates we want to import into Excel.

35 Vlookup: Use the WorksheetFunction property in Excel VBA to access the VLOOKUP function. All you need is a single code line.

36 List Box: Use Excel VBA to place a list box on your worksheet. A list box is a list from where a user can select an item.

37 Check Box: A check box is a field which can be checked to store information. To create a check box in Excel VBA, execute the following steps.

38 Loan Calculator: This page teaches you how to create a simple loan calculator in Excel VBA. The worksheet contains the following ActiveX controls: two scrollbars and two option buttons.

39 Currency Converter: Use Excel VBA to create a Userform that converts any amount from one currency into another.

40 Progress Indicator: Learn how to create a progress indicator in Excel VBA. We’ve kept the progress indicator as simple as possible, yet it looks professional. Are you ready?

Источник

Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic

Introduction

This is a tutorial about writing code in Excel spreadsheets using Visual Basic for Applications (VBA).

Excel is one of Microsoft’s most popular products. In 2016, the CEO of Microsoft said «Think about a world without Excel. That’s just impossible for me.” Well, maybe the world can’t think without Excel.

  • In 1996, there were over 30 million users of Microsoft Excel (source).
  • Today, there are an estimated 750 million users of Microsoft Excel. That’s a little more than the population of Europe and 25x more users than there were in 1996.

We’re one big happy family!

In this tutorial, you’ll learn about VBA and how to write code in an Excel spreadsheet using Visual Basic.

Prerequisites

You don’t need any prior programming experience to understand this tutorial. However, you will need:

  • Basic to intermediate familiarity with Microsoft Excel
  • If you want to follow along with the VBA examples in this article, you will need access to Microsoft Excel, preferably the latest version (2019) but Excel 2016 and Excel 2013 will work just fine.
  • A willingness to try new things

Learning Objectives

Over the course of this article, you will learn:

  1. What VBA is
  2. Why you would use VBA
  3. How to get set up in Excel to write VBA
  4. How to solve some real-world problems with VBA

Important Concepts

Here are some important concepts that you should be familiar with to fully understand this tutorial.

Objects: Excel is object-oriented, which means everything is an object — the Excel window, the workbook, a sheet, a chart, a cell. VBA allows users to manipulate and perform actions with objects in Excel.

If you don’t have any experience with object-oriented programming and this is a brand new concept, take a second to let that sink in!

Procedures: a procedure is a chunk of VBA code, written in the Visual Basic Editor, that accomplishes a task. Sometimes, this is also referred to as a macro (more on macros below). There are two types of procedures:

  • Subroutines: a group of VBA statements that performs one or more actions
  • Functions: a group of VBA statements that performs one or more actions and returns one or more values

Note: you can have functions operating inside of subroutines. You’ll see later.

Macros: If you’ve spent any time learning more advanced Excel functionality, you’ve probably encountered the concept of a “macro.” Excel users can record macros, consisting of user commands/keystrokes/clicks, and play them back at lightning speed to accomplish repetitive tasks. Recorded macros generate VBA code, which you can then examine. It’s actually quite fun to record a simple macro and then look at the VBA code.

Please keep in mind that sometimes it may be easier and faster to record a macro rather than hand-code a VBA procedure.

For example, maybe you work in project management. Once a week, you have to turn a raw exported report from your project management system into a beautifully formatted, clean report for leadership. You need to format the names of the over-budget projects in bold red text. You could record the formatting changes as a macro and run that whenever you need to make the change.

What is VBA?

Visual Basic for Applications is a programming language developed by Microsoft. Each software program in the Microsoft Office suite is bundled with the VBA language at no extra cost. VBA allows Microsoft Office users to create small programs that operate within Microsoft Office software programs.

Think of VBA like a pizza oven within a restaurant. Excel is the restaurant. The kitchen comes with standard commercial appliances, like large refrigerators, stoves, and regular ole’ ovens — those are all of Excel’s standard features.

But what if you want to make wood-fired pizza? Can’t do that in a standard commercial baking oven. VBA is the pizza oven.

Why use VBA in Excel?

Because wood-fired pizza is the best!

A lot of people spend a lot of time in Excel as a part of their jobs. Time in Excel moves differently, too. Depending on the circumstances, 10 minutes in Excel can feel like eternity if you’re not able to do what you need, or 10 hours can go by very quickly if everything is going great. Which is when you should ask yourself, why on earth am I spending 10 hours in Excel?

Sometimes, those days are inevitable. But if you’re spending 8-10 hours everyday in Excel doing repetitive tasks, repeating a lot of the same processes, trying to clean up after other users of the file, or even updating other files after changes are made to the Excel file, a VBA procedure just might be the solution for you.

You should consider using VBA if you need to:

  • Automate repetitive tasks
  • Create easy ways for users to interact with your spreadsheets
  • Manipulate large amounts of data

Getting Set Up to Write VBA in Excel

Developer Tab

To write VBA, you’ll need to add the Developer tab to the ribbon, so you’ll see the ribbon like this.

To add the Developer tab to the ribbon:

  1. On the File tab, go to Options > Customize Ribbon.
  2. Under Customize the Ribbon and under Main Tabs, select the Developer check box.

After you show the tab, the Developer tab stays visible, unless you clear the check box or have to reinstall Excel. For more information, see Microsoft help documentation.

VBA Editor

Navigate to the Developer Tab, and click the Visual Basic button. A new window will pop up — this is the Visual Basic Editor. For the purposes of this tutorial, you just need to be familiar with the Project Explorer pane and the Property Properties pane.

Excel VBA Examples

First, let’s create a file for us to play around in.

  1. Open a new Excel file
  2. Save it as a macro-enabled workbook (. xlsm)
  3. Select the Developer tab
  4. Open the VBA Editor

Let’s rock and roll with some easy examples to get you writing code in a spreadsheet using Visual Basic.

Example #1: Display a Message when Users Open the Excel Workbook

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub Auto_Open()
MsgBox («Welcome to the XYZ Workbook.»)
End Sub

Save, close the workbook, and reopen the workbook. This dialog should display.

How is it doing that?

Depending on your familiarity with programming, you may have some guesses. It’s not particularly complex, but there’s quite a lot going on:

  • Sub (short for “Subroutine): remember from the beginning, “a group of VBA statements that performs one or more actions.”
  • Auto_Open: this is the specific subroutine. It automatically runs your code when the Excel file opens — this is the event that triggers the procedure. Auto_Open will only run when the workbook is opened manually; it will not run if the workbook is opened via code from another workbook (Workbook_Open will do that, learn more about the difference between the two).
  • By default, a subroutine’s access is public. This means any other module can use this subroutine. All examples in this tutorial will be public subroutines. If needed, you can declare subroutines as private. This may be needed in some situations. Learn more about subroutine access modifiers.
  • msgBox: this is a function — a group of VBA statements that performs one or more actions and returns a value. The returned value is the message “Welcome to the XYZ Workbook.”

In short, this is a simple subroutine that contains a function.

When could I use this?

Maybe you have a very important file that is accessed infrequently (say, once a quarter), but automatically updated daily by another VBA procedure. When it is accessed, it’s by many people in multiple departments, all across the company.

  • Problem: Most of the time when users access the file, they are confused about the purpose of this file (why it exists), how it is updated so often, who maintains it, and how they should interact with it. New hires always have tons of questions, and you have to field these questions over and over and over again.
  • Solution: create a user message that contains a concise answer to each of these frequently answered questions.

Real World Examples

  • Use the MsgBox function to display a message when there is any event: user closes an Excel workbook, user prints, a new sheet is added to the workbook, etc.
  • Use the MsgBox function to display a message when a user needs to fulfill a condition before closing an Excel workbook
  • Use the InputBox function to get information from the user

Example #2: Allow User to Execute another Procedure

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub UserReportQuery()
Dim UserInput As Long
Dim Answer As Integer
UserInput = vbYesNo
Answer = MsgBox(«Process the XYZ Report?», UserInput)
If Answer = vbYes Then ProcessReport
End Sub

Sub ProcessReport()
MsgBox («Thanks for processing the XYZ Report.»)
End Sub

Save and navigate back to the Developer tab of Excel and select the “Button” option. Click on a cell and assign the UserReportQuery macro to the button.

Now click the button. This message should display:

Click “yes” or hit Enter.

Once again, tada!

Please note that the secondary subroutine, ProcessReport, could be anything. I’ll demonstrate more possibilities in example #3. But first.

How is it doing that?

This example builds on the previous example and has quite a few new elements. Let’s go over the new stuff:

  • Dim UserInput As Long: Dim is short for “dimension” and allows you to declare variable names. In this case, UserInput is the variable name and Long is the data type. In plain English, this line means “Here’s a variable called “UserInput”, and it’s a Long variable type.”
  • Dim Answer As Integer: declares another variable called “Answer,” with a data type of Integer. Learn more about data types here.
  • UserInput = vbYesNo: assigns a value to the variable. In this case, vbYesNo, which displays Yes and No buttons. There are many button types, learn more here.
  • Answer = MsgBox(“Process the XYZ Report?”, UserInput): assigns the value of the variable Answer to be a MsgBox function and the UserInput variable. Yes, a variable within a variable.
  • If Answer = vbYes Then ProcessReport: this is an “If statement,” a conditional statement, which allows us to say if x is true, then do y. In this case, if the user has selected “Yes,” then execute the ProcessReport subroutine.

When could I use this?

This could be used in many, many ways. The value and versatility of this functionality is more so defined by what the secondary subroutine does.

For example, maybe you have a file that is used to generate 3 different weekly reports. These reports are formatted in dramatically different ways.

  • Problem: Each time one of these reports needs to be generated, a user opens the file and changes formatting and charts; so on and so forth. This file is being edited extensively at least 3 times per week, and it takes at least 30 minutes each time it’s edited.
  • Solution: create 1 button per report type, which automatically reformats the necessary components of the reports and generates the necessary charts.

Real World Examples

  • Create a dialog box for user to automatically populate certain information across multiple sheets
  • Use the InputBox function to get information from the user, which is then populated across multiple sheets

Example #3: Add Numbers to a Range with a For-Next Loop

For loops are very useful if you need to perform repetitive tasks on a specific range of values — arrays or cell ranges. In plain English, a loop says “for each x, do y.”

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub LoopExample()
Dim X As Integer
For X = 1 To 100
Range(«A» & X).Value = X
Next X
End Sub

Save and navigate back to the Developer tab of Excel and select the Macros button. Run the LoopExample macro.

This should happen:

Etc, until the 100th row.

How is it doing that?

  • Dim X As Integer: declares the variable X as a data type of Integer.
  • For X = 1 To 100: this is the start of the For loop. Simply put, it tells the loop to keep repeating until X = 100. X is the counter. The loop will keep executing until X = 100, execute one last time, and then stop.
  • Range(«A» & X).Value = X: this declares the range of the loop and what to put in that range. Since X = 1 initially, the first cell will be A1, at which point the loop will put X into that cell.
  • Next X: this tells the loop to run again

When could I use this?

The For-Next loop is one of the most powerful functionalities of VBA; there are numerous potential use cases. This is a more complex example that would require multiple layers of logic, but it communicates the world of possibilities in For-Next loops.

Maybe you have a list of all products sold at your bakery in Column A, the type of product in Column B (cakes, donuts, or muffins), the cost of ingredients in Column C, and the market average cost of each product type in another sheet.

You need to figure out what should be the retail price of each product. You’re thinking it should be the cost of ingredients plus 20%, but also 1.2% under market average if possible. A For-Next loop would allow you to do this type of calculation.

Real World Examples

  • Use a loop with a nested if statement to add specific values to a separate array only if they meet certain conditions
  • Perform mathematical calculations on each value in a range, e.g. calculate additional charges and add them to the value
  • Loop through each character in a string and extract all numbers
  • Randomly select a number of values from an array

Conclusion

Now that we’ve talked about pizza and muffins and oh-yeah, how to write VBA code in Excel spreadsheets, let’s do a learning check. See if you can answer these questions.

  • What is VBA?
  • How do I get set up to start using VBA in Excel?
  • Why and when would you use VBA?
  • What are some problems I could solve with VBA?

If you have a fair idea of how to you could answer these questions, then this was successful.

Whether you’re an occasional user or a power user, I hope this tutorial provided useful information about what can be accomplished with just a bit of code in your Excel spreadsheets.

Источник

Programming in Excel

Excel Programming (Table of Contents)

  • Introduction to Programming in Excel
  • How to Program in Excel?

Introduction to Programming in Excel

Have you ever been tired of doing a task in Excel which you feel can be automated and save your time? Most of the time, you must have encountered such tasks. However, in order to automate any task, you first need to have programming skills for that particular language. In Excel, you can do programming with the help of Visual Basic for Application (VBA) which is Excel’s own programming language that can help you to automate the tasks. In this article, we will see how we can do programming in Excel VBA. VBA can be used to write a program that can automate the task for you. The piece of lines we write under VBA is called Macro, which is written in such a way that they instruct the Excel system about what to be done.

How to Program in Excel?

Let’s understand how to Program in excel with few illustrations.

Enabling Developer Tab

The first thing that comes is enabling the developer tab that helps you to record and store a macro (VBA Code). Let us see how we can get that enabled.

  • Navigate to the File menu in your excel file and click on it.

Programming in excel 1-1

  • Within the File menu, click on Options, and it will load a new window with all excel options available.

Programming in excel 1-2

  • In the new window that popped up named Excel Options, click on the Customize Ribbon tab. You can see all the customization options you can use for Excel Ribbon, which appears at the top of your Excel file.

customize ribbon-program excel

  • Enable Developer option under Main Tabs dropdown within Customize the Ribbon: section. You can check (tick-mark) the Developer tab to enable it. Click the OK button placed at the bottom right of the Excel Options tab, and that’s it.

Programming in excel 1-3

  • You have successfully enabled the Developer option within your excel. If you check the Excel Ribbon in your file now, you’ll be able to see a new tab added there with the name Developer on it.

Developer Tab-program excel

This is the first step you need to follow before you start writing macros in Excel. Because the Developer tab is needed to record and run the macro, this option tab is not by default enabled, which is why we tried enabling it here first.

Recording a Macro

  • Open the Excel file. Navigate towards the Developer tab you just enabled and then click on the Record Macro button, categorized and can be seen under the Code section.

Programming in excel 2-1

  • As soon as you click on the Record Macro button, you’ll see a window popping up; in that window, you must have to assign a name to the macro; you can also assign a shortcut key for this macro to run. Can you add the description, if any, for this macro you are creating? Once you are done with all this, you can click on the OK button placed at the right bottom of the window. See the screenshot below for your reference.

Record Macro

As soon as you click OK, the system starts recording the macro and all the tasks you perform will be recorded and converted to Excel Program in the backend.

  • Try typing the sentence “This is my first VBA code, and I am very happy!” in cell A1 within the Excel sheet and press Enter key. These steps will be recorded in the backend of the macro.

VBA programming excel

  • Under the Code section, you might have observed that the Record Macro button has changed to Stop Recording. This is like Play and Stop. Record Macro Works as Play button and Stop Recording work as Stop button. Click on the Stop Recording button to stop the recording.

Stop Recording

The magic behind all this is, Excel has recorded my steps here and converted those into pieces of code so that this task can be automated. It means, every single step, selecting cell A1, inputting the text as “This is my first VBA code, and I am happy!”, clicking Enter to go to the next cell. All these steps are converted into a VBA code. Let’s check the code now.

  • In order to go to Visual Basic Editor, you can click on the Visual Basic option under the Code category in the Developer tab, or you can use Alt + F11 as a shortcut for the same.

Visual Basic

  • Navigate towards the Modules section under VBAProject and click on the plus button under it to see the list of active modules in VBA.

Module 1

  • Inside the Modules folder, you can see Module1 as soon as you click on the plus sign. You can double click on Module1; it is where your code for the task we performed in previous steps (Step 3 and 4) are recorded. Save this code, and you can run it every time to get the same output. See the screenshot below:

myfirstcode

Conclusion

  • We can record a macro in Excel to automate day to day small tasks, which are simpler for the system to manipulate programmatically.
  • The cool thing about it is you don’t need to dig your head deep for the logic behind each step you perform. Excel VBA does it for you.
  • For some complex tasks, such as the one which involves looping and conditional statements, you need to write code manually under VBA.

Things to Remember About Programming in Excel

  • The Developers tab is not by default enabled and visible to you in Excel Ribbon. You need to enable it through Excel Options.
  • Recording a macro works on simple tasks that are repeating, and you need those to be automated. However, for complex tasks which involve looping or Conditional Inputs and Outputs are still need to be coded manually under VBA.
  • You need to save the file as an Excel-Macro Enable file format in order to be able to read and run the code again on your excel.

Recommended Articles

This is a guide to Programming in Excel. Here we discuss how to Program in Excel along with practical examples and a downloadable excel template. You can also go through our other suggested articles –

  1. Ribbon in Excel
  2. TRIM Formula in Excel
  3. Project Management Template in Excel
  4. COUNTIFS in Excel

Все приложения из пакета Microsoft Office поддерживают возможность внедрения в их документы исполняемого кода — скриптов. При их помощи можно решать широкий спектр задач автоматизации обработки данных. А использование форм позволит буквально создать программу на основе офисного приложения. Сделать это можно, например, в Excel.

Как в Excel создать программу

Вам понадобится

  • — Microsoft Office Excel.

Инструкция

Запустите Microsoft Office Excel. Если необходимо, создайте новый документ. Для этого нажмите клавиши Ctrl+N или разверните меню «Файл» и выберите пункт «Создать…». Затем кликните по ссылке «Чистая книга» в панели «Создание книги».

Откройте окно редактора Visual Basic. Для этого нажмите сочетание клавиш Alt+F11 или выберите пункт «Редактор Visual Basic» в разделе «Макрос» меню «Сервис». Там вы увидите панель проекта, отображающую дерево объектов данной книги Excel, а также содержащиеся в ней формы, модули и модули классов.

Создайте формы, если это необходимо. В главном меню кликните по пункту Insert, а затем UserForm. В разделе Forms панели проекта добавится новый элемент. При создании форма будет автоматически открыта. Мышью переносите элементы управления из панели Toolbox в окно формы. Изменяйте их размеры и положение. После выделения мышью меняйте их свойства в панели Properties. Сохраняйте формы, нажав Ctrl+S.

Создайте нужное количество модулей или модулей классов. Для этого выбирайте пункты Module или Class Module в разделе Insert главного меню. Откройте окна редактирования кода нужных модулей или форм, дважды кликнув по соответствующим им элементам в окне проекта.

Добавьте декларации классов в модули классов. Определите их при помощи ключевого слова Class:
Class CSampleClass
End Class

В определения классов добавьте методы, а в модули — заготовки функций и процедур. Функции объявляются с помощью ключевого слова Function, после которого следует имя и набор параметров, через запятую, заключенных в скобки. Например:
Function SampleFunction(a, b, c)
End Function
Аналогично (только при помощи ключевого слова Sub) объявляются процедуры:
Sub SampleProcedure(a, b)
End Sub

Объявите члены классов, а также глобальные и локальные (в функциях и методах) переменные. Для этого используйте предложение Dim…As (после ключевого слова As указывается тип переменной). Например, объявление переменной oWB, хранящей ссылку на объект книги, может выглядеть так:
Dim oWB As Excel.Workbook
Указав размерность в круглых скобках, можно задекларировать массив:
Dim aWBooks(10) As Excel.Workbook

Реализуйте алгоритм работы программы, внеся изменения в код функций, процедур, методов классов. Используйте структуры управления Visual Basic для контроля потока исполнения. Работайте с собственными структурами данных, объектами созданных форм встроенными объектами Excel.

Источники:

  • как создать документ в excel

Войти на сайт

или

Забыли пароль?
Еще не зарегистрированы?

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Понравилась статья? Поделить с друзьями:
  • Create a picture of a word
  • Create a number line with word
  • Create a newspaper in word
  • Create a new document in microsoft word
  • Create a form letter in word