VBA Intermediate class 3 Summary

This lesson: Workbook and Worksheet Object

Speaker: rover18

Study time: November 2010

       Will learn this lesson workbook object Workbooks, Workbook and Worksheet Object Worksheets, Worksheet. We learned about the four elements of the VBA - objects, properties, methods and events following, you will find the VBA program is a series of operations and control of the object: if the object as a noun, then the property is a description of the noun adjective, method is to give the action of the verb as a noun, an event is triggered after a change of action. Everything around the object is expanded. So what objects have in VBA? What is the relationship between objects? Which properties, methods and events for each object has? The relationship between the structure of these objects we call the object model.

 

Object Model: a collection of all hierarchical distribution structure objects in EXCEL

Set (collection): Object Set consists of a set of objects, such as Workbooks is the set of all currently open Workbook object, Worksheets is designated or set of all active workbook Worksheet object.


Note: The object model tree diagram can be found in the 2003 edition of help, but in the 2007 version and the 2010 version of Help, Microsoft canceled a structure diagram, an increase of members of the set of objects form.

A workbook

(A), the workbook representation

1, index notation Workbooks (Index)

The order workbook open their number, according to the number specified reference workbook: Workbooks (1)

2, the name of the notation Workbooks ( "Worksheet name")

Workbooks ( "worksheet name .xls") 'has been saved worksheet

Workbooks ( "Worksheet name") 'unsaved work table


Note: It should be noted, has been saved workbook may not add the suffix references, but if the system is set up in the open "extensions for known file types" will be wrong. So better to write on the safe side extension.

3, two representations of constraints

        After testing found that both the index number of references, or file name references, only applies to projects Explorer displays the workbook, when by Excel shortcut to open the unsaved workbook, not in a Project Explorer, so NA, the error message "subscript out of range" appears.

(Two), new, open, activate, save, close the workbook

1, a new workbook Workbooks.Add method

Workbooks.Add(Template)

Template optional parameters to determine how to create a new workbook. If you omit this parameter, you will create a new workbook contains three blank worksheets.

Template Value Description:

parameter

value

Explanation

xlWBATChart -4109 Create a chart titled Chart is only one workbook
xlWBATWorksheet -4167 Create a new worksheet named Sheet1 only one workbook


  Application.SheetsInNewWorkbook property settings

       In Excel, the tool can be set by default worksheet number of options for new workbook, which corresponds to the VBA code is SheetsInNewWorkbook property. Changing the number of the new workbook worksheet code is:

Application.SheetsInNewWorkbook = 1 'new workbook only one worksheet


Note: This setting changes the default number of worksheets options, so I finally remember to restore.

2, open the workbook Workbooks.open method

Workbooks.Open(FileName, Password, WriteResPassword)

Parameters FileName Required, Password and WriteResPassword optional.

parameter type of data Explanation
FileName Variant To open the workbook file name. It may include file path
Password Variant A string containing the password required to open the workbook was protected by. If you omit this parameter and workbook password, the user is prompted to enter the password.
WriteResPassword Variant A string containing the password required to write protect the workbook by. If you omit this parameter and workbook password, the user is prompted to enter the password.

Example:

Workbooks.Open ( "C: \ Desktop \ exercises .xls")

Open method there are many other parameters, lists the common parameters.

3, activate the workbook Workbook.Activate method

Use the Workbook object Activate method can open the workbook becomes the active workbook. Example:

Workbooks ( "exercises .xls"). Activate

4. Save the workbook


Save your changes to the workbook: Workbook.Save method

Workbooks ( "exercises .xls"). Save

AciveWorkbook.Save


Do not save changes to the workbook: Workbook.Saved property

The Saved property of the workbook is True, indicates that the workbook changes from the last save has not happened, you can not save and close the workbook without modification made to the workbook.

Workbooks ( "exercises .xls"). Saved = True

The first time you save a workbook, with Workbook.SaveAs method

Workbook.SaveAs(FileName, FileFormat, Password, WriteResPassword,)

Filename mandatory parameters, optional parameters other.

name type of data Explanation
Filename Variant To save a string representation of the file name. It may include the full path, if you do not specify a path, the file will be saved to the current folder.
FileFormat Variant File format used when saving files. For existing files, defaults to the last file format specified; for the new file, using the default format for the current version of the Exce used.
Password Variant It is a case-sensitive string (maximum of 15 characters), password protection for the specified file.


   Note: To write the file name extension, otherwise the default format uses the current version, if you use 2007 or later, you can use * .xls sure to save as a 2003 version of the file.

Activeworkbook.SaveAs Filename: = "C: \ job title .xls" 'to save the new file

workbooks ( "exercises .xlsx") SaveAs filename:. = "C: \ job title .xls" 'to save the file already exists


Note: The adoption of an existing file saved as backward compatible, that is, if the original file is more than the 2007 version, save for the 2003 version, but in turn, 2003 version of the file can not be saved as more than 2007 versions of files through "SaveAs" method.

5, close the workbook Workbook.Close method

Workbook.Close(SaveChanges, Filename)

All parameters are optional

name type of data Explanation
SaveChanges Variant If the workbook is not changed, this parameter is ignored. If there are changes to the workbook, this parameter is True, save the changes to the workbook. If the workbook has not been named, use the FileName parameter. If you omit the Filename parameter, the user is required to provide a file name.
Filename Variant In this file name to save your changes.

     Example:

activeworkbook.Close savechanges: = true, filename: = "C: \ Exercises .xls" 'Save changes to the new workbook and close

Workbooks ( "Problem .xls"). Close false 'off without saving the changes, may be omitted Savechanges

(C), other common properties

1, Workbooks.Name attribute (name)

Returns a String value that represents the name of the object. We can rename the workbook by Name attribute.

2, Workbooks.path properties (storage path)

Returns a String value that represents the full path to the application, excluding the end delimiter and file name.

3, Workbooks.fullname properties (full path)

Returns the name of the object (expressed as a string), which comprises a disk path. String type. It is the result of a complete Path property and the Name property of the workbook.

FullName=Path &“\”& Name

4, Workbook.IsAddin property

If you specify a workbook as an add-in to run, the property value is True. Boolean type. If this property is set to True, then the workbook will have the following characteristics:


If the changes when you open the workbook you will not be prompted to save the workbook.
Workbook window is not visible.
The workbook macros are not displayed (pointing to the "Tools" menu in the "macro" item and click the "macro" command to display the dialog box) in the "Macro" dialog box.
Although the workbook macros are not visible in the "Macro" dialog box, you can still pass the "Macro" dialog to run macros in the workbook. In addition, the macro name without using the workbook name identification.
When you open a workbook hold down the Shift key does not work.

Second, the worksheet

(A), Sheets set the difference between the set Worksheets

Sheets collection on behalf of all current worksheet workbook, including the chart sheet Chart, worksheet Worksheet and macro sheet.

Worksheets collection only on behalf of all current worksheet Worksheet workbook.

Charts collection specified or active workbook set of all the chart sheets Chart

(B), the worksheet representation

1, index notation Worksheets / Sheets (Index)

The worksheet location (index number) in the workbook. Index sheet tabs from the left to right, count the first worksheet usually Worksheets (1), said last sheet usually Worksheets (WorkSheets.count) FIG. If you want to reference all the worksheets in the workbook contains charts and worksheets, including, to use the Sheets collection of objects.

2, table name Notation Worksheets / Sheets ( "Sheet Name")


Note: use the worksheet name string, such as Worksheets ( "Sheet1")

3, the code name attribute representation Worksheet.codename

In addition to these two common mode represents a worksheet, there is a less common, but very practical approach: Codename properties.

Codename is the name of the worksheet automatically assigned when you create a worksheet, you can see Sheet1 (Sheet1), in brackets is the Name property in Project Explorer, outside of the parentheses is CodeName property. It can (name) of a first row of modifications in the properties window. Whether it is to sort the worksheet, or rename the worksheet, which CodeName properties do not change (unless you delete the worksheet, or is (name) rename items in the VBE window).

Sheet3.Name 'return to the table name Sheet3 table

tt

See the FIG., The green area is the Name property, the work table; yellow region is CodeName properties. Note the immediate results window, three ways to obtain three different results.

(Iii), create, delete, copy, move, select the worksheet

1, a new worksheet Worksheets.Add method

New worksheet, chart, or macro sheet. The new sheet will become the active worksheet. Worksheets.Add (Before, After, Count, Type), the parameters are optional

name type of data Explanation
Before Variant Before specifying the worksheet object, the new worksheet This worksheet will be placed
After Variant After specifying the worksheet object, the new worksheet This worksheet will be placed
Count Variant To add a number of worksheets. The default is 1
Type Variant Specify the type of worksheet, you can be one of XlSheetType constants: xlWorksheet, xlChart, xlExcel4MacroSheet or xlExcel4IntlMacroSheet. If you insert a template based on an existing worksheet, the template path is specified. The default value is xlWorksheet


Note: The default insert a new worksheet in front of the active worksheet.
Note: The name may be in the Add New Sheet Name property method followed by

worksheets.Add.name = "excelhome" 'while the new name for the worksheet

2, delete the worksheet Worksheets.delete method

3. Copy Sheet Worksheets.copy method

Microsoft Excel将工作表复制到工作簿的另一位置并自动为其命名为:原表名(2)。Copy方法带有2个可选的参数,即参数Before和参数After,在使用时两个参数只参选一。

名称 数据类型 说明
Before Variant 将要在其之前放置所复制工作表的工作表。如果指定了 After,则不能指定 Before。
After Variant 将要在其之后放置所复制工作表的工作表。如果指定了 Before,则不能指定 After。


     注:如果既不指定 Before 也不指定 After,则 Microsoft Exce将新建一个工作簿,其中包含复制的工作表。

Worksheets("sheet2").Copy After:=Worksheets(sheets.count)‘复制Sheet2表到最后

4、 移动工作表Worksheets.Move方法

Move方法与Copy方法的参数相同,作用也一样,用法可参照Copy方法。

5、 激活、选择工作表


激活工作表Worksheet.Activate方法

Worksheets("sheet2").Activate ‘ 激活当前工作簿中的工作表sheet2


选择工作表Worksheet.Select方法

Worksheets("sheet2").Select ‘ 选择当前工作簿中的工作表sheet2


Active与Select方法区别

‘以下示例同时选择工作簿中的工作表sheet2、sheet3和sheet5

‘方法1:

Worksheets(Array("sheet2", "sheet3","sheet5")).Select ‘用Array参数

‘方法2

Worksheets(“sheet2”).Select

Worksheets(“sheet3”).Select Replace:=False ‘用Replace参数

Worksheets(“sheet5”).Select False ‘可以省略Replace

当工作表隐藏后,Select方法将会出现错误,而使用Activate则会正常运行;Activate方法只能激活一个工作表,而Select方法可以同时选择多个工作表。


注:如果Replace值为True,则此语句前选中的工作表将被取消选中。

三、 Application.DisplayAlerts属性

禁止显示警告和消息框,默认值为 True。将此属性设置为 False 可在宏运行时禁止显示提示和警告消息;当出现需要用户应答的消息时,Microsoft Exce将选择默认应答。

1、 自动覆盖保存现存工作簿

如果使用工作簿的 SaveAs 方法覆盖现有文件,则“确认另存为”对话框具有的默认响应为“否”;如果将 DisplayAlerts 属性设置为 False,则 Exce选择的响应为“是”。如果选择的响应为“是”,则将覆盖现有文件。

2、 不保存修改直接关闭工作簿

如果使用工作簿的Close方法关闭现有文件,若修改文件后未保存,且DisplayAlerts 属性设置为 False,则“确认保存关闭“对话框的默认响应为”否“,即不保存对工作簿所做的更改就关闭。

示例:

Sub test()

Application.DisplayAlerts = False

Cells(3, 2) = "It's a test"

Workbooks("练习题.xls").Saveas filename:=”练习题.xls” ‘自动覆盖文件保存

Cells(3, 2).Clear

Workbooks("练习题.xls ").Close ‘不保存修改,直接关闭

Application.DisplayAlerts = True

End Sub

3、 删除工作表不跳出警告框

用Delete方法删除工作表会引起Excel跳出警告对话框

To avoid this, we can use Application.DisplayAlerts = False to shield pop-up warning box, the default response at this time of the dialog box to "delete."

IV Summary

This lesson of Excel workbooks and worksheets objects made a brief introduction on the representation workbooks, worksheets, create, save, delete, and other methods and properties close very simple example. In fact, members of the Workbook and Worksheet Object object there are many methods, properties, and events, it has not been introduced in the lesson, while the workbook and worksheet objects are used to and we will be at work objects, so in practical applications to be more use of Microsoft's own VBA help, and do not forget to learn by recording the macro.

ExceHome Technology Forum

 

Excehome free online training center

Reproduced in: https: //www.cnblogs.com/zhangchenliang/archive/2012/11/07/2758636.html

Guess you like

Origin blog.csdn.net/weixin_34112208/article/details/93495282