Вы находитесь на странице: 1из 361

Microsoft : Office. : , , .

( ), ,
. . IT- , :
Excel SQL Server,
(, )
;
Excel;
(300400 ) Project Central ( Microsoft Project)
- ;
Word,
.
, , .
,
. , , ,
.
(, Excel
Word), .

10

,
, .
, (
30 Microsoft) - Microsoft Official Curriculum (MOC).
: Microsoft Access
- : ( 2381), ( 1904) . . , .
. ,
" Office",
. Office
Excel,
VBA, - - (
VBA ).
" " Word, Excel, Access,
PowerPoint, Outlook Project, .
.
, VBA, . ,
. ( ) , .
( ) , . .
,
.
.
:
"" .
( ),

11

, ;
, ,
. (" Excel"), ,
;
Office ,
(, Word Application Document Selection, Range Bookmark,
Excel Application Workbook Worksheet Range). 80% VBA;
,
, . . ,
.
.
.
Microsoft Office 2003 .
Office XP.
Office 97 Office 2000,
. ,
VBA Office , , ,
. , Microsoft
Office, ,
VBA.


. ! ,
, .
info@askit.ru, Web- www.askit.ru.

( ). ,
, ,
.
Course page:
http://www.askit.ru/custom/vba_office/vba_office_info.htm


Microsoft Office
1.1.
Microsoft Office
: . Office , ,
( , ). ,
:
, : , ,
, . . ,

. ,

;
: . , .
(, , , , , . .) :
, , -,
. . ( , ), (, Word)
;
, . , , -

Microsoft Office

13

, 2%. ""
,
, .
, ,
, . , Outlook, Project,
Excel
, Office
.
, ,
?
, , :
;

( ),
, . .,
.

1.2. VBA
, . .
VBA (Visual Basic for Applications) Visual Basic,
Microsoft Office Microsoft .
, Office
VBA. COM- , :
Visual Basic, VBScript, Java, JScript, C++, Delphi . .
.NET- : VB.NET, C# . .
Office. , vbs
, Word, :
Dim oWord
Set oWord = CreateObject("Word.Application")
oWord.Visible = true
oWord.Documents.Add
oWord.Selection.TypeText (" VBScript")

14

, VBA Office. VBA


Office, VBA
Office: Word, Excel, PowerPoint . . , ,
VBA ( )
.
VBA :
Microsoft Office Word, Excel, Access,
PowerPoint, Outlook, FrontPage, InfoPath;
Microsoft, Visio Project;
100 , , CorelDRAW
CorelWordPerfect Office 2000, AutoCAD . .
.
VBA . ,
Office , ,
, :
Visual Basic (
);
VBScript ( "" VBA).
Windows, Web (VBScript Internet Explorer), Web- ASP, DTS SQL Server,
Exchange Server - .
VBA , ( ), . , Office , : , . .
VBA , ,
Microsoft
Office .
, VBA ,
, , ,
. , , VBA
: , -

Microsoft Office

15

, . , VBA-
VBA, , . VBA ( , ),
C++ DLL
(Add-In) Word, Excel, Access . .
VBA ,
.
.
- , VBA Office.
(C++, Java, Delphi) ,
, . , Office ( , , . .)
.

1.3. :

Microsoft Office ( Access FrontPage)
, , .
.
, , . VBA-, .

Microsoft Office 2003 , . , ,


| |
, .
.


: ,

16

. , (. . ).
, VBA. . ,
"" , , . ., (,
, , . .),
.
,
, ,
.
:
, ,
. ,
. ,
, ,
(<Ctrl>+<Home>);
, ,
. | .

, , , ;
,
,
. - , .
,
.
( Microsoft Office,
, , Word, Excel, PowerPoint,
Project):
1. | . (. 1.1) :
. : ,
.
Excel 64 , Word 80 . ;

Microsoft Office

17

. ,
;
. Word
Normal.dot,
Excel ,
PERSONAL.XLS
( ). , ,
. 2.2;
. , , ( ).

. 1.1.

2. OK .
. .
, | | .
3. ,
, | ( <Alt>+<F8>),

18

(. . 1.2)
. , . .
,
( Word)
| | ,
Word, ListCommands
. (
Word 26 ). , .
, VBA
, , . :
- ,
;
, - ( VBA InputBox()
);
, .
, .
, .
, , ,
Office. , , Office
.
: Excel.
Excel | , , , VBA
Diagram. , , , ,
! Diagram , Excel " " (
), Chart. (. . -

Microsoft Office

19

), .

1.4.
, ( , ,
Visual Basic, ),
,
. .
,
, | | (. 1.2).

. 1.2.

:
;
Visual Basic ;
Visual Basic;
Visual Basic
;

20

;
.
, ( ,
, ) . ,
.
.
, . , ,
, ""
, . "Visual
Basic", <Alt>+<V>, Microsoft Office <Alt>+<M>. (, ) ,
. . !

, , ,
, ,
, . .
, ,
.
.
Word : |
.
: (. 1.3).
, ,
.
<Alt>+<1>, <Alt>+<M> . ., .
,
: . <Alt>+<N>, <F> <Alt>+<N>, <S>. ,
<Alt>+<N>, <F>, . , .
,
, .

Microsoft Office

21

. 1.3.

.
, . ,
.
(<Ctrl>+<S>, <Ctrl>+<N> . .),
.

Excel ( | )
. : | ,
.
(. 1.4),
( <Ctrl>) . ,
Excel, , .
, , . , , ,

22

, ?
, . ( )
, .

. 1.4.


. ,
. ,
, . Word :
1. .
2. , (,
_) , .
Normal.dot, Word ( ). Word,
. .
3. OK ,
( -
). ,
,
| . ,

. , , , ,

Microsoft Office

23


(. 1.5).

. 1.5.

,
(, Normal.NewMacros.QueryTable).
- .
. (
!) , .
(. 1.6).
:
(
);
, . . .
,
, ;
;

24

. 1.6.

,
;
42 .
Word , , ;
,
: ,
;
(), ( ), , / .
, ;
();

.
, ,
( ).
. ,
.

Microsoft Office

25

-:
1. ( | ).
2. .
3.
(. 1.7) .

. 1.7.

4.

( ).
.
(. 1.8)

(. . ). .
, (. 1.9).
Excel , - -. Excel
( | )
, : (. 1.10).

26

. 1.8.

. 1.9.

,
, . , ,
. . , Word.
Excel ,
Word,
.
( )
.

Microsoft Office

27

. 1.10. Excel

Office (PowerPoint,
Project, Outlook . .) , Word.

, : , , , . , "" (
, , ).
.
, . 5. .
: ,
. , , Excel,
Excel Word . .
. 5.
:
. , Word
. 1.1.

28

1.1. Word

AutoExec

Word ( Normal.dot)

AutoNew

AutoOpen

( Normal.dot)
,

AutoClose

AutoExit

Word

Excel
Auto_Open, Auto_Close, Auto_Activate Auto_Deactivate. Microsoft
, , .
, Auto: , Office 2003
.
,
| | .
, , , , ,
.
Word Excel, . , Word
MyMacros Normal.dot, :
winword.exe /mMyMacros

, Office, , ,
.

1:

Word
:
. ,
. 1.11.

Microsoft Office

29

. 1.11. ,

:
,
( " . ." ).
. (. 1.12).
, ,
.

. 1.12.

1
1. Word. |
.
"" ( ), ,
(Normal.dot), .
2.
Normal.NewMacros. . , , .
. .
.
3. ,
( | ).
4. Word ,
.


Visual Basic
2.1.
, . : , - , ,
. (, Word
Selection
Range). , ,
.
Office Visual Basic, .
, ,
.
Visual Basic , .

,
Microsoft Office, VBA Visual Basic .
COM- , , Visual Basic, C++, Delphi, Java,
VBScript JavaScript, ActivePerl, C#, Visual Basic .NET . . VBA
( Visual Basic) Microsoft Office,
Microsoft Office .

Visual Basic

31

Visual Basic, .
Office :
|
Visual Basic;
<Alt>+<F11>;
Visual
Basic ( );
;

.
, . 2.1.

. 2.1. Visual Basic Excel

Visual Basic , . <Alt>+<Tab> ( "",


<Alt>+<F11>).

32

Visual Basic 9 :
Project Explorer .
Visual Basic. . . 2.2;
UserForm . , . . 5;
Toolbox . . . 5;
Properties .
;
Code . . . . 2.3;
Object Browser . , .
. 4, ;
Watch .
. , Locals
Immediate, . 6, ;
Locals .
;
Immediate .
.
- : View
, , .
, .
Office Visual Basic . VBA
Office . , . , ,

Visual Basic

33

, VBA,
( ): , .

2.2.
(Project Explorer) VBA
Visual Basic
. ,
:
<Ctrl>+<R>;
Project Explorer Standard;
View | Project Explorer.
Project Explorer VBA.
(Project), Word, Excel, PowerPoint ,
. , Visual Basic Word, Project Explorer Word Normal.dot.
Visual Basic Excel, Project Explorer
Excel PERSONAL.XLS.
, Office (, ,
. .), ( ) , . Insert Project
Explorer.
VBA. :
(
);
( ).
Word Normal.dot ( ) NewMacros ( Excel Module1), .

34

VBA , . :
( Project
Explorer).
VBA ( VB);
. , , ;
.
, , ,
.
,
. . VBA
, .

, ,
.
. 5.
Project Explorer References, . .
( Excel ). ,
( Word) , , ,
"" .
Word Normal (. .
Normal.dot), .
,
. . 4.
Project Explorer
. Project
(VBAProject Excel) Project Properties (
Tools | Project Properties).
:
. ,
;

Visual Basic

35

, , ;
, . ,
.
Project Explorer .
, ,
(, ) Insert | Module.
.
. 2.3.
(
), . Modules. , .
, .

, . ,
. ,
Normal ( Word) PERSONAL.XLS ( Excel).


(, , . .),

Insert | UserForm.
. . 5.
, ( ),
VBA.

2.3. (Code Editor)


2.3.1.
,
. :
Project Explorer (
<Enter>);

36

( Project Explorer, . .)
View Code;
<F7> (
View | Code).
, , ,
, ,
<Ctrl>
, Word.
-
. .

2.3.2.
.
. , . ,
General. , ,
.
.
Declarations
() ,
.
, .

2.3.3.

, .
, , ,
. . ( ) , .
Edit ( ),
Edit | Bookmark. , Toggle Bookmark.
, . .

.

Visual Basic

37

2.3.4.
, . .
.
VBA-
( . 4),
. ,
,

.
Visual Basic . :
, , . .
(
, ,
), <Tab>.
, Edit | List
Properties/Methods <Ctrl>+<J>.
,
Tools | Options ( Auto List Members
Editor Options).
Visual Basic
, , . :
. , Edit | Parameter Info <Ctrl>+<Shift>+<I>.

Auto Quick Info Editor
Options.
( ) , '='.
Edit | List Constants
<Ctrl>+<Shift>+<J>. . 3.
VBA
.
Edit | Complete Word
<Ctrl>+<>. , - .

38

, :
, . Auto Indent Options;
,
;
.
Edit Comment Block
Uncomment Block;
Sub
Function, End Sub
End Function. -;
, . , , .
, Auto Syntax Check Options. ,
;

.
<Ctrl>+<Tab> <Ctrl>+<F6>;
Full Module View .
, Procedure View. .

2.4.
Office , .
Visual Basic <F1>.
Standard. , . 2.2.

(,
) <F1>.

Visual Basic

39

, (, Range Range) .
Microsoft Office :
(Microsoft Excel Visual Basic Reference, Microsoft Word
Visual Basic Reference . .)
Office;
(Microsoft Visual Basic Documentation,
Office)
VBA;
(Microsoft Office Visual Basic Reference, Office)
Office: ,
, Windows SharePoint
Services . .
(, Microsoft Access) (. 2.3) ADO, SQL . .

. 2.2. VBA Excel

. 2.3. VBA Access

, Office. (. 2.4):

40

. 2.4. Excel

Programming Concepts ( )
, . , Excel , , . .;
Office: (Collections), (Objects), (Methods), (Properties) . . ,
( , ,
Range Excel), .
, .
, . . , , :
Programming Concepts
;

Visual Basic

41

, ,
, . , Office ( , ). - Office,
, , . ,
, ;
, . , , .
, :
VBA , , . , -
,
Office.

2:

:
. 1 , . :
( Selection.TypeText)
:
Dim sInput As String
sInPut = InputBox(" ",
" ")

:
Selection.TypeText Text:=(". . .")

( ) :
Selection.TypeText Text:=(". " & sInPut)

, ,
-.

42

, .
, Visual
Basic ( InputBox()) Word ( TypeText() Selection) . .

2
1. Word <Alt>+<F11>.
Microsoft Visual Basic Project Explorer,
Normal | Modules | NewMacros, NewMacros
<F7>. NewMacros.
2. Sub () . , , (
:
, ):
Sub ()
'
'
' 02.05.2004 R
'
Dim sInPut As String
sInPut = InputBox(" ", _
" ")
Selection.TypeText Text:=" :" & vbTab & vbTab _
& vbTab & " . ."
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
Selection.TypeParagraph
Selection.ParagraphFormat.Alignment = wdAlignParagraphLeft
Selection.TypeText Text:=(". " & sInPut)
Selection.TypeParagraph
Selection.TypeText Text:=". 55-55"
End Sub

3. <Ctrl>+<S>, , <Alt>+<Q>,
Word. , , .


VBA
3.1.
, , VBA. , , , :
,
. ,
VBA ,
, .
, Visual Basic,
. , (C++, Java, Delphi, VBScript
JavaScript, Perl . .) . , , , , - ,
. ,
VBA
.
,
VBA.
VBA, ( Visual Basic for Applications),
Visual Basic.

44

:
VBA ;
,
(') REM;
(");
VBA (, , ) 255 ;
( ,
C, Java, JavaScript, );
( 308 ). :
MsgBox " 1" : MsgBox " 2"

:
MsgBox " " _
& vUserName

3.2.
VBA.
, VBA - .
VBA 7. :
(+), (), (*), (/), :
(^). , 2^3 = 8;
(\). , (
) . , 5\2 = 2;
(Mod). ,
. , 5 Mod 2 = 1.
VBA . :
Let nVar = 10

:
nVar = 10

VBA

45

. " nVar 10", :


If (nVar = 10)

" nVar 10".


, .
VBA 8:
(=). , If (nVar = 10);
, (>) , (<). , If (nVar > 10);
(>=) (<=). , If (nVar >= 10);
(<>). , If (nVar<>10);
(Is). ,
. , If (obj1 is obj2);
(Like). ,
.
True ( )
False ( ).
:
;
;
/ . , ,

Option Compare Text

Like :
1 Like 2

1 VBA, 2
, Like. (. 3.1).

:
And
Or

. ;

. ;

46
Not

. True, ;

Xor . E1 Xor E2 True,


E1 = True E2 = True, False;
Eqv

, True,
;

Imp , E1 Imp E2
E2 = False, True.

False, E1 = True

And, Or, Not, .


3.1. Like

0 9

( )

[a,b,c]

[!a,b,c]

VBA , . .
. VBA (+) (&).
(&), :
(&) ;
(+) Null Null.
(&):
MsgBox " " & vUserName

: , , . ,
. .

VBA

47

3.3.
.
.
- ,
. ,
" " .
VBA :
Dim nMyAge As Integer
nMyAge = nMyAge + 10
MsgBox nMyAge

. :
Dim nMyAge As Integer

.
Dim

. VBA 4 .
Dim .
Dim , , .
Private

VBA , Dim.
( ).

Public , .
, Dim.
Static . , ,
. - .
:
Static nVar1 As Integer
nVar1 = nVar1 + 1
MsgBox nVar1

, Dim.

48

(nMyAge) ( , ) . VBA (, , , . .):


;
(
);
255 ;
( .
. 3.3);
(,
) .
VBA
,
. ( Microsoft, Charles Simonyi,
):
,
. , :
str ( s) String, ;
fn ( f) ;
sub ;
c ( ) ;
b Boolean, (True False);
d ;
obj ( o) ;
n ;
, :
MsgBox objMyDocument.Name
Sub CheckDateSub()

VB Const,
, ,
, COMPANY_NAME.

VBA

49

( Const . 3.4).
(As Integer)
. ,
.
VBA :
:
Byte 0 255;
Integer 32 768 32 767;
Long 2 147 483 648 2 147 483 647;
Currency 19 ,
4 ;
Decimal 29 ( 0 28 );
Single Double (Double 2
));

Decimal (, Dim n As Decimal)


.
Decimal, Variant (Dim n), Variant
VBA . Variant
, Decimal, VBA
. , Decimal Variant CDec().

(String ( 2 )
( 65 400 ));
(Date 01.01.100 31.12.9999);
(Boolean True False);
(Object );
Variant

, .

,
Type.

50


( ).
, :
,
. - ;
,
(Single Double). ,
, ;
((%) Integer, ($) String . .). , :
' Dim nVar1 As Integer

:
nVar1% = nVar1% + 1

.
. ,
:
Dim nVar1

Variant.
, VBA . ,
nVar1 = nVar1 + 1
MsgBox nVar1

. ,
Variant. !
. :
:
(, );

,
. , Excel :

VBA

51

:
Dim oWbk As Workbook
Set oWbk = Workbooks.Add

:
Set oWbk = Workbooks.Add

oWbk
.

. ( ):
Option Explicit

, Options Require Variable Declarations (


Tools | Options, Editor).
, , :
Dim n
n = n + 1
MsgBox


. . : n
N, . . VBA, , Variant, .
.
Option Explicit .
, , :
Dim nVar1 As Integer, s1 As String

:
nVar1 = 30

,
:
nVar1 = nVar1 + 1

"", "".

52

:
:
sVar1 = "Hello"

/ "" (#):
dVar1 = #05/06/2004#

, /
"" : 05 , 06 .
(, )
;
,
(&H):
nVar1 = &HFF00

( ) (&O).
:
0;
"" (
);

ASCII 0 ( );
Variant Empty.
(. . ) IsEmpty();
Object ( ).

3.1:

:
1. Excel C:\LabVariablesOperators.xls.
A1, A2 A3 .
2. Visual Basic Excel
(. . 2.2).

VBA

53

3. Tools | References
Microsoft Word 11.0 Object Library.
4. :
Public Sub
MsgBox
MsgBox
MsgBox

FromExcelToWord()
Range("A1").Text
Range("A2").Text
Range("A3").Text

Dim oWord As Word.Application


Dim oDoc As Word.Document
Set oWord = CreateObject("Word.Application")
oWord.Visible = True
Set oDoc = oWord.Documents.Add()
oDoc.Activate
oWord.Selection.TypeText " "
End Sub

A1, A2 A3,
Word
" ".
5. , .
:
, " " A1, A2 A3 .

3.1
:
Public Sub FromExcelToWordAnswer()
Dim sA1, sA2, sA3, sText As String
sA1 = Range("A1").Text
sA2 = Range("A2").Text
sA3 = Range("A3").Text
sText = sA1 + " " + sA2 + " " + sA3
Set oWord = CreateObject("Word.Application")
oWord.Visible = True
Set oDoc = oWord.Documents.Add()
oDoc.Activate
oWord.Selection.TypeText sText
End Sub

54

3.4.
, ,
, VBA-. :
, ;
- (, ),
.
VBA Const:
Const COMP_NAME As String = "Microsoft"

,
.

( , , , , . .). . , :
UserForm1.BackColor = vbGreen

UserForm1.BackColor = 65280

, , .
VBA : ,
, , , . .
VBA: Microsoft Visual Basic Documentation |
Visual Basic Language Reference | Constants. ( Miscellaneous Constants) :
vbCrLf , :
MsgBox " " + vbCrLf + " "


Office, . 1015.

3.5.

.
: - ( -

VBA

55

- ) . VBA
: If...Then Select Case.

3.5.1. If ... Then


If...Then . ( ):
If Then
1
[ElseIf N Then
N]
[Else
2]
End If

, . , 1, 2;
N

, .
, ( N ), N. (
ElseIf) ,
, Select Case (.
. 3.5.2).
If...Then :

- :
If nTemperature < 10 Then
MsgBox " "
End If

, , :
If nTemperature < 10 Then
MsgBox " "
Else
MsgBox " "
End If

56

( ):
If (nTemperature < 10) And (bRain = True) Then
MsgBox " "
End If

, False,
( ElseIf):
If (bIGoInCar = True) Then
MsgBox " "
ElseIf nTemperature < 10 Then
MsgBox " "
Else
MsgBox " "
End If

, bIGoInCar Boolean
True False, :
If bIGoInCar Then ...

If...Then:
Then If .
,
;
, , If Then, End If
:
If nTemperature < 10 Then MsgBox " "

Else/ElseIf,
End If , ;
If...Then . ;
If...Then :
If MyVar = 5 Then
MsgBox "MyVar = 5"
If MyVar = 10 Then
MsgBox "MyVar = 10"
End If
End If

VBA

57

3.5.2. Select Case


Select Case , . :
Select Case
Case 1
1
[Case N
N]
[Case Else
2]
End Select

:
Select Case sDayOfWeek
Case ""
MsgBox " "
Case ""
MsgBox " "
Case Else
MsgBox " "
End Select

Select Case:
:
Case ""

:
Case sDayOfWeek = ""

. , :
Case 0 To 5, 15, Is > 55

" 0 5 , 15, 55".


Is VBA
. Case
, Or, . .
, ;

58

(0 To 5)
( 0 5).

3.5.3. GoTo
GoTo ,
- .
GoTo :
GoTo EngineNotStarted
...
EngineNotStarted:
MsgBox " "
...

EngineNotStarted: , (
), . , GoTo.
, GoTo "" GoTo .
GoTo , , .
GoTo ,
. GoTo Do While...Loop (. . 3.6) .

3.2:

:
1. Excel C:\LabCondConstructions.xls.
2. Visual Basic Excel
.
3. :
Public Sub IfThenSub()
Dim nResult As Integer
nResult = MsgBox(" ", vbYesNo, " ")
ThisWorkbook.Worksheets(1).Range("A1").Value = _
" : " & nResult
ThisWorkbook.Worksheets(1).Range("A1").Columns.AutoFit
End Sub

VBA

59

4. ,
. A1 " : 6", , .
, ,
MsgBox().

3.2, :
,
(, "
:
").
If...Then...Else.
3.2, :
:
Public Sub IfThenSubAnswer()
Dim nResult As Integer
nResult = MsgBox(" ", vbYesNo, " ")
If nResult = vbYes Then
sResult = ""
ElseIf nResult = vbNo Then
sResult = ""
Else
sResult = " "
End If
ThisWorkbook.Worksheets(1).Range("A1").Value = " : " _
& sResult
ThisWorkbook.Worksheets(1).Range("A1").Columns.AutoFit
End Sub

3.2, :
:
nResult = MsgBox(" ", vbYesNo, " ")

:
nResult = MsgBox(" ", vbAbortRetryIgnore, " ")

, A1
"", "" "", ,
. Select Case.

60

3.2, :
:
Private Sub SelectCaseAnswer()
nResult = MsgBox(" ", vbAbortRetryIgnore, "
")
Select Case nResult
Case vbAbort
sResult = ""
Case vbRetry
sResult = ""
Case vbIgnore
sResult = ""
Case Else
sResult = " "
End Select
ThisWorkbook.Worksheets(1).Range("A1").Value = " : " _
& sResult
ThisWorkbook.Worksheets(1).Range("A1").Columns.AutoFit
End Sub

3.6.
, -
. ,
,
For...Next:
For iCounter = 1 to 10
MsgBox ": " & iCounter
Next

, , Step:
For iCounter = 1 to 10 Step 2
MsgBox ": " & iCounter
Next

:
For iCounter = 10 to 1 Step -2
MsgBox ": " & iCounter
Next

VBA

61

For...Next
Exit For:
VStop = InputBox(" ")
VInput = CInt(VStop)
For iCounter = 1 to 10
MsgBox ": " & iCounter
If iCounter =VInput Then Exit For
Next

VBA - ,
Excel, . .
,
For Each...Next:
For Each oWbk in Workbooks
MsgBox oWbk.Name
Next


:
For Each oWbk in Workbooks
If oWbk.Name = ".xls" Then
Set oMyWorkBook = oWbk
Exit For
End If
Next

Workbooks
(. . Excel),
, ".xls",
. ,
, , , :
Set oMyWorkBook = Workbooks(".xls")

For Each...Next .
: , - .
Do While...Loop Do Until...Loop.
Do While...Loop : -
, :

62
Do While MyVar < 10
MyVar = MyVar + 1
MsgBox "MyVar = " & MyVar
Loop

: , , ,
, . .

,
<Ctrl>+<Break>. ,
. 3.1, ( Continue), (End) (Debug).

. 3.1. <Ctrl>+<Break>

Do Until...Loop. , : , .
Do Until MyVar >= 10
MyVar = MyVar + 1
MsgBox "MyVar = " & MyVar
Loop

,
:
Do
MyVar = MyVar + 1
WScript.Echo "MyVar = " & MyVar
Loop While MyVar < 10

, , .
Exit Do.

VBA

63

VBA While...Wend. ,
Visual Basic. ,
Do While...Loop:
While My Var < 10
MyVar = MyVar + 1
WScript.Echo "MyVar = " & MyVar
Wend

3.7.
.
,
.
:
Dim MyArray(2) As Integer

2 (upper bound).
(lower bound) 0. , , 0
. .
, (, , ) 1, :
Option Base 1

, :
Dim MyArray(2)

Variant.
,
, (, Integer
String).
( ) :
MyArray(0) = 100

:
MsgBox MyArray(0)

64

, , :
Dim MyArray(4, 9)

, (, , ,
). VBScript
60 .
,
. :
Dim MyArray()
ReDim MyArray(4)

'
'

ReDim ,
. , Preserve:
ReDim Preserve MyArray(7)

,
, Preserve
.
:
Dim MyArray
MyArray = Array(100, 200, 300, 400, 500)

.
Erase:
Erase MyArray

,
( )
.
, .
UBound() (
, ):
UBound(_ [, ])

, VBA
.

VBA

65

Office . , .
, Word Documents Document, . . , Excel Workbooks
( ) Worksheets ( ) . .
, :
( Add()
, Count ,
Item() ). .

3.3:

:
1. Word C:\LabLoops.doc.
.
2. Visual Basic .
3.3, :
ForNextSub(), 10 1 10.
3.3, :
:
Public Sub ForNextSub()
Dim i As Integer
For i = 1 To 10
MsgBox i
Next
End Sub

:
Public Sub ForNextSub2()
Dim i As Integer
i = 1
Do While i <= 10
MsgBox i

66
i = i + 1
Loop
End Sub

3.3, :
ForEachSub(),
LabLoops.doc.
() ThisDocument.Words.
Text .
3.3, :
ForEachSub() :
Public Sub ForEachSub()
For Each oWord In ThisDocument.Words
MsgBox oWord.Text
Next
End Sub

3.8.
3.8.1.
VBA. VBA
,
- ( , . .).
, (
"" ).
: ( General Declarations)
. .
VBA :
Sub () - :

VBA

67

Sub Farewell()
MsgBox "Goodbye"
End Sub

VBA Sub, .
VBA
Office. ,
, ;
Function () ,
. : ( ) - ,
. :
Function Tomorrow()
Tomorrow = DateAdd("d", 1, Date())
End Function

:
Private Sub Test1()
Dim dDate
dDate = Tomorrow()
MsgBox dDate
End Sub

, - . :
Tomorrow = DateAdd("d", 1, Date())

, Sub , (. . 3.8.4).
? :
. ,
:
Private Sub Test1()
MsgBox Tomorrow()
End Sub

VBA ( Office).
: Date(), , DateAdd(),
, , , . . . 3.9.

68

VBA (event procedure)


Sub ,
, ,
. . 5.
Property ( ).
,
, .

3.8.2.
VBA (
) (Public). ,
, ,
. Public :
Public Sub Farewell()

, Public ,
:
Sub Farewell()

:
Private Sub Farewell()

,
.
, , ,
.
(,
Public) - .

Option Private Module

Static,


(. . 3.3). :
Private Static Sub Farewell()

3.8.3.
, , :
Private Sub Farewell()

VBA

69

End Sub . , Insert |


Procedure. .

3.8.4.
, . , , , . , .
, :
Function fSum(nItem1 As Integer, nItem2 As Integer)
fSum = nItem1 + nItem2
End Function

:
MsgBox fSum(3, 2)

,
- (,
fSum(3)) "Argument not optional" "
". - ,
.
Optional:
Function fSum(nItem1 As Integer, Optional nItem2 As Integer)

VBA .
, ,
IsMissing (
Variant),
( , . .).
:
nResult = fSum(3, 2)

, .
, . . 3 (nItem1), 2 (nItem2). :
nResult = fSum(nItem1 := 3, nItem2 := 2)

70

, , , , (:=), C++.
.
, (fSum(3, 2))
. , "" , ?
?
, : ( , byRef)
( byVal).
, .
,
. VBA .
, . , , .
:
Private Sub TestProc()
' nPar1
Dim nPar1 As Integer
nPar1 = 5
' nItem1 fSum
MsgBox fSum(nItem1:=nPar1, nItem2:=2)
' , nPar1
' , fSum
MsgBox nPar1
End Sub
Function fSum(nItem1 As Integer, nItem2 As Integer)
'
fSum = nItem1 + nItem2
' !
nItem1 = 10
End Function

VBA

71

, , :
Function fSum(nItem1 As Integer, nItem2 As Integer)

:
Function fSum(byVal nItem1 As Integer, nItem2 As Integer)

VBA, ,
, .
. ,
:
fSum 3, 2

. - , ,
:
nResult = fSum(3, 2)

VBA , .
.

3.8.5.
.
, , . . ?
:
(. . , , NewMacros) , (. . 1.4).
;
( . 5) Excel Word;
(AutoExec(), AutoNew() . .). .
, , Office 2003 .
( )

72

, | |
;
: ,
, . . Microsoft
.
. 4 5;
/m
, :
winword.exe /mMyMacros

, .
VBA ,
. ( ). ( ) (
), .
VBA
End Exit. :
Exit Sub
End Sub

.
:
End ,
. End ;
Exit
. ,
, , - (, ).

3.4:

:
1. NewMacros Normal.dot
fMultiply(), :

VBA

73

;
.
2. NewMacros Normal.dot
AutoNew() :
Public Sub AutoNew()
Dim nMult1 As Integer
Dim nMult2 As Integer
Dim nResult As Integer
nMult1 = CInt(InputBox(" : "))
nMult2 = CInt(InputBox(" : "))
nResult = 10
Selection.InsertAfter nResult
Selection.Collapse wdCollapseEnd
End Sub

3. AutoNew() , nMult1 nMult2 fMultiply()


nResult ( 10).
4. Word , .
5. AutoNew() ,
.

3.4
1. Word <Alt>+<F11>. Project
Explorer Normal | Modules
NewMacros.
2. NewMacros
fMultiply():
Public Function fMultiply(nM1 As Integer, nM2 As Integer)
fMultiply = nM1 * nM2
End Function

3. AutoNew() ( ):
Public Sub AutoNew()
Dim nMult1 As Integer
Dim nMult2 As Integer

74
Dim nResult As Integer
nMult1 = CInt(InputBox(" : "))
nMult2 = CInt(InputBox(" : "))
nResult = fMultiply(nMult1, nMult2)
Selection.InsertAfter nResult
Selection.Collapse wdCollapseEnd
End Sub

4. AutoNew(),
( Public Sub AutoNew() End Sub)
Comment Block Edit.

3.9. VBA
3.9.1.
VBA . VBA,
, Excel,
Word, Access , , AutoCAD. ,
.
,
,
VBA . ,
Visual Basic VBScript,

C++, Delphi, Java, JavaScript . .
VBA (. 3.2).
:
? , , . VBA
( , , , ).
: , .
.
, .

VBA

75

. 3.2.

3.9.2.

VBA
. ,
:

InputBox();
/ ,
;
/ /.
, 'C' ( Convert) .
: CBool(), CByte(), CCur(), CDate(),
CDbl(), CDec(), CInt(), CLng(), CSng(), CStr(), CVar(), CVDate(), CVErr().
, ,
, :

TypeName(),

76
nVar1 = CInt(InputBox(" "))
MsgBox TypeName(nVar1)

"Integer".
, .
Str()

. , CStr(), .

Val() "" .
( , ).
,
.

IsDate() ,
. IsArray(), IsEmpty(),
IsError(), IsMissing(), IsNull() IsObject(). True False
.
IsNumeric()

Hex() Oct() .

3.9.3.
. , .
Asc()
. , Asc("D") 68. , .
Chr(),

. , Excel A1
A20 A :
Dim n, nCharCode As Integer
n = 1
nCharCode = Asc("")
Do While n <= 20
ActiveWorkbook.ActiveSheet.Range("A" & n).Value = Chr(nCharCode)

VBA

77

n = n + 1
nCharCode = nCharCode + 1
Loop

AscB() AscW(). AscB() , AscW() Unicode.


Chr() . , Asc() (. ),
: .
, Word "" ( ).
, :
Selection.Text = """"

. :
Selection.Text = Chr(34) & "" & Chr(34)

ChrB() ChrW(). Asc().


InStrRev() .

. , 0. InStr() , InStrRev() .

InStr()

Left(), Right(), Mid()

, .
Len() ( ). , . .

UCase() . ,
(, , . .).
LCase()

RSet() ( ). , .

LSet()

LTrim(), RTrim(), Trim() ,


, .
Replace()

String()
. -

Space()

78

Len(). Spc(), . .
StrComp()

StrConv() ( Unicode , , . .).


StrReverse()

"" , -

.
Tab()

,
. ,
. , . vbTab.

3.9.4.

VBA . , ,
.
: VBA, , ,
Microsoft Office Excel. Excel

, VBA.
,
Excel.
, ( | ) , Excel ,
Analysis ToolPak VBA,
VBA ( Excel, ).
VBA . VBA.
Abs()


( , ). , Abs(3) Abs(3)
3. , , , .

VBA

79

. ,
.
Int(), Fix()

Round() - . Int()
, Fix() ,
Round() .
Round() , :
MsgBox Round(2.505, 2)

Format()
(. . 3.9.6):
MsgBox Format(2.505, "#,##0.00")
Rnd()

Randomize ( , , ).
Rnd() :
_ = Int( + (Rnd() * ))
MsgBox (Int(1 + (Rnd() * 100)))

Rnd()
Randomize .
Sgn()

. 1,
, 1, , 0, 0.

3.9.5.
.
VBA / .
Date(), Time(), Now()


, .
, , :
Date = #5/12/2004#
DateAdd() , , .
DateDiff()

( -

).
DatePart() ,
(, , ).

80

DateSerial() . DateValue(),
. ( ) TimeSerial() TimeValue().
Day() ( Year(), Month(), Weekday(), Hour(), Minute(), Second())
DatePart(), .
MonthName()

. . ,
.
Timer()

, .

/, Outlook. , / . . 13.

3.9.6.
Format() , Format...
(FormatNumber(), FormatCurrency(), FormatDateTime() . .) Format() :
Format(, "")

.
Format() ( , ):
Format(15/20, "Percent")
Format(Date, "Long Date")
Format(1, "On/Off")
Format(334.9, "###0.00")
Format(" ", ">" )

Format... , , .
,
.
DatePart(),
" " .

VBA

81

3.9.7.

VBA - , ,
. ,
(, Word) . . 5, ,
. 1015, Office.

VBA.
VBA MsgBox().
, :
MsgBox( [, ] [, _] [, _,
___])

MsgBox() :
(OK, Cancel, Abort, Retry,
Ignore, Yes, No);
Critical ( ), Exclamation
( ), Question (
), Information ( "I");
;
.
, , ( 7 ).
VBA. MsgBox() :
Dim nVar As Integer
nVar = MsgBox (" ?", vbInformation + vbOKCancel, _
" ")

nVar 1, OK, 2,
(Cancel).
(, ) ,
. Popup() Wscript.Shell.
Tools | References Windows Script Host
Object Model, :

82
Dim oShell As New WshShell
oShell.Popup "Test", 5

MsgBox().
, , 1.
InputBox(). :
Dim InputName
InputName = InputBox(" ")
MsgBox (" : " & InputName)

InputBox() , ,
, . ,
InputBox()
String, .
.
Beep:
Dim i
For i = 1 To 3
Beep
Next i

,
,
Office (Office Assistant). Internet Explorer.

3.9.8.

VBA , , If...Then...Else
Select Case. -
( , ),
.
, . .
Choose()

( ) . ,
.

VBA

83

, :
Choose(2, "", "", "")

"".
IIf() Immediate If, . . " If". If...Else,
. :
IIf(n > 10, " ", " ")
Switch() " = ",
, . :
Function Language (CityName As String)
Language = Switch(CityName = "", "", CityName = _
"", "", CityName = "", "")
End Function

3.9.9.
, Microsoft
Office . .
VBA .
Array()

Dim myArray As Variant


myArray = Array(10,20,30)
MsgBox A(2)
Filter() , .
LBound(), UBound()


( )
( ).

Join() , , .
, . , , Split(). ,
, , , , . .

84

3.9.10.
VBA
, ,
. . ,
( , VBA) , -, ,
(, Word
Word). -,
Windows Microsoft Scripting Runtime, ,
. VBA
. , ,
- (, Excel , ), . Microsoft
(www.microsoft.com/scripting).
, VBA.
CurDir()

, , .

Dir()

EOF()
True, .

Error()

. RaiseError() Err (. . 6, ).
FileAttr()

,
: , , , . .

FileDateTime()


. , .
FileLen()

FreeFile()

, .

GetAttr()
(, , . .).

VBA

85

Input() . ,
C:\text1.txt
:
Dim MyChar
' Open()
Open "c:\text1.txt" For Input As #1
Do While Not EOF(1)
' ,
'
MyChar = MyChar & Input(1, #1)
Loop
Close #1
'
MsgBox MyChar
'

InputB() ,
.
Loc() Location () , .
Seek(), , .
LOF()

length of file

.
Open

, VBA,
. "Open Statement". , , ( , ). ,

, :
Open ":\file1.txt" For Output Shared As #1

3.9.11. VBA
VBA,
.
DoEvents()

. - VBA , (, ). VBA .
( , -

86

. .)
, , , "" .
Environ()


( , , , SET).
, - . :
MsgBox Environ("TEMP")
GetAllSettings()

( )
, . SaveSetting() ,
DeleteSetting() . GetSetting() . ,
HKEY_CURRENT_USERS.
. Windows Script Host Object Model,
Windows 2000, XP
2003. WSHShell, RegRead(),
RegWrite() RegDelete().
Microsoft (www.microsoft.com/scripting).
Partition() , ,
( ).
.
QBColor()


16 RGB-,
VBA.
.

RGB()

. RGB, , : (Red), (Green) (Blue). 0 255. , ,


RGB(0, 255, 0).
Shell()

VBA
Program ID .

VBA

87

Windows API.

, , ,
WshShell WshExec Windows Script Host Object
Model ( , . .). Windows,
www.microsoft.com/scripting.
TypeName()

, . , -
.

VarType() , , .
.




VBA,
. VBA,
Microsoft Office,
.
- , . , Microsoft Office.

4.1.
,
. "" . "" . , , - .
( )
. Windows ""
DLL OCX ( , , EXE
TLB).
, (. . )
,
" ".
VBA ( instantiation, instance),

89

. .
, (
Microsoft Office).
, .

4.2.
VBA .
:
Dim oApp As Object
Set oApp = CreateObject("Word.Application")
MsgBox oApp.UserName

(late binding).
oApp , Word.Application.
, , Visual Basic , . , , ,
. (early binding):
Dim oApp As Word.Application
Set oApp = CreateObject("Word.Application")
MsgBox oApp.UserName

oApp Word.Application,
.
:
Dim oApp As New Word.Application
MsgBox oApp.UserName

New , WithEvents
(String, Integer . .), Set. , VBScript New ,
, CreateObject().

90

New , VBA .
,
:
Dim oApp As New Word.Application
oApp.Documents.Add
Dim oDoc As Word.Document
Set oDoc = oApp.Documents(1)
oDoc.SaveAs "C:\docvba1.doc"

Word.Application, Add() Documents , oDoc, SaveAs() .


:
Set _ = Nothing

:
Set oDoc = Nothing

,
, , ,
( , ). " ",
.
, .
Nothing. , . ,
Word,
, Quit(), .

4.3.
, , , .
, . - , .

91

.
:
.

:
oDoc.Activate

.
:
. 1 [, 2, ... , N]

. :
oDoc.SaveAs "C:\doc12.doc"

, .
:
= .(1 [, 2, ... , N])

:
Dim nCent
nCent = oApp.CentimetersToPoints(10)
MsgBox nCent

, , . . , :
= .()

4.4.
, . .
:
= .

:
sName = oApp.UserName

92

:
. =

:
oApp.ActivePrinter = "HP LaserJet 4"

:
(10 "HP LaserJet 4");
(10 + 5);
:
1. = 2.

- :
1. = 2.()

, .
, , (
) .

4.5.
WithEvents
, , . ,
, , .
Visual Basic. (,
Application).
WithEvents, , :
Public WithEvents App As Word.Application

.
Visual Basic App .
. 5,
:
, , . .
( ) -

93

, ( ) , . , , (, ).

4.6.
, , , . :
, , ?
Object Browser, , VBA. ,
<F2>
. "", , , , .
. , Object Browser, Tools | References
References Object Browser.
:
Object Browser - . , CommandButton MSForms (. . ), , .
, ,
Control
VBA;
Object Browser ,

. , , , ,
( ).
.

4.7.
, , , . , -

94

Excel , Excel, , ,
, . . . 1015
Microsoft Office: Word, Excel, Access, PowerPoint, Project,
Outlook. VBA
Office .
Windows
,
. , Windows Microsoft (
), .
MSDN (Microsoft
Developer Network, ).
www.microsoft.com/msdn.
, MSDN -
DVD.
, .
: Visual Basic Tools | References
.
:
Windows Script Host Object Model (wshom.exe) .
, , , , , . .
Windows 2000, XP, 2003 ( Windows 98 Second Edition Windows NT 4.0);
Microsoft Scripting Runtime (scrrun.dll) . ( )
, ,
, . . Windows Script Host Object Model;
Microsoft ADO ( , "msado")
.
. 9. Windows 2000, XP Windows 2003 Server (
);

95

Microsoft SQLDMO Object Library ( sqldmo.dll)


Microsoft SQL Server ( , . .).
, SQL Server
7.0, 2000 2005. SQL Server 2005
SMO (SQL Server Management Objects), RMO (Replication Management Objects) AMO (Analysis Management Objects);
Microsoft CDO ( 1.21, for NTS 1.2, for Windows 2000
1.0; olemsg.dll, cdonts.dll, cdosys.dll)
. , . .
Windows 2000, XP Windows 2003 Server. , Microsoft Office;
Microsoft WMI Scripting v1.1 (wbemdisp.tlb)
WMI (Windows Management
Instrumentarium). :
( , ) , , . . . , -
,
, . . ( WMI) Windows 2000, XP Windows 2003 Server. ,
WMI,
(, ), :
www.askit.ru/progr_admin/progr_admin_m14.htm;
Active Directory Scripting Interface (adsldp.dll, wldap32.dll, adsnt.dll,
adsnds.dll, adsnw.dll) Active Directory, NT, NetWare, . . ,
, , . .
Windows 2000, XP Windows 2003 Server (
, );
Windows Explorer.
,
;

96

Internet Explorer
.
Web- ( , ""), -, - . .
HTML, Microsoft
Office ( . 5).
, , , .
,
, (, ). " ", , .

4:

Windows Script Host VBA
:
Word (, ). <Alt>+<F11>, Visual Basic, Project Explorer ( Project (1))
Insert | Module. . Insert | Procedure
WSH().
:
1. Tools | References
Windows Script Host Object Model.
2. WSH() WScript.Network
WScript.Shell .
3. WSH() , :
Word
ComputerName, UserName UserDomain
WScript.Network;

97

Word :
ThisDocument.Activate
Selection.TypeText Text:=(_)

Run() WScript.Shell "calc";


Environment WScript.Shell
;
Word
.

,
, Variant.

4
WSH() :
Public Sub WSH()
Dim oNetwork As WshNetwork
Dim oShell As WshShell
Dim sComputer As String
Dim sDomain As String
Dim sUser As String
Dim oColl As Variant
Dim sEnv As Variant
'
Set oNetwork = CreateObject("WScript.Network")
Set oShell = CreateObject("Wscript.Shell")
' Wscript.Network
sComputer = oNetwork.ComputerName
sDomain = oNetwork.UserDomain
sUser = oNetwork.UserName
ThisDocument.Activate
Selection.TypeText Text:=(sComputer & vbCrLf & sDomain & vbCrLf & _
sUser & vbCrLf & vbCrLf)

98
' Run Wscript.Shell
oShell.Run "Calc"
'
Set oColl = oShell.Environment
'
For Each sEnv In oColl
Selection.TypeText Text:=(sEnv & vbCrLf)
Next
'
Set oNetwork = Nothing
Set oShell = Nothing
End Sub

,

5.1.
( MsgBox() InputBox())
. , ,
. ,
VBA.
VBA. ,
(
), . , ,
.
VBA? .
- (, , . .), , ,
, ,
, . .

5.2.

: Visual Basic
(. . )

100

Project Explorer Insert | UserForm. (Form designer), ( UserForm1)


Toolbox (. 5.1).

. 5.1.

Properties (
<F4>), . ( Click) <F7>,
<Shift>+<F7>.
,

, .
( ShowModal ) .
Name

. , , .
( Visual
Basic). ,
(UserForm1), - ,

101

( ).
Caption ( ). ,
(, " ").
Enabled False,
. , , - .
ShowModal

True ( ), ,
( "" ).

, .
.
( Visual Basic)
<F5>. ,
, .
Show():
UserForm1.Show

, , ( Load).
, :
, ;
( AutoExec Word);
,
(, CommandButton) (
);
Open Word Excel, .
, , .
:
( Hide()), :
UserForm1.Hide

102

, . Show() ,
"", , ,
,
. ;
,
Unload:
Unload UserForm1


(Copy(), Cut(), Paste()),
(PrintForm(), Repaint(), Scroll()).
VBA . (event) , . ,
, , ,
. . VBA ,
, (eventdriven).
.
.
Initialize (
). , ,
,
. .

( ) DblClick
. . ( CommandButton).
Click

Error

,
. . 6, .
Terminate


(, Unload). , , . . (, End),
.

103

,
, ( ) ( ).

, Initialize. , .
, :
, Microsoft Access, ,
Office, .
;
. ,
<Ctrl>+<P> ( );

( ), :
(
Show() Hide(), )
.
Multipage.

5.3.
5.3.1.
,
VBA ( )
. VBA
(CommandButton, CheckBox,
OptionButton), ( ,
, , Microsoft Web Browser, Internet
Explorer, Calendar . .). , ( ,
, . .).
Toolbox.
Toolbox ,

104

, Toolbox,
, .
( Add() Controls),

, .

5.3.2. Label
. (Label) , - (. 5.2).

. 5.2. Label

.
Label , , , , . . , .
Label Caption, , .

.
, (Click, Error . .), : , .

5.3.3. TextBox
(TextBox)
(. 5.3).

105

. 5.3. ( TextBox)

:
- , (, , . .);
( , Excel . .);

, (
).
.
Value ( Text, )
, . , , .
AutoSize

, . , . .
.

ControlSource

.
, , Excel, Recordset . .

, ControlSource.
ControlTipText

, , . ( ).

Enabled False, ( , -

106

, ). ,
, - ( ).
Locked

, , .
, . .
MaxLength , .
AutoTab .
MultiLine , . , ,
InputBox().
PasswordChar , ""
. , , .
ScrollBars , ( ). ,
.
WordWrap ,
MultiLine True.
.


, .
Change (. .
).

(, ,
. .)

5.3.4. ComboBox
(ComboBox) .
""
, ( ).
ComboBox . 5.4.

107

. 5.4. ( ComboBox)

ComboBox :

4- .
, (OptionButton), ,
,
;

( , Excel . .).
, AddItem().
Initialize . :
Private Sub UserForm_Initialize()
ComboBox1.AddItem "-"
ComboBox1.AddItem " "
ComboBox1.AddItem ""
ComboBox1.AddItem " "
End Sub

varIndex () , ListCount
ComboBox .
.
ColumnCount, ColumnWidth, BoundColumn, ColumnHeads, RowSource ,
.
,

108

(
).
MatchEntry

, .
, ,
.

MatchRequired

,
, . False, . . .

Value ( Text) .

(AutoSize, Enabled, Locked, ControlText, ControlTipText,


, TextBox.

MaxLength)

Change, ,
TextBox. , ListBox
( ,
MultiSelect ComboBox ) . .

5.3.5. ListBox
ListBox ,
:
. , , ;
.
. 5.5.
:
, ComboBox, .
ListBox :

ComboBox ( , , );
, (
ListBox ).

109

. 5.5. ( ListBox)

, ListBox , ComboBox.
MultiSelect, . .

5.3.6. CheckBox
ToggleButton
(CheckBox) ( "" "") (ToggleButton) ( ). . 5.6.

. 5.6. ( CheckBox) (ToggleButton)

CheckBox .
Caption

, ,
.

110

TripleState False ( ),
: .
TripleState True,
Null, "" . , , ,
, .
Value

. True (
), False () Null "" (
TripleState True).
CheckBox Change.
,
"" (. 5.6), .
( , TripleState) ,
CheckBox. .
. ToggleButton - .
ToggleButton

5.3.7. OptionButton Frame


CheckBox ,
(OptionButton)
"/" (. 5.7).

. 5.7. (2 OptionButton) ( Frame)

, OptionButton, : ( RadioButton).

111

.
Caption

.
Value ( True
False).
Change.
, .
, . (, //, , . .). .

. (
), . , Frame.
Frame , (. 5.7).
,
,
, ,
. , BorderStyle 1 Caption.

5.3.8. CommandButton
CommandButton ()
(. 5.8).

. 5.8. ( CommandButton)

, , : OK
(Cancel). OK ,

112

, . , .
.
Cancel

True, <Esc>. ,
"", "", " ". , <Esc>, .
Click, :
Private Sub CommandButton1_Click()
Unload Me
End Sub
Me

, ( ).
.
Caption

, .

Default True,
<Enter>, ( ).
, , ( , , . .).
Picture

,
().

TakeFocusOnClick

,
. True.

, , Click. , , .

5.3.9. ScrollBar SpinButton


(ScrollBars) ,
.
ScrollBar
( "") -
(. 5.9).
, : , ,
, . .

113

. 5.9. (ScrollBar) (SpinButton)

ScrollBar Change. .
Max Min , .
32 767 +32 767.

.

SmallChange ,
(
).
LargeChange

Orientation

( ). 1,
. . ( ). .
ProportionalThumb

: ( ) .

Value

. ,
.
, .
, , :

114
Private Sub ScrollBar1_Change()
Label1.Caption = ScrollBar1.Value
End Sub


.
Change
.
(SpinButton) ,
(. 5.9). SpinButton
, (, ). , SpinButton, ScrollBar.

5.3.10. TabStrip MultiPage


(TabStrip) (MultiPage)
,
.
(),
.
, TabStrip , MultiPage .
(,
Word , | ). MultiPage
. 5.10.

. 5.10. ( MultiPage)

TabStrip . ,
(
).

115

.
.
MultiRow

, .
TabOrientation ,
( ).
Value

, (
0).

Change (. .
). , ,
.

5.3.11. Image
, (Image) .
, ( ). , Image:
Picture
( );
Picture Label
CommandButton.
;
.
.
Picture

PictureAlignment
. .
PictureSizeMode


, .

PictureTiling

, ,
("").

Image Click.

116

5.3.12.

, ToolBox .
VBA .
, Windows, ( ).
,
ToolBox,
Additional Controls, . ,
,
( Office) .
Internet Explorer, Acrobat Reader, , - . . ,
Microsoft Web Browser ( Windows
- (Microsoft)), Internet
Explorer, :
Toolbox
Additional Controls;
Microsoft Web Browser ( - (Microsoft));
,
.
. WebBrowser1.
, . , ,
Internet Explorer ,
Initialize .
:
Private Sub UserForm_Initialize()
WebBrowser1.Navigate "http://www.AskIt.ru"
End Sub

117

Web- (, HTML). Internet Explorer Windows


.
MSDN.
, Calendar () (. 5.11).

-, Calendar Control 8.0.
.

. 5.11. Calendar , ,
Calendar

Value, . . ,
.
.
Excel ToolBox RefEdit ( Additional Controls
RefEdit.Ctrl). .
, , "",
Excel. ,
, RefEdit
. , ,
. Value.

Access. Access,
. 12.

118

5:

:
1. Excel Prikaz.xls. A1 A5 , . 5.12.
,

Word.

. 5.12. Excel

2. Visual Basic Project Explorer


View Code.
3. :
' UF1
Private Sub Workbook_Open()
UF1.Show
End Sub
' , Word
Public Sub DocWrite(sPovod As String, sFio As String, bFlagPremia As
Boolean, bFlagGramota As Boolean, nSummaPremii As Long, sOtvIsp As
String)
Dim oWord As Word.Application
Dim oDoc As Word.Document
Set oWord = CreateObject("Word.Application")

,
Set oDoc = oWord.Documents.Add()
oWord.Visible = True
oDoc.Activate
With oWord.Selection
.TypeText ""
.Style = " 1"
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.TypeText vbCrLf
.Style = ""
.TypeText vbCrLf
.TypeText ".-" & Space(90) & Date
.TypeText vbCrLf
.TypeText vbCrLf
.TypeText " " & sPovod & _
" " & sFio & ":"
.TypeText vbCrLf
If bFlagPremia Then
.TypeText vbTab & "- " & _
nSummaPremii & " "
End If
If bFlagGramota Then
.TypeText vbCrLf
.TypeText vbTab & "- ."
Else
.TypeText "."
End If
.TypeText vbCrLf
.TypeText vbCrLf
.TypeText vbCrLf
.TypeText vbCrLf
.TypeText " " & vbTab & vbTab & _
vbTab & " . ."
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.TypeParagraph
.TypeText vbCrLf
.TypeText vbCrLf
.ParagraphFormat.Alignment = wdAlignParagraphLeft
.TypeText Text:=(". " & sOtvIsp)
.TypeParagraph
End With
End Sub

119

120

4. Project Explorer
Prikaz.xls Insert | UserForm.
<F4>. Properties Name UF1.
Toolbox CommandButton1.
Caption " " ( ) , ,
. 5.13.

. 5.13.

5. CommandButton1 , View Code Click :


Private
Dim
Dim
Dim
Dim
Dim
Dim

Sub CommandButton1_Click()
sPovod As String
sFio As String
bFlagPremia As Boolean
bFlagGramota As Boolean
nSummaPremii As Long
sOtvIsp As String

'
sPovod = " "
sFio = " "

121

bFlagPremia = True
bFlagGramota = True
nSummaPremii = 100000
sOtvIsp = " . ."
'
Call .DocWrite(sPovod, sFio, bFlagPremia, bFlagGramota, _
nSummaPremii, sOtvIsp)
End Sub

6. , :
Word .
:
, . :
1. sPovod : " ", "
" ,
. ( , ). " ".
2. sFio
. A Excel. "
".
.

3. bFlagPremia bFlagGramota
"" "".
.
, " , !" .
4.
nSummaPremii

122

0 . 100 000 ., .
"" , .
(
) 100 .
100 .
5. . <Esc>.
6. "
".
, , ,
. 5.14.

. 5.14.

5
1 ( ):
1. Project Explorer UF1.
ToolBox Label . Label1 Properties. Caption " :"
Font .

123

2. ToolBox OptionButton
.
.
3. .
Name optOsvoenie, Caption " ".
Name optVnedrenie Caption "
", optDrugoe ":" .
4. ToolBox TextBox
. Name txtDrugoe.
5. View Code.
Initialize UserForm
:
optOsvoenie.Value = True
txtDrugoe.Visible = False

6. Change optDrugoe :
If optDrugoe.Value = True Then
txtDrugoe.Visible = True
Else
txtDrugoe.Visible = False
End If

7. Click CommandButton1 :
sPovod = " "

:
If optOsvoenie.Value = True Then sPovod = _
" "
If optVnedrenie.Value = True Then sPovod = _
" "
If optDrugoe.Value = True Then sPovod = txtDrugoe.Value

8. , ,
.
2 ( ):
1. Label ":" .

124

2. Toolbox ComboBox . ComboBox


cbFIO.
3. Initialize UserForm
:
Dim
Dim
Set
For

oColumn As Range
oCell As Range
oColumn = Columns("A")
Each oCell In oColumn.Cells
If oCell.Value <> "" Then
cbFIO.AddItem oCell.Value
End If
Next
cbFIO.ListIndex = 0

4. Click CommandButton1 :
sFio = " "

:
sFio = cbFIO.Value

5. , .
3 ( ):
1. ToolBox
CheckBox. Name
chPremia Caption "",
chGramota " " .
2. Initialize UserForm :
chPremia.Value = True
chGramota.Value = True

3. Click CommandButton1 :
bFlagPremia = True
bFlagGramota = True

:
bFlagPremia = chPremia.Value
bFlagGramota = chGramota.Value

125

If bFlagPremia = False And bFlagGramota = False Then


MsgBox " , !"
Exit Sub
End If

4. , .
4 ( ):
1. Label
" :". Name lblSum.
2. Name
txtSum.
3. ScrollBar :
Name sbSum;
Min 0;
Max 100 000;
SmallChange 100.
4. Change sbSum :
txtSum.Value = sbSum.Value

5. Change txtSum :
sbSum.Value = CLng(txtSum.Value)

, . 100 000, .
, . 6.

6. Initialize UserForm :
sbSum.Value = 100
txtSum.Value = 100

7. Change chPremia
:
If chPremia.Value = False Then
lblSum.Visible = False

126
txtSum.Visible = False
sbSum.Visible = False
Else
lblSum.Visible = True
txtSum.Visible = True
sbSum.Visible = True
End If

8. Click CommandButton1 :
nSummaPremii = 100000

:
nSummaPremii = sbSum.Value

9. , .
5 ( ):
1. :
Name btnEscape;
Caption "";
Cancel True.
2. Click
Unload Me

6 ( ):
1. Properties.
2. Caption "
".
3. ,
.



6.1.
, , ,
,
.
( ).
:
( , . .).
.
"" VBA
.
. VBA ,
. VBA;
. , . . (. . 6.2);
(run-time error). , ,
( , ,
. .). ,
, . ,

128


.
" " ( , ), .
: , ,
, "".
( ),
,
.

6.2. .
Immediate, Locals Watch
6.2.1.
. , .
, , , . :
;
, , ,
;
, ,
;
, . ,
, ,
;

;
, , ,
, . .;
Office ( );

129

, .
, ,
, .
"" .
, , . ,
. , .
,
.

6.2.2.

, , , ,
. .
:

( Debug | Step Into <F8>). ;
(breakpoint). ,
Debug Toggle
Breakpoint ( <F9>).
,
.
.
.
;
, .
, Stop.
,
:
n1 = 10
n2 = 5
Stop
nResult = n1/n2

(, ), Break -

130

Standard, Run | Break <Ctrl>+<Break>;


( Watches).
. 6.2.6.

, , ,
(. 6.1).
, .

. 6.1.

6.2.3.
, - . :
. Debug | Step Into <F8>. -

131

( ),
. , , ""
(Step Into) ;
- ,
,
.
Debug | Step Over ( <Shift>+<F8>);
- , , Debug | Step Out ( <Ctrl>+<Shift>+<F8>);
, (,
),

Run to Cursor (
Debug <Ctrl>+<F8>).
;
"" - , (. . ), Debug | Set Next Statement (
<Ctrl>+<F9>), (
) . Office
, .
Comment Block Edit ( );

(, )
, Show Next Statement;
, <F5>
Run | Continue ( Run). Reset
<Alt>+<F4>. ,
Standard.
,
.
Immediate, Locals Watch (
), -

132

. , . 6.2 (
Auto Data Tips Options, Tools | Options).

. 6.2.

, Edit
Quick Info ( <Ctrl>+<I>).
.
, ( ) ,
,
Set Next Statement (<Ctrl>+<F9>)
.
. , , ,
, ,
Immediate, Locals
Watch.

6.2.4. Immediate
. Immediate (immediate) ,
View <Ctrl>+<G>. :
. , Immediate:
Print nResult
Print oDoc.FullName

:
?nResult
?oDoc.FullName

133

Print() Debug.
Immediate
:
Debug.Print nResult

MsgBox() ,
(. .
) Debug ( Assert() ).
Immediate , ;
, . Microsoft
(,
) ;
, :
Print 25*115

Immediate . 6.3.

. 6.3. Immediate

Immediate , ,
Immediate <Ctrl> ( ).

134

6.2.5. Locals
, , , . /
Immediate . Locals ( View | Locals Window).
, ( . 6.4).

. 6.4. Locals

,
Locals, Value .
. ,
( ), (#).
Locals .

6.2.6. Watches
Watches ( , , View) ,
"" .

135

,
, . . , , nResult = 10, , :
InStr(oDoc.Fullname, "Document") <> 0

:
,
Add Watch. Add Watch ;
Add Watch Debug;
Quick Watch Debug.
Watch
, .
""
.
;
Watches.
Add Watch. (
) , True False,
If...Else, " " ( ), : . :
Watch Expression (
Value Watches);
Break When Value Is True ,
"" ( True);
Break When Value Changes , .
Watches
, , ,
, .

6.3.

, :

136

, ,
, . . , , . VBA
,
.
:
1. ( , . .) :
On Error GoTo __

:
Dim a As Integer, b As Integer, c As Integer
On Error GoTo ErrorHandlerDivision
c = a / b

2. :
ErrorHandlerDivision:
MsgBox " "

3.
, , Exit Sub ( )
Exit Function ( ). -
:
Private Sub UserForm_Click()
Dim a As Integer, b As Integer, c As Integer
On Error GoTo ErrorHandlerDivision
c = a / b
Exit Sub
ErrorHandlerDivision:
MsgBox " "
End Sub

, ,
( ),
.

137

4.
: ,
, . :
, (
).
Resume;
, . Resume Next;
.
Resume . , GoTo.
, :
( ),
:
On Error GoTo 0

On Error Resume Next.


.
,
Select Case
( Err), .
Err.
.
Number . , , . 0, .
Description .
(
- ). .
Clear() Err . On Error GoTo 0.
Raise()

, .
, .

138

, , . (, ), . ,
, ( ).

6:

:
1. Excel C:\ErrorHandling.xls.
2. A1 " :".
3.
.
4.
( )
Excel .
.
5. .
. , , ,
. 6.5.
6.
.
Visual Basic Click .
:
Private Sub CommandButton1_Click()
Dim nNum1 As Integer
Dim nNum2 As Integer
Dim nResult As Integer
nNum1 = InputBox(" ")
nNum2 = InputBox(" ")
nResult = nNum1 / nNum2
Range("B1").Value = nResult
End Sub

139

7. Excel, (

) .
, , B2.

. 6.5.

:
,
(, , 0).

Click .
.

6
.
.
, , :
Option Explicit
Private Sub CommandButton1_Click()
Call subPrepare
End Sub

140
Public Sub subPrepare()
Dim nReturnCode As Integer
Dim nAnswer As Integer
nReturnCode = fDiv()
Select Case nReturnCode
Case 1
MsgBox (" !")
nAnswer = MsgBox("?", vbYesNo)
If nAnswer = vbYes Then
Call subPrepare
Else
Application.Quit
End If
Case 2
MsgBox (" !")
nAnswer = MsgBox("?", vbYesNo)
If nAnswer = vbYes Then
Call subPrepare
Else
Application.Quit
End If
Case 3
MsgBox (" ")
nAnswer = MsgBox("?", vbYesNo)
If nAnswer = vbYes Then
Call subPrepare
Else
Application.Quit
End If
End Select
End Sub
Function fDiv()
On Error Resume Next
Dim nNum1 As Integer
Dim nNum2 As Integer
Dim nResult As Integer
nNum1 = InputBox(" ")
nNum2 = InputBox(" ")
nResult = CInt(nNum1) / CInt(nNum2)


Select Case Err.Number
Case 0
Range("B1").Value = nResult
fDiv = 0
Case 11
fDiv = 1
Case 13
fDiv = 2
Case Else
fDiv = 3
End Select
End Function

:
Private
Dim
Dim
Dim
Dim

Sub CommandButton1_Click()
nNum1 As Variant
nNum2 As Variant
nResult As Integer
nError As Integer

Do
nNum1 = InputBox(" :")
On Error Resume Next
nError = CInt(nNum1)
If Err.Number = 13 Then
MsgBox (" ")
nNum1 = ""
End If
On Error GoTo 0
Loop While (nNum1 = "")
Do
nNum2 = InputBox(" :")
On Error Resume Next
nError = CInt(nNum2)
If Err.Number = 13 Then
MsgBox (" ")
nNum2 = ""
ElseIf nNum2 = 0 Then
MsgBox (" !")
nNum2 = ""
End If
On Error GoTo 0
Loop While (nNum2 = "")

141

142
nResult = nNum1 / nNum2
Range("B1").Value = nResult
End Sub

:
Private
Dim
Dim
Dim

Sub CommandButton1_Click()
nNum1 As Variant
nNum2 As Variant
nResult As Integer

Do
nNum1 = InputBox(" :")
If IsNumeric(nNum1 & "") Then Exit Do
MsgBox " "
Loop
Do
nNum2 = InputBox(" :")
If IsNumeric(nNum2 & "") Then
If Int(nNum2) <> 0 Then Exit Do
MsgBox " !"
Else
MsgBox " "
End If
Loop
nResult = nNum1 / nNum2
Range("B1").Value = nResult
End Sub


- , Office MsgBox(). Office , ,
. ,
(. . , - ). Assistant
Balloon. Assistant , Balloon ,
(. 7.1).
Assistant VBA
:
Assistant.On = True
Assistant.Visible = True
Assistant.Animation = msoAnimationThinking

. 7.1. ( Rocky)

144

( , ), , "" (. .
).
Assistant.
Animation ""
(, , , - . .).
, .
- , .
FeatureTips , ( Office) .
FileName .
Rocky. ,
Office, ,
(
acs). , , :
Assistant.FileName = "Offcat.acs"
GuessHelp
, , ,
.
KeyboardShortcutTips

, .

Left

""
.

MoveWhenInTheWay ,
- , .
NewBalloon
Balloon (. .


"",
). , "" :
Dim Bal1
Set Bal1 = Assistant.NewBalloon

Balloon , Show():
Bal1.Show

145

, "" , :
Assistant.NewBalloon.Heading = " ?"
On

, , , , , .
SearchWhenProgramming ,
VBA.
Sounds

TipOfDay - Office.
Top .
Visible

.

(Help()),
(StartWizard()), (Move()) . .
, , Balloon, . . . , .
.
BalloonType , .
, ,
.
Button

Callback

, .

Checkboxes

Heading , ,
.
Icon

, .

Labels

Mode

.
:

msoModeModal ( ) , ;

146

msoModeModeless , ;
msoModeAutoDown
, .
Text , , . ,
.

Button , , , ,
. :
intButton = Bal1.Show()

:
Select Case Bal1.Show()
...

Balloon Close().
.
, ,
Microsoft Office, .
, . ,
www.agentry.net.



VBA , . CommandBars,
Application (
). CommandBars ,
, CommandBar (
, ), , , CommandBarControls,
, . :
CommandBarButton

,
;

CommandBarComboBox

(
, , );

CommandBarPopup

.

:
Dim CBar1 As CommandBar
Set CBar1 = CommandBars.Add("", msoBarTop)
CBar1.Enabled = True
CBar1.Visible = True

(. 8.1),
, , | ,
: .
,
CommandBarControl ( , )
CommandBarControls .

148

. 8.1.

Add() CommandBars,
.
:
Set CBar1 = CommandBars.Add("", msoBarTop)

("") ( ).
(msoBarTop) (msoBarTop,
msoBarBottom, msoBarLeft, msoBarRight), , (msoBarFloating), ,
, (msoBarPopup).
Visible .
, .
CommandBar.
BuiltIn

, /
(. . Office). .
,
, , , .
Context

, ( Normal.dot, . .).

.
Controls
CommandBarControls, , ,
.
Enabled

Height, Left, Top Width , .

149

Index, Name NameLocal CommandBars. Name ,


NameLocal , , Index .

Office :
Dim cBar As CommandBar
For Each cBar In CommandBars
Debug.Print cBar.Index & vbTab & cBar.Name
Next

Office,
CommandBars 41.
Protection

Type , . ,
( , ,
).
.
Visible

, . False, . . .

,
. ,
:
Dim But1 As CommandBarControl
Set But1 = CBar1.Controls.Add(msoControlButton)
But1.Caption = " 1"

.
,
, 1 (. 8.2).
,
( ) Add() Controls
CommandBar ( CBar1).
, .
Application

. .).

(Word, Excel

150

. 8.2. 1

Count

,
.
Item () CommandBarControl .
Add()

( Delete() ).
Add() Controls. ,
. Type . :
msoControlButton
msoControlEdit

(. . );

msoControlDropdown

msoControlComboBox

msoControlPopup

, (. 8.3), Add():
Dim But1 As CommandBarControl
Set But1 = CBar1.Controls.Add(msoControlPopup)
But1.Caption = " 1"

Add() Id. . , ,
4,
, 5.

151

1, , . ,
. , Id (, Locals).

. 8.3.


, , .
, / .
. ,
, , (), , , .
CommandBarButton .
Caption .
, .
Enabled , . .

( ) ( ). , 4 . Word Excel
,
. ,
, . , FaceId, 1 .
FaceId

152
Id

, .
, Id
1.

Index

Controls.
.

Mask


. ,
, .

OnAction

.
, ( , ,
). (COM Add In). :

But1.OnAction = "MySub"
Parameter
. String.
Picture

() . , FaceId.
, , Visual Studio, .
ShortcutText

,
.

State

(, ).

Style

, . , : ,
, .

ToolTip .
"" Caption.
Type

( ).

Visible

, .

Delete()

Execute() ,
OnAction;
Reset()
.

153

CommandBarButton Click.
, , OnAction.
, .
.
, - .

Controls, . ,
Controls CommandBar,
CommandBarPopup, . . . :
' CommandBar
Dim CBar1 As CommandBar
Set CBar1 = CommandBars.Add("", msoBarTop)
CBar1.Enabled = True
CBar1.Visible = True
Dim Menu1 As CommandBarPopup
Dim SubMenu1 As CommandBarPopup
Dim SubMenu1Item As CommandBarButton
'
Set Menu1 = CBar1.Controls.Add(msoControlPopup)
Menu1.Caption = " 1"
'
Set SubMenu1 = Menu1.Controls.Add(msoControlPopup)
SubMenu1.Caption = " 1"
' Proc1
Set SubMenu1Item = SubMenu1.Controls.Add(msoControlButton)
SubMenu1Item.FaceId = 5
SubMenu1Item.Caption = " "
SubMenu1Item.OnAction = "Proc1"

, . 8.4.
, , . ,
For Each Name.
( VBA shortcut menus) , . :

154

Set CBar1 = CommandBars.Add(" ", msoBarPopup, , _


True)
Set MenuItem1 = CBar1.Controls.Add
MenuItem1.FaceId = 3
MenuItem1.Caption = " 1"
Set MenuItem2 = CBar1.Controls.Add
MenuItem2.FaceId = 5
MenuItem2.Caption = " 2"

. 8.4.

, .
, :
ShowPopup():
CBar1.ShowPopup

, ( ). , ,
, . ,
Excel BeforeRightClick, Word
.
.

8:
,

:
1. Word
: .
, , , . 8.5.

155

. 8.5. Word

, .
2. , , . 8.6.

. 8.6.

, (. 8.7)

. 8.7.

8
, , , ( -

156

ShowNewToolbar()).
Word,
Normal.dot.
Public Sub ShowNewToolbar()
' , Assistant
' ,
Dim cBar As CommandBar
For Each cBar In CommandBars
If cBar.Name = "Assistant" Then
cBar.Visible = True
Exit Sub
End If
Next
'
Dim CBar1 As CommandBar
Set CBar1 = CommandBars.Add("Assistant", msoBarTop)
CBar1.Enabled = True
CBar1.Visible = True
'
Dim But1 As CommandBarControl
Set But1 = CBar1.Controls.Add(msoControlButton)
But1.Caption = " "
But1.FaceId = 52
But1.OnAction = "ShowAssistant"
'
Dim But2 As CommandBarControl
Set But2 = CBar1.Controls.Add(msoControlButton)
But2.Caption = " "
But2.FaceId = 103
But2.OnAction = "DisableAssistant"
End Sub
Public Sub ShowAssistant()
', " "
'
Assistant.On = True
Assistant.Visible = True
'
',
Dim cBarCont As CommandBarControl


For Each cBarCont In CommandBars(41).Controls
If cBarCont.Caption = " " Then
Exit Sub
End If
Next
'
Dim CBar1 As CommandBar
Set CBar1 = CommandBars(41)
CBar1.Enabled = True
CBar1.Visible = True
Dim Menu1 As CommandBarPopup
Dim SubMenu1 As CommandBarPopup
Dim SubMenu1Item As CommandBarButton
'
Set Menu1 = CBar1.Controls.Add(msoControlPopup)
Menu1.Caption = " "
'
Set SubMenu1 = Menu1.Controls.Add(msoControlPopup)
SubMenu1.Caption = ""
'
' TextToAssistant
Set SubMenu1Item = SubMenu1.Controls.Add(msoControlButton)
SubMenu1Item.FaceId = 5
SubMenu1Item.Caption = " "
SubMenu1Item.OnAction = "TextToAssistant"
End Sub
Public Sub DisableAssistant()
',
' " "
Assistant.On = False
Dim cBarCont As CommandBarControl
For Each cBarCont In CommandBars(41).Controls
If cBarCont.Caption = " " Then
cBarCont.Delete
Exit Sub
End If
Next
End Sub

157

158

Public Sub TextToAssistant()


',
Dim oBal1 As Balloon
Set oBal1 = Assistant.NewBalloon
oBal1.Text = Selection.Text
oBal1.Show
End Sub



ADO
9.1.
(, VBA) , . , , ,
,
. ( , , . .).
Office ,
.
Word
, Excel ,
Access (

- , SQL Server
Oracle).
Office
. , (
Excel, Word), - . , ,
,
, .
, .

160

, .
.
.
, Office ( )
: -, Microsoft SQL
Server, Oracle, IBM DB2, , Access, FoxPro, DBase,
Paradox, , (, Excel
).

9.2. ADO
ADO ActiveX Data Objects , ActiveX (COM), .
, Office DAO RDO,
. ADO ADO.NET,
ADO
.NET Framework. , ADO.NET:
.NET Framework ( );
ADO.NET Visual Basic
, Visual Studio;
.
ADO.NET .
ADO , , OLE DB ODBC. ADO COM, COM (VC++, Visual Basic, Delphi, VBA,
VBScript, JScript, ActivePerl . .).
, MDAC (Microsoft Data Access
Components, Microsoft).
Windows 2000, XP, 2003 (
). MDAC
Web- Microsoft (www.microsoft.com/download).

ADO

161

MDAC
.
ADO Microsoft Access.
Microsoft Access, ,
( <Alt>+<F11>)
<F1>.
ADO. ADO Programmer's Guide ( , ), ADO Programmer's Reference (
ADO, , ) (. 9.1).

. 9.1. ADO Microsoft Access

ADO . .
Connection
. , ,
Errors.
Command

, (
, , , . .). SQL-,
Command, , SQL. Command
Parameters , .
Recordset

, .

162

Fields,


(, , . .), .

Properties, ,
.
. , , Recordset Connection.
ADO,
. Tools References Microsoft
ActiveX Data Objects ( , ,
). MDAC 2.8.
, , 2.1,
Windows, Windows 2000. ,
VBA , , - .

9.3. Connection Errors


Connection . ,
Northwind SQL Server
LONDON, :
Dim cn As New ADODB.Connection
cn.ConnectionString = "Provider=SQLOLEDB.1;Integrated
Security=SSPI;Initial Catalog=Northwind;Data Source=LONDON"
cn.Open

, ,
, . :
ConnectionString ?
.
.
:
1. (, ).

Windows New | Text Document . 9.2.
.

ADO

163

. 9.2. Windows Explorer

2. , udl ( User
Data Link ). , (. 9.3).

. 9.3. 1.udl

, , , txt, udl. Windows Explorer Tools Folder Options,


Folder Options View Hide file

164

extensions for known file types (


). , , udl.
3. , UDL- ,
. Data Link Properties .
4. Provider (, SQL Server Microsoft OLE DB Provider
for SQL Server, Oracle Microsoft OLE DB
Provider for Oracle, Access Microsoft JET 4.0
OLE DB Provider). Excel
. 9.4.
5. Connection.
-. , SQL Server
, . 9.4, Access . 9.5.

. 9.4. SQL Server

, , . , -

ADO

165

, Test Connection, . ,
. OK, .

. 9.5. Access

6. ,
UDL-,
Open With | Choose Program Notepad
() OK. . Format Word wrap (. 9.6).

, , .

7. ConnectionString .

166

. 9.6.

, (connection string)
. "=", (
). .
Provider .
(SQL Server, Access, Oracle) .
OLE DB. ODBC.
, (,
OLE DB ). ODBC Excel.

, Provider .
Connection.
Integrated Security , SQL Server
Windows. SQL Server,
, : User ID
Password . ,
.
Data Source

. , SQL Server.
Oracle Microsoft Access,
, .

Initial atalog
Northwind.

UDL, .
. , ,
,

ADO

167

UDL- ( Test
Connection).
, ,
: Connection,
ConnectionString Open(). .
Provider

,
. ConnectionString,
. Provider :
"Microsoft.Jet.OLEDB.4.0" Access;
"SQLOLEDB.1" SQL Server ( );
"MSDAORA.1" Oracle;
"ADsDSOObject"
Windows.
ConnectionString Connection. . ,
.
Open()

.
Connection, .
Close()

. ,
.
, :
cn.Close
Set cn = Nothing

:
Set cn = Nothing

.
Connection ,
(
Microsoft). , , Errors,
Error . ( , -

168

, . .), .
:
Dim cn As ADODB.Connection
Set cn = CreateObject("ADODB.Connection")
cn.Provider = "SQLOLEDB"
cn.ConnectionString = "User ID=SA;Password=password;" _
& "Data Source = LONDON1;Initial Catalog = Northwind"
On Error GoTo CnErrorHandler
cn.Open
Exit Sub
CnErrorHandler:
For Each ADOErr In cn.Errors
Debug.Print ADOErr.Number
Debug.Print ADOErr.Description
Next

.
, ,
ADOError ( ). .
Description

.
.

Number

. Microsoft (www.microsoft.com/support) .

Source . ,
Errors .
SQLState NativeError , SQL- .

9.4. Excel

Excel . , Excel (. . 11), ADO :
, , . ADO ;

ADO

169

Excel Excel,
ADO . ADO,
Excel, "" , , SQL Server Oracle. , , Excel,
.
Excel ,
.
.
, Excel, Fact.xls
C:.
, . 9.7.

. 9.7. Excel, ADO

, .
. (
Excel ). ,
, , . . Excel, . : ( B3 D8) . Excel
| .
Volumes (. 9.8).

170

. 9.8.

,
.
, , Excel
.
UDL- C:\Fact.xls. UDL- OLE DB, , , (Microsoft JET 4.0 OLE DB Provider mdb).
ODBC ( ODBC Excel
). Windows
Administrative Tools ( )
Data Sources (ODBC) ( ODBC). ,
. 9.9.

ADO

171

. 9.9. ODBC

DSN (Data Source Name


ODBC):
User DSN ( )
, , , ;
System DSN ( )
;
File DSN ( ) .
,
System DSN Add.

, . , , Microsoft Excel Driver Finish. .
:
Data Source Name . , .
ExcelVolumes;

172

Select Workbook
( C:\Fact.xls);
Options,
, , Excel , Read Only.
, . 9.10.

. 9.10. ODBC Excel

OK,
ODBC.
,
ConnectionString , ADO. , , :
cn.ConnectionString = "Provider=MSDASQL.1;DSN=FactExcel;" _
& "DBQ=C:\Fact.xls;"

- ,
:
, , UDL-
( );
, Provider Microsoft OLE DB Provider for ODBC Drivers;
Connection Use Data Source Name ExcelVolumes.

ADO

173

(. 9.11). Test
Connection, OK.

. 9.11. ODBC

UDL- , .
Excel :
Public Sub ConnectToExcel()
Dim cn As New ADODB.Connection
cn.ConnectionString = "Provider=MSDASQL.1;" _
& "Data Source=ExcelVolumes"
cn.Open
' Recordset
'
Dim rs As New ADODB.Recordset
rs.Open "Volumes", cn
MsgBox rs.GetString
End Sub

174

Excel, :
Excel;
ODBC ExcelVolumes;
, Connection Open.

9.5. Recordset Fields


9.5.1. Recordset
Recordset .
Recordset? Recordset Set
of Records, . . .
( Excel),
. Recordset
Excel:
Excel "" .
, , , . Recordset "" .

( -
);
Excel
, , , . .
Recordset
.
, (
),
(Fields) (Rows). Recordset (,
cn
Northwind SQL Server):
Recordset

Dim rs As New ADODB.Recordset


rs.Open "customers", cn

, Recordset , , , :
MsgBox rs.GetString

ADO

175

Recordset , . Errors
Recordset , , Err.
Customers .
( ) . Open() SQL. ,
:
rs.Open "select * from dbo.customers", cn

, :
Where (
) Recordset , ;

;
SQL,
.
"" , . ,
, Change
, SQL Server, ,
.
:
rs.Open "select * from dbo.customers Where CompanyName = " & "'" _
& ComboBox1.Value & "'" , cn

"'" .
, , , :
select * from dbo.customers Where CompanyName = 'Alfreds Futterkiste'

SQL .
,
,
.

176

(, )
.
. ,
SQL . ,
. ,
SQL ,
. ,
VBA.

9.5.2.
Recordset
Recordset
( , Open()).
CursorType, .
Recordset (
).
Recordset.
Recordset (
, , ).
:
adOpenForwardOnly .

( ).
, , ,
;
adOpenStatic , , , ;
adOpenKeyset ,
( );
adOpenDynamic :
, ,
. ,
Microsoft.Jet.OLEDB.4.0 ,
Access Excel .
Recordset.RecordCount
adOpenStatic adOpenKeyset.

ADO

177

adOpenDynamic 1,
.

adOpenForwardOnly

CursorLocation. , .
adUseServer ( ).
adUseClient ( ). , , , , .
LockType. , ,
Recordset. :
adLockReadOnly Recordset , . ;
adLockPessimistic ,
, . Recordset,
, , , Update()
CancelUpdate();
adLockOptimistic . Update(). ;
adLockBatchOptimistic , adLockOptimistic,
. , , .
Open() ,
SQL ( ).
OLE DB , , , .
,
Recordset . Options,
.

178

:
adCmdText

SQL;

adCmdTable

( SQL, );
adCmdTableDirect , ( SQL-), ;
adCmdStoredProc

, , , Recordset.
.
Recordset , Recordset :
Dim rs As New ADODB.Recordset
rs.CursorType = adOpenStatic
rs.LockType = adLockOptimistic
rs.Open ... ',

:
rs.CursorType = adOpenStatic
rs.LockType = adLockOptimistic

, . -
(, ).

9.5.3. Recordset
Recordset ,
. , , Recordset.
Recordset (,
).
Recordset (
AbsolutePosition). MovePrevious() (
), ,
MovePrevious() , . AbsolutePosition
2. , Recordset , , BOF

ADO

179

( . Begin Of File, , , ). ,
,
BOF. , ( Recordset):
Debug.Print rs.BOF
rs.MovePrevious
Debug.Print rs.BOF

False, True.
Recordset
EOF ( End Of File). , ,
EOF.
, Recordset BOF, EOF True.
Recordset - .

Recordset .
, Recordset, , . Move...
Move() : NumRecords
( , ) () , . : ,
. , .
MoveFirst(), MoveLast(), MoveNext()

MovePrevious()
: , , .

, ( MovePrevious()
Move() ) ,
adOpenForwardOnly, ( ) .
:
rs.MoveFirst
Do Until rs.EOF

180

'-
',
rs.MoveNext
Loop

, Find() Seek().
Find()

. ,
, .
,
Like .
Find() ,
, EOF ( BOF, ). , Recordset Customers,
:
rs.Find "country = 'Germany'"
Do While Not rs.EOF
Debug.Print " : " & rs.Fields("CompanyName")
mark = rs.Bookmark
rs.Find "country = 'Germany'", 1, adSearchForward, mark
Loop

Fields
Bookmark, : Field ,
, Bookmark ,
.
Seek()

Find() , ( Index Recordset ,


, ,
Recordset, (Primary Key)).

TableDirect, .
,
Recordset ( )
Bookmark.
Variant,
Recordset, , , .

ADO

181

, , , Recordset, Microsoft ,

, Bookmark
.

9.5.4. Fields Field


Recordset ,
( Recordset (records) Record) . Recordset Field, Fields.
Record , ,
Recordset
AbsolutePosition, Find(), Move() . . Fields Field
.
Fields ,
Collection.
Count

, Recordset.

Item ( Field)
. ,
, :
rs.Fields("CompanyName")

:
rs!CompanyName

, .
Append()

Recordset. Delete()
. Recordset
( Open()
ActiveConnection).
Update() ,
CancelUpdate() ,

Recordset.
Recordset.

Refresh() , (
). Recordset Recordset.
Resync()
Recordset),

Fields Record (
.

182

Field.
ActualSize

, DefinedSize
( ), .
Attributes

( , ,
,
. .)

Name

. , , .

NumericScale Precision ,
, .
Value

Field. , ( Fields Record, Record; Fields


Recordset ). , ( ). ADO (, , ), .
OriginalValue , , UnderlyingValue ,
( Recordset, , OriginalValue UnderlyingValue
). Value Field
(. . , ,
, ), :
Debug.Print rs.Fields("CompanyName")
Debug.Print rs.Fields("CompanyName").Value
Status , adFieldOK ( 0), , Recordset.
Type


. , nvarchar 202.

Field : AppendChunk() GetChunk().


(, . .),
Value .

ADO

183

9.5.5.
Recordset , . ,
(,
SQL Server , ). , ORDER BY,
Sort
Recordset.
: , . ,
.
, (,
, ). , , Recordset ,
( ,
, ),
.
Sort :
,
(. . CursorLocation
adUseClient, );
, ,
Excel.
:
rs.Sort = "CompanyName"

, ,
(. . Field) Recordset.
:
rs.Sort = "Country ASC, CompanyName DESC"

(Country),
(CompanyName) DESC (
ASC ,
).
Recordset

184

( ,
),
:
rs.Sort = ""

Recordset .
Recordset,
, .
Filter Recordset.
:
,
Find():
rs.Filter = "LastName = 'Smith' AND FirstName = 'John'"

Like ( '*' '%'). Find() , Find() , Filter


;
;
, ,
, . .
, :
rs.Filter = ""

9.5.6.
Recordset

, .
, , ( ),
, , , , . .
, : (, , Command). Recordset,
.

ADO

185

, LockType
Recordset adLockReadOnly,
Recordset.
Recordset.
Recordset : (AddNew(), Edit(), Delete()) .
Update() Recordset,
( Delete() Update() ).
.
AddNew() ,
:
,
( );
, Value
Fields;
Update() .
Recordset
:
Dim rs As ADODB.Recordset
Set rs = CreateObject("ADODB.Recordset")
rs.CursorType = adOpenKeyset
rs.LockType = adLockOptimistic
rs.Open "select * from dbo.customers", cn
rs.AddNew
rs.Fields("CompanyName") = "Test rs company"
rs.Fields("Country") = "Germany"
rs.Fields("CustomerId") = "TESTR"
rs.Update

,
AddNew(), .
Edit()
:
rs.Find "CustomerID='ALFKI'"
rs.Fields("ContactName") = ""
rs.Update

186

Delete() :
rs.Find "CustomerID='TESTR'"
rs.Delete

, Update() !
,
.
Err.

9.5.7.
Recordset
Recordset, .
AbsolutePage, PageSize, PageCount
() Recordset.
10 .
ActiveCommand

Command,
, Recordset
. Command
. 9.6.

ActiveConnection Connection,
Recordset. ( ) ,
Connection, Source.
CacheSize , ( ). , Recordset , ,
.
EditMode

: , , ,
. .

InsertCommand, DeleteCommand, UpdateCommand Command, ,


, Recordset -

ADO
MarshalOptions ,
Recordset :

187


( )

MaxRecords


Recordset, ( ). , Recordset.
CacheSize.
State ,
Recordset.


5 : , , ,
.
Status

Recordset .
Cancel()

).

Recordset (,

CancelBatch() CancelUpdate()
Recordset ( Update())

Clone() Recordset
Recordset ( ,

).

Close()

, Recordset
( ). Open(),
( Recordset
Close() ).
CompareBookmarks()

( , ,
. .).
GetRows() Recordset
Variant.


, , , , Recordset.
:
Dim arr As Variant
'
arr = rs.GetRows
Debug.Print arr(2, 3)

188

GetString()

Recordset
. , . , Recordset:
Debug.Print rs.GetString
NextRecordSet() Recordset
, Open(), :
"select * from dbo.customers; select * from dbo.employees"


.
Requery() , Open(), Recordset.
Resync() ,
. (
Requery()).
Save() Recordset . ADTG (Microsoft Advanced Data TableGram), XML
. :
rs.Save "C:\rscustomers.xml", adPersistXML

Recordset ,
Open().
SetAllRowsStatus() Status
Recordset.
Supports() ,
Recordset ( , , . .). , , (. . ).
Recordset (EndOfRecordset,
FetchComplete, MoveComplete), , .

9.6. Command
Parameters
, , Recordset. -

ADO

189

. ,
.
. -
( , , . .)
,
Recordset .
SQL (
, DDL , , ,
) Command.
:
Dim cmd As ADODB.Command
Set cmd = CreateObject("ADODB.Command")

, , Command
Connection.
Command.ActiveConnection. Connection,
,
ActiveConnection . : -, , -,
Command,
- , .
Connection:
cmd.ActiveConnection = cn

. ,
ADO , ( , SQL . .), : , . CommandType. , , Options Open()
Recordset, . 9.5.2. ,
, :
cmd.CommandType = adCmdStoredProc

, . CommandText. ,

190

CustOrderHist, :
cmd.CommandText = "CustOrderHist"


. Parameters
Parameter. :
Parameter
( Refresh() Parameters),
:
cmd.Parameters.Refresh
cmd.Parameters(1) = "ALFKI"

Parameter
Parameters. (
), :
Dim Prm As ADODB.Parameter
Set Prm = cmd.CreateParameter("CustomerID", adVarWChar, _
adParamInput, 5, "ALFKI")
cmd.Parameters.Append Prm

. Execute(). :
cmd.Execute

,
,
. .
- ( ), .
, ?
(, OUT
),
Command, Value.
, CustOrderHist, ( ), :

ADO

191

, Execute()
Recordset, :
Dim rs2 As ADODB.Recordset
Set rs2 = cmd.Execute()
Debug.Print rs2.GetString

, Open() Recordset
Command ( Connection ):
Dim rs2 As ADODB.Recordset
Set rs2 = CreateObject("ADODB.Recordset")
rs2.Open cmd
Debug.Print rs2.GetString

Command.
CommandStream
( CommandText) (,

).
( ).
CommandStream CommandText ( ).
CommandTimeout

,
, .

Dialect

(parsing)
.

NamedParameters ,
(True)
(False, ).
Prepared , .
True ( False),
,
.
, , . " " (command preparation) .
State

,
Recordset.

Cancel() (
), .

192

9:

:
Microsoft Access .mdb, Microsoft Office 2003 C:\Program Files\Microsoft Office\OFFICE11\SAMPLES.
,
.
. ,
Microsoft Office ,
.
:
1.
InsertQueryResults.doc.

Word

C:\

2.
.
3. ( ) Word . .
4. . . , , , . 9.12.
5. | Bookmark1.
6.
.
Visual Basic Click .
:
Private
Dim
Dim
Dim

Sub CommandButton1_Click()
nEmpId As Integer
sLastName As String
sFirstName As String

ADO

193

Dim sTitle As String


nEmpId = CInt(InputBox(" :"))
',
sLastName = ""
sFirstName = ""
sTitle = ""
' ,
ThisDocument.Activate
ThisDocument.Bookmarks("Bookmark1").Select
Selection.TypeText CStr(nEmpId) & " " & sLastName & " " & _
sFirstName & " " & vbTab & sTitle & vbCrLf
End Sub

. 9.12. Word

:
Click , .mdb:
sLastName ;
sFirstName ;
sTitle .

194

( )
InputBox().

9
Click() :
Private
Dim
Dim
Dim
Dim

Sub CommandButton1_Click()
nEmpId As Integer
sLastName As String
sFirstName As String
sTitle As String

'
nEmpId = CInt(InputBox(" :"))
' Connection
Dim cn As New ADODB.Connection
' .mdb
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Program Files\Microsoft Office\OFFICE11\" _
& "SAMPLES\.mdb"
cn.Open
' Recordset
Dim rs As New ADODB.Recordset
'
rs.CursorType = adOpenStatic
' Recordset
rs.Open "SELECT [], [], [], [] " & _
"FROM [] WHERE [] = " & nEmpId, cn
', Recordset
If rs.EOF = True And rs.BOF = True Then
MsgBox " "
Exit Sub
End If
'
sLastName = rs.Fields("")
sFirstName = rs.Fields("")
sTitle = rs.Fields("")
ThisDocument.Activate
ThisDocument.Bookmarks("Bookmark1").Select
Selection.TypeText nEmpId & " " & sLastName & " " & sFirstName & _
" " & vbTab & sTitle & vbCrLf
End Sub

10

Word
10.1. Word
Word ,
Microsoft Office. Word.
Word , ,
. , , : , -, ,
, , . .
, , Word,
, . .
,
Microsoft Access, Crystal Reports,
Microsoft Reporting Services . .
Microsoft Word, , , , , ,
.
. ?

, "" ". .
". Crystal Reports Microsoft Reporting
Services, . -
. . , .
Word, -

196

10


Word. .
Word . ,
Word ,
( dot).
, (,
),
Word, , , Crystal Reports Reporting Services.
Word
. Word
.
:
"" .
Word , ,
HTML, XML EML ( ).
SharePoint Portal Server (Word 2003) SharePoint Portal Server.
, .
Word , : ,
, . .
, , .

10.2. Word.

Word , . 10.1.

. ( ):
Application;
Document ( Documents);
Selection;
Range;
Bookmark ( Bookmarks).
. , , ,

Word

197


. Word ( )
, .
, ,
.
Office,
, . ,
.

. 10.1. Word

10.3. Application
10.3.1. Application
Application Microsoft Word.
Word "" . ,

198

10

Word . , (
Word ,
Access). Word
Office, Microsoft
Word 11.0 Object Library.
Word :
Dim oWord As New Word.Application

, , , , , - . :
1. Word .
2. , ( , ).
Word :
oWord.Visible = True

: ? , . Word
, . ,
. , ,
, Word - : -,
, -, , Word , .
Word , (
, Task Manager). Word
Quit().
Word , . ,
Word :
Dim oWord As New Word.Application
oWord.Visible = True
oWord.Documents.Add

Word , , , :
Set oWord = GetObject(, "Word.Application")

, ( OLE), Word

Word

199

. , .
Word.
VBA Word (. . Word ),
Application . ( ,
Application ). , ,
, VBA
Word , Application.
:
Application.Selection.TypeText " "

Selection.TypeText " "

, Application Word.
( , Word, ,
, , . .) . , Declarations ( !)
Application WithEvents, :
Public WithEvents App As Word.Application

App (. . Application),

, .

10.3.2. ,
Application
,
Application.
ActiveDocument

Word. ,
Application, :

ActiveDocument.Save

, ,
Activate().

10

200
ActivePrinter


. , ,
. ,
.
AutomationSecurity

.
msoAutomationSecurityLow . msoAutomationSecurityForceDisable ( ) msoAutomationSecurityByUI (, ).

BackgroundPrintingStatus

, Word

.
Browser

, Browser (
, ). Target, 12 (, , , , , . .).
Next() Previous()
.
Build Word.
,
Word.
CapsLock

, CapsLock . (
), (
Windows API). NumLock.
Caption

"Microsoft Word"
, " ".

CheckLanguage

True, Word
, . , .
Word.
COMAdIns COM
Ad ins Word ,
COM. .

Word

201

CustomizationContext

,
,
, . ,
:
CustomizationContext = NormalTemplate

, , ,
, Normal.dot (, ,
).
Dialogs

Dialogs,
Word. ""
Word Word
, . ,
"" ,
( Locals),
. ,
VBA, , . :
Dim oDlg As Dialog
Set oDlg = Application.Dialogs(wdDialogFileOpen)
If oDlg.Display = -1 Then
MsgBox " : " & _
Application.Options.DefaultFilePath(wdCurrentFolderPath) & _
"\" & oDlg.Name
End If

, ,
Application FileDialog, .
DefaultSaveFormat

Word
(,
Save As). TXT, Unicode, RTF . .

DisplayAlerts .
VBA.
.
, .

202

10

DisplayAutoCompleteTips

. .

Documents . .

. 10.4.
EmailOptions
EmailOptions, Word -

Outlook.
EnableCancelKey

, <Ctrl>+<Break>.
wdCancelDisabled,
, , ,
Word Task Manager.
FeatureInstall

,
Office
.
msoFeatureInstallNone.
FileDialog FileDialog, . . , , . Show() .
FileSearch

FileSearch, .

International . , , , , Word . .
IsObjectValid ( , . .). ,
, .
, , ,
.
KeyBindings

. KeyBindings .
,
Word
( , ,
<Alt>+<F4>). :

Word

203

CustomizationContext Application, . .
: Normal.dot, , ;
Application.BuildKeyCode()
;
KeyBindings.Add() ,
.
, <Alt>+<D>
DataLoad() , :
CustomizationContext = NormalTemplate
Application.KeyBindings.Add wdKeyCategoryMacro, _
"Normal.NewMacros.DataLoad", BuildKeyCode(wdKeyAlt, wdKeyD)
Language , , Word (,
). 1049, 1033. ( , . .) LanguageSettings.
MacroContainer .
,
( Normal.dot
).
NewDocument Word. NewDocument.
Application.NewDocument.Add().
NormalTemplate
Template, Normal.dot, .
Option

Option .
( | ).
Path

Word .

PrintPreview ,
.
.
ScreenUpdating , ( False). , - .

204

10

Selection

. Selection
, .
. 10.5.
ShowStartupDialog

, Task Panel (
) Word. .
Show..., .
SpecialMode , Word
( <F2> <Shift>+<F2>,
<Enter>).
StartUpPath

/
. ,
, Word .
.
\application data\microsoft\word\startup.

StatusBar .
Status Bar ( ), . . , , , ,
. .
System

System,
( , , , . .).

Microsoft System Information.
Tasks Tasks Task,
.

- ( , , , Windows,
Windows API . .). . Shell, . 10.6.10.
UserControl

( Excel).
, Word
. , ,
, .

Word

205

UserName . , .
UserInitials

VBE

, VBE, Visual Basic. VBA, ,


.

Version Word ( ,
Build). Word 2003 11.0.
Visible

Microsoft Word
Word c , .

Windows

Windows,
Window.
Word.
WindowsState

Word.
Application .
Activate() Word .
, Document.
BuildKeyCode()


Word.
Application.KeyBindings.
ChangeFileOpenDirectory()

, Word (
, , );
CheckGrammar() CheckSpelling()
. Document Range.
CleanString() . "" (, , Selection
Range) Word
, .
DefaultWebOptions() , , Word HTML (, , CSS, . .).

10

206

GoBack() . Word
, Word
, , :
RecentFiles(1).Open
Application.GoBack
GoForward()

KeyBoard()

.
Word, . :

Application.Keyboard 1049

:
Application.Keyboard 1033

,
.
KeyString()

, BuildKeyCode(). BuildKeyCode() ,

.

ListCommands() , . Word, , .
OnTime()

.
Word , - . Word . .

OrganizerCopy()

.
, , . OrganizerDelete() OrganizerRename().
PrintOut()

,
( )
. Application, Document Window.
Quit() , , , . Word .

Word

207

Repeat() .
ResetIgnoreAll() ,
" " .
Run()

. / .

ScreenRefresh()

. ,
ScreenUpdating.
ShowClipboard()

Word ( ).
DDE, . .
Application : , , , , , . . ,
Application Visual Basic.
, Declarations
:
Public WithEvents App As Word.Application


App .

10.4. Documents
Document
10.4.1. Documents
Application Word (
) Documents Document, . Word
.
:
1. Word.
2. .
3. - (,
, ).

208

10

Word Application,
. Selection, Range Bookmark,
. 10.5. , , , . . Documents Document.
:
Dim oDoc As Word.Document
Set oDoc = Application.Documents.Add()

(
Normal.dot) oDoc.
.
, . - , , . , ,
. , Word,
.
Word.
, , ,
dot (, C: dog_blank.dot). :
Dim oDoc As Word.Document
Set oDoc = Application.Documents.Add("C:\dog_blank.dot")

Bookmark Range (. . 10.5)


.
:
. , : , , -,
, ;

-, . .

Word

209

: , -. , , ;
. OLE Access.
Access ,
. . Word Access. , Access, :
SQL Server, Oracle . .
, , . .
mdb, Word. ,
Access ,
. , Documents.Add() , .
,
OLEActivate().
Word, . , . 12.
, - .
Open() Documents.
:
Dim oDoc1 As Word.Document
Set oDoc1 = Documents.Open("c:\doc1.doc")

,
, .
( ) Open() ,

, .
, . .
Save() SaveAs()
Documents Save(), Word,
.
Document.

210

10

, Word Word
, ,
Word TXT, HTML, XML . .
( FileConvertor).
, , , ,
Exchange Server, SharePoint Portal Server.
FileSystemObject
Microsoft Scripting Runtime,
Windows (. . 4).

10.4.2. Documents
Documents, ,
Word, .
1. Count . Documents. , .
Add()
( ).
Word. :
Add(Template, NewTemplate, DocumentType, Visible)

Template , NewTemplate
(True/False) , DocumentType
, : wdNewBlankDocument,
wdNewEmailMessage, wdNewFrameset wdNewWebPage (
), Visible (
) . . , Normal.dot (
| ).
Open()

Documents. . ,
( ).
:

Word

211

Dim oDoc1 As Document


Set oDoc1 = Documents.Open("c:\doc1.doc")
Item()

.
For...Next -
If...Then. Name:
Dim oDoc1 As Word.Document
For i = 1 To Documents.Count
Set oDoc1 = Documents.Item(i)
If oDoc1.Name = "doc1.doc" Then
Exit For
End If
Set oDoc1 = Nothing
Next

oDoc1
doc1.doc, . ,
.
,
.
Item() . ,
Documents:
MsgBox Documents.Item(1).Name

Close()
.

Save()

CanCheckOut() ( "" )
CheckOut() ( ) -

,
SharePoint Portal Server.

10.4.3. Document,

, Application Word,
Documents ( ,
) , , ,
Document. , .

212

10

, Document
. , ,
Document:
Documents. , , Documents.Item(1);
ThisDocument.
, , :
MsgBox ThisDocument.Name

ActiveDocument Application.
:
MsgBox Application.ActiveDocument.Name


MsgBox ActiveDocument.Name

Document .
ActiveWritingStyle

(
, , . .).
.

AttachedTemplate (
, , . .) , ( |
).
Background

Shape, ( Web-).

BuiltInDocumentProperties
DocumentProperties , -

(, , ,
. .);
Characters

Range,
.
Document, Selection Range. , ,
(, );
Content

, Range,
(main document story). ,
, , ,
. .

Word

213

CustomDocumentsProperty ,
DocumentProperties,

. . , , , / , ,
. .
DefaultTabStop


. 35 , 1,25 .

DisableFeatures ,
Word ( ,
).
DisableFeatures , DisableFeaturesIntroducedAfter.
DoNotEmbedSystemFonts
( ,
, ).
, ,
, .
EmbedTrueTypeFonts , , (, ). true-type , , .
Envelope Envelope,
.
Fields

Fields
. .
Word ,
: , , , . .
Word | .
Footnotes

Formatting... ,
.
FormFields Fields,
.
FullName

( Web). .

10

214
GrammarChecked

, (
). Range.
, , GrammaticalErrors,
( )
ShowGrammaticalErrors. SpellingChecked, SpellingErrors ShowSpellingErrors.
HasPassword , .
Password .
Word, Excel Access .
Indexes (. . )
.
Name

( ).

OpenEncoding ,
. 1251.
PageSetup . .
Paragraphs

.
Path

( ).
, .

Permission

Permission,
Word ( ).
PrintRevisions

() . .

ProtectionType ( ,
, , . .).
Protect().
ReadOnly ,
. ,
.

RemovePersonalInformation
-

RemoveDateAndTime

Word

215

( ).
-.
Saved . , .
SaveEncoding

( ) ,
.

SaveFormat


(DOC, RTF, TXT, HTML . .). .

Sections

. Sentences
. Shapes, Styles,
Subdocuments, Tables, Windows Words.
Type

(, Web-
).

Variables .
, (custom attributes), ,
, .

Document.
Activate() (, ).
AddToFavorities()


. ,
.
CheckGrammar()
.

CheckSpelling()
Close()

. ( ), ( ).

Compare()
, .
DetectLanguage()

.
, .
. , LanguageDetected False.

FitToPages()

.
,
. " "
.

10

216

FollowHyperlink() ( HTML, Internet Explorer).


GoTo()

. Document Range Range, Selection


.
, ,
, , , , , , , , . . , , , . .
.
Merge()

.
, .

PresentIt()

PowerPoint.

PrintOut()

,
.

PrintPreview()

.
Protect()


, IRM. | .
Range() . Range (. . 10.5),

.
Redo() .
, True, .
Repaginate() .
, (, ( |
) Options).
Save()

. , .

SaveAs() .
, , ,
, .
, , .

Word

217

Select()

. , Selection
Range.

TransformDocument() , , XML XSLT.


(Extensible
Stylesheet Language Transformation, XSLT),
, .
Undo() . Redo().
UndoClear() ,
.
UnProtect() (
Protect() ).

.
Document : New ( , , ), Open Close. Visual Basic.

10.5. Selection, Range Bookmark


10.5.1. Selection
,
, , ,
.
Selection, Range Bookmark.
.
, , Selection.
, - Word, ,
. Selection
( ,
, ). .
Selection . , Selection

218

10

. Word . :
Application.Selection.Text = " "

:
Selection.Text = " "

,
Selection,
.
Word:
. ,
;
Select(),
(Document, Range, Bookmark, Table
, PageNumber, Field . .). , , . .;
Selection,
;
Find .
. 10.6.5;
,
. . .
, ,
( <Ctrl>) , , .
, Selection, , Type Information
Selection.
, Selection ,
, . : -

Word

219

. , . :
(. . ) , ,
Word.
Visible Document Application;
Selection
Range Bookmark, .

10.5.2. Selection

Selection.
Bookmarks

Bookmarks, . . ,
. VBA Word.
. 10.5.

Start End

,
(
, , ).
0. , ,
( , ).
ExtendMode

,
, <Home> <End> , .
Find

, Find. Replace
. 10.6.5.

Flags

,
, : ,
. .
.
Font Font,
. ,
| . ,
Arial 10 pt, :

10

220
Selection.Font.Name = "Arial"
Selection.Font.Size = 10
Information

Selection .
(
, , <CapsLock>
<NumLock>, "" , . .).
IPAtEndOfLine

True, (insertion
point IP) (
).
LanguageId , . .
NoProofing .
, , ,
. .
Range

Range.

StoryType

. , .

Text

Selection.
( , ). , 100 "!", :

For i = 0 To 100
Selection.Text = "!"
Selection.EndOf
Next

EndOf() .
,
100 , .
Type ,
, - . ,
1, 2.
Words

Words.
Range, .

Word

221

Selection , .
Calculate()


( Single).

ClearFormatting()

( ,
).
Selection, Find Replace.
Collapse() . :
. , .
Copy(), CopyAsPicture(), Cut(), Paste()

Delete()
, , , .

EndKey()

,
<End>. ( ) ,
( ) , . , :
Selection.EndKey Unit:=wdStory, Extend:=wdMove

,
HomeKey().
EndOf()

EndKey().
, , , , , , . .
, EndKey()
, EndOf() , , .
, StartOf().
Expand() , , . .,
. Extend() ( ,
. .). , Expand(), Shrink().
GoTo()
Document.

222

10

GotoNext() , , . .
GotoPrevious() ( ).

Insert... .
InsertBefore() ( ) InsertAfter() ( ).
Move... , Word.
:
MoveLeft(), MoveRight(), MoveUp(), MoveDown(), MoveEnd(), MoveStart()
,
, , , . ,
,
, , , . .;
MoveStartUntil(), MoveStartWhile(), MoveEndUntil(), MoveStartWhile()
,
, ( )
. ;
Move() . , , , ,
, . . ,
.
Next()

, , , , ,
. . Previous().
NextField() , ( Field
Nothing). PreviousField().
SelectColumn(), SelectRow(), SelectCell()


Word.

SelectCurrentAlignment(), SelectCurrentFont(), SelectCurrentIndent(),


SelectCurrentColor() . . -

, , , . .

Word

223

.
SetRange()

.
,
. 0,
. Range.

Sort(), SortAscending(), SortDescending()


, . . (
). .
ToggleCharacterCode()


Unicode. ,
, :

Selection.TypeText Text:="20ac"
Selection.ToggleCharacterCode
TypeText() , . ,
. , ReplaceSelection Options (. . 10.6.4).
WholeStory()

. , , , . .

10.5.3. Range,

, Selection.
Range.
, Selection
( ), Range
,
.
Range Selection.
,
(, , , - ).
Range : , .

224

10

Selection
Range, .
( ).
Range , Selection .
Range :
Range() Document.

, , . , ,
10 , :
Dim rngDoc As Range
Set rngDoc = ActiveDocument.Range(Start:=0, End:=10)

Range, (Bookmark, Selection, Table-Row-Cell,


Paragraph . .).
Range, ;

(Characters, Words, Sentences . .), Range.
Range. , Range, , ;
Range. SetRange() Range;
, , .
, (, , . .),
, .

Range, ( , . .).
( , Range , )
Range Selection (. . ).
Range Select().
Range
Selection ( ),

Word

225

. Range
- Text, , ,
. Range.
InsertDatabase() Word.
,
Range. ODBC, DDE,
Access. ,
.
ADO
(. . 9). Access
:
With Selection
.Collapse Direction:=wdCollapseEnd
.Range.InsertDatabase _
Format:=wdTableFormatSimple2, Style:=191, _
LinkToSource:=False, _
Connection:="Table.", _
DataSource:="C:\Program Files\Microsoft
Office\OFFICE11\SAMPLES\.mdb"
End With
IsEqual() Range ( Selection
Range). ,
, True.
FoneticGuide()

Relocate()

.
Select() , Selection
Range (. . ).
.
SetRange() Range.
. , Range,
(
), :
Dim MyRange As Range
Set MyRange = ActiveDocument.Range(Start:=0, End:=0)
MyRange.SetRange Start:=MyRange.Start, End:=Selection.End
MyRange.Select
'

226

10

10.5.4. Bookmark
Bookmark .
, (, ). Selection Range
,
( Range , .
, , , .
( | ) ,
Range , Move() (MoveDown(),
MoveRight(), MoveNext()) Selection. ,
( ), , ,
(
Selection Range).
Bookmark .
, Selection Range.
Bookmark .
Bookmark ( Bookmarks, ) Selection ( Select()) Range ( Range), , :
ThisDocument.Bookmarks("Bookmark1").Select
MsgBox Selection.Text

Bookmark ,
, Add()
Bookmarks:
ThisDocument.Bookmarks.Add Name:="temp", Range:=Selection.Range

, .
Bookmark .
Empty True, , ;
Name . , Bookmarks () , .

Word
Range

227

Range .

Start, End, StoryType


Selection.

Bookmark .
Copy()

Delete()

Select()

, .

10.6. Word
Word ,
. ,
, .
Word. Application
.

10.6.1. AddIns AddIn


AddIns AddIn,
Word , Word.
, Add()
( | ). ,
.
dot,
Word. ,
"" ,
, , . . , (,
-).
DLL (
wll Word Add-In Library). , Word. COM- ,
, ++, Visual Basic Delphi, ,

228

10

VBA .
, .

10.6.2. AutoCorrect
,
| .
, . , , , . ,

, :
For Each Item In AutoCorrect.Entries
Item.Delete
Next

10.6.3. Languages Language


Languages , Word
. ,
Word, :
For Each lan In Languages
Debug.Print lan.Name
i = i + 1
Next lan
Debug.Print i

10.6.4. Options
Word .
, | . Options , ,
. , Word
( ), :
Options.BlueScreen = True

Word

229

10.6.5. Find Replacement


Find Replacement, ,
. Find ,
"" . (Text,
Style, Font, Forward, MathCase, LanguageID . .), . , Execute()
,
, ReplaceWith,
.
, ,
Execute(). ,
True (, , ), False.
Find ,
. Find Selection,
. Range,
. ,
"2004", :
Selection.Find.Text = "2004"
Selection.Find.Execute

Replacement .
Replacement Find. ,
"2004" "2005", :
Selection.Find.Text = "2004"
Selection.Find.Replacement.Text = "2005"
Selection.Find.Execute Replace:=wdReplaceAll

: Find Replacement
.
, . ClearFormatting().
Find Replacement (
)
. ,
:
Selection.Find.Text = "2004"
Selection.Find.ClearFormatting

230

10

Selection.Find.Replacement.Text = "2005"
Selection.Find.Replacement.ClearFormatting
Selection.Find.Execute Replace:=wdReplaceAll

10.6.6. Font ParagraphFormat


Font ParagraphFormat . Font , | ,
ParagraphFormat | . Font
Font, , ,
Selection, Range Find, ParagraphFormat Format,
Paragraph ( )
Paragraphs ( ). Format,
ParagraphFormat, Find.
Font ParagraphFormat , .
, Arial
, :
Selection.Font.Name = "Arial"
Selection.Font.Bold = True

,
:
Paragraphs(1).Format.Alignment = wdAlignParagraphJustify

10.6.7. PageSetup
, PageSetup .
, |
. PageSetup
Document, Selection Range,
. ,
, :
ThisDocument.PageSetup.Orientation = wdOrientLandscape

10.6.8. Table, Column, Row Cell


-
(, ,
. .), , , -

Word

231

. .
,
( ,
).
, Tables ( Document, Selection Range)
Table ( ):
Set Range1 = ThisDocument.Range(Start:=0, End:=0)
Dim Table1 As Table
Set Table1 = ThisDocument.Tables.Add(Range1, 3, 4)

, , AutoFormat() ( ,
| ):
Table1.AutoFormat wdTableFormatGrid5

- .
Word Cell.
Columns Rows, Selection Range,
:
Table1.Cell(1, 1).Range.InsertAfter "10"
Table1.Cell(2, 1).Range.InsertAfter "15"
Table1.Cell(3, 1).AutoSum

10,
15, . Word , , Excel, Formula() Cell
.
Word , , , , .

.

10.6.9. System
System , .

232

10

Windows Script Host WMI


. (Windows NT, Windows 98),
, .
System.
CountryRegion . , 7 ( ,
), 1.
FreeDisk


( ). ,
, ,
.
HorizontalRezolution VerticalResolution , ,
.
LanguageDesignation

. , :

Debug.Print System.LanguageDesignation
OperationSystem .
, : "Windows" Windows 95/98/ME "Windows NT" NT/2000/XP/2003.

: Connect() ( )
MsInfo() ( ).

10.6.10. Tasks Task


Word Excel, Access ,
Word
.
Word VBA
Shell. , , :
Shell "notepad.exe"

, , Application Word, Windows


Script Host ( ), WMI,
.

Word

233

, ,
Word Tasks,
Task. Tasks .
Exists() , . ,
:
If Tasks.Exists("Notepad") = False Then
Shell "notepad.exe"
Else
Tasks("Notepad").Activate
End If
Tasks("Notepad").WindowState = wdWindowStateMaximize
ExitWindows() Log Off, . . Windows. Word
( ), .

Task .
Height, Width, Top, Left

Visible

WindowState

.
Activate(), Close(), Move(), Resize()

.
SendWindowMessage()

.
Windows ( ,
. .). , , Microsoft Platform Software Development Kit ( Microsoft). , , :

Tasks("Notepad").SendWindowMessage &H111, 11, 0

10.6.11. Windows Window


Windows Window Word
.
:

10

234
Dim Window1 As Window
Set Window1 = Windows("doc2.doc")

:
Set Window1 = ThisDocument.ActiveWindow

Window.
. , , :
Window1.Caption = " "

10:

Word
:
Word. , . 10.2
( ). , , .

. 10.2.

:
1. Normal.dot FormDog
, . 10.3.

Word

235

. 10.3.

2. , ,
Word.
3. C:\DogovorTemplate.dot,
, .
4.
,
.


(,
).
. . 12.
( ) .

10
1 ( ):
1. Visual Basic Word Normal Project Explorer, Insert | UserForm.
2. ,
. 10.3 ( . 5).
:
txtNumber ;
txtCity ;

236

10

txtDate ;
txtOrg ;
txtPerson ;
txtTitle ;
txtLaw ;
cmdDog ;
cmdancel .
3. . Caption " ".
cmdDog True Default,
cmdCancel True Cancel. Name FormDog.
2 ( ):
1. NewMacros Normal FormDog(). :
Public Sub FormDogShow()
FormDog.Show
End Sub

, .
2. Word ,
. ,

Normal.NewMacros.FormDogShow.
(. . 1).
,
.
3 ( Word):
1. Word,
. 10.4.
2. . . 10.2 (, ).
:
bNumber ;
bCity ;

Word

237

bDate ;
bOrg ;
bPerson ;
bTitle ;
bLaw .
3.
C:\DogovorTemplate.dot.

Microsoft

Word

. 10.4.

4 ( ):
1. Click cmdCancel
:
Private Sub cmdCancel_Click()
FormDog.Hide
End Sub

2. Click cmdDog :
Private Sub cmdDog_Click()
Dim oDoc As Document
Set oDoc = Application.Documents.Add("C:\DogovorTemplate.dot")
oDoc.Bookmarks("bNumber").Range.Text = txtNumber.Value
oDoc.Bookmarks("bCity").Range.Text = txtCity.Value
oDoc.Bookmarks("bDate").Range.Text = txtDate.Value

238
oDoc.Bookmarks("bOrg").Range.Text = txtOrg.Value
oDoc.Bookmarks("bPerson").Range.Text = txtPerson.Value
oDoc.Bookmarks("bTitle").Range.Text = txtTitle.Value
oDoc.Bookmarks("bLaw").Range.Text = txtLaw.Value
FormDog.Hide
oDoc.Activate
End Sub

10

11

Excel
11.1. Excel
Excel
Office. Office, , Excel.
:
Excel
, (, . .)
. , , (, . .) ,
, . Excel ;
, ,
Excel. , . , . ,
;
, , Excel. , ,

240

11

Excel ( ). Excel
, , .
, , - ;
Excel
, .
, , . . Excel.

Excel ;
, Excel (
Excel, DBF . .). , ,
Excel
.
, , . , ,
.
Excel, Word, ,
(, . .). (, , , Excel ( ).
Word Excel ,
( A1 R1C1). , Excel , .
Excel . Word
: Application Document Range, Excel
,
: Application Workbook () Worksheet ()
Range ().
Excel (, , . .), . Excel
.

Excel

241

Excel ,
. , (
PivotTable) Excel OLAP-
Microsoft Panorama Software, QueryTable
, Chart
. .

11.2. Application
Word, Application Microsoft Excel Excel Excel.
Excel ,
Excel.Application (
Tools | References Microsoft Excel 11.0 Object
Library). :
Dim oExcel As New Excel.Application
oExcel.Workbooks.Add
oExcel.Visible = True

, Word, Excel,
Application . .
-
, Visual Basic Excel ,
Application. Excel :
Application.Workbooks.Add

Workbooks.Add

Application Office , ,
Word.Application. ,
Excel,
Excel , . Application,
Declarations
Application WithEvents, , :
Public WithEvents App As Excel.Application


App, Application
(. 11.1).

11

242

. 11.1. App

11.3. Application
, Excel.Application
Word.Application. . .
, -,
Application Excel, , Word .
Application.
Active... (,
), ,
, . . ,
ActiveCell, ActiveSheet . . . ActivePrinter ,
.
AddIns
AddIn).

(
Word, , Excel . Excel
( | ),
, , , . .
, -

Excel

243

( )
.
AutoRecover , Excel. , Excel 5 , :
Application.AutoRecover.Time = 5

,
1 120. | .
Calculation
( ,
, , ). , .
| , (
<F9>).
CalculationState

, Excel
.

Cells

Application. Range,
. (. . , ) Range Item,
:
Application.Cells(1, 2).Font.Bold = True

.
Columns Rows. , , :
Application.Columns(2).Font.Bold = True

:
Application.Rows(2).Font.Bold = True

, Cells, Columns Rows


Cell, Column Row, ,

11

244

Range. Range Excel


.
Range . 11.6.
Cursor
Excel ( Application Word - ).
(xlWait), .
,
.
DataEntryMode

, .
(data entry mode),
.
: xlOn , xlStrict
, <Esc>, xlOff .
ThousandsSeparator , ,
.
UseSystemSeparators:

DecimalSeparator

Application.UseSystemSeparators = False
Dialogs

Dialog,
Excel (
) .
FileDialog, ,
(,
). , Word.
DisplayAlerts ,
Word, . ,
(, , ).
EnableEvents
Application, ( -

- , . .).

Excel

245

ErrorCheckingOptions

,

Excel ( ,
. .).
, ,
.
FileDialog

(
Dialogs). ,
,
:

Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
Application.FileDialog(msoFileDialogOpen).Show
Debug.Print Application.FileDialog(msoFileDialogOpen).SelectedItems(1)

.
FileSearch


.
Interactive


Excel ( , ). , , , . ,
, Excel.
International LanguageSettings

, Word.

LibraryPath ,
Excel xla. \Office11\Library.
MoveAfterReturn

<Enter> (
), MoveAfterReturnDirection .
. , , :
Application.MoveAfterReturnDirection = xlToRight
Names Names, . Add()
Names
.

246

11

, Word Excel. Excel


| .
OLEDBErrors ODBC OLE DB . ,
ODBCError OLEDBError , .

ODBCErrors

OnWindow . ,
( , ). , Excel ( ).

Auto_Activate Auto_Deactivate ( , , ,
OnWindow).
Range . Range, Excel
.
ReferenceStyle A1 ( , ) R1C1 ( ,
). | , R1C1.
A1, , , R1C1
( , AA, AB . .). -
R1C1,
. ,
.
Selection , ,
.
, Range. -
, , . ., , .
Sheets . 11.5, Excel. Sheets

Excel

247

, .
Worksheets, Sheets,
Worksheet ( ).
TemplatesPath , Excel (, ).
Application Data\Microsoft\Templates
.

ThisWorkbook ,
, .
Excel.

ThisCell

Windows, Workbooks

Sheets , ,
, Excel.
. 11.5.
WorkSheetFunction VBA Excel , -
.

Excel.Application .
ActivateMicrosoftApp() ,
( ,
) Office (Word, Access, PowerPoint) (Project, FoxPro, Schedule Plus).
AddCustomList()

.
Range (
, ), Array. DeleteCustomList().

Calculate...
. Calculate()
( , ), CalculateFull() , CalculateFullRebuild()
( ). CheckAbort().
ConvertFormula()

: (, A1 R1C1),
.
(
'=') .

11

248
DoubleClick()


, . . .

Evaluate()

.
Excel .
:
A1 ( Cell);

( Range);
, ( );
, :
Evaluate("[Book1.xls]Sheet1!A5"))

, . ,
:
[a1].Value = 25
Evaluate("A1").Value = 25

, .
, Evaluate()
Excel.
GetOpenFilename()
. ,
(
), :
Filename = Application.GetOpenFilename()
If Filename <> False Then
Debug.Print Filename
End If
GetSaveAsFilename()

,
.
GoTo() . Range, ( R1C1)
VBA,
. Select(),
, .

Excel

249

Help()
( ).
.
Intersect() ,
.
, Nothing.
OnKey() "" VBA . , Msg() 1 <Alt>+<M>,
:
Application.OnKey "%{m}", "1.Msg"
OnRepeat()

,
.

OnUndo().
RegisterXLL() Excel xll
.
.
Repeat()

, ( ).
.
Undo().

Run()

VBA, Excel
XLL- ( 30 ).

SendKeys()

. , - - (,
, ).
Union()

Volatile()

, .
True,
(volatile) ,
, .
Wait() Excel
, . ,
, , - . .

11

250

,
. Excel, , . ,
, :
If Application.Wait(Now + TimeValue("0:00:5")) Then
MsgBox " "
End If
Quit() OnTime()

, Word.

11.4. Workbooks
Workbook,
Application
Excel Workbook, Excel. , Workbook Excel ,
Document Word
Excel, .
:
Workbooks, Workbooks Application. ,
Workbooks Excel
.
, :
Debug.Print Workbooks(".xls").FullName

Application.ActiveWorkbook.

:
Debug.Print ActiveWorkbook.Name

Application.ThisWorkbook.
,
:
Debug.Print ThisWorkbook.Name

Excel ,
( , Excel, , DBF). Add()
Open() . , Excel :

Excel

251

Dim oWbk As Workbook


Set oWbk = Workbooks.Add()

, ,
, .
:
Dim oWbk As Workbook
Set oWbk = WorkBooks.Open("C:\mybook1.xls")

, Workbooks .
OpenDatabase() , (
),

Excel;
OpenText() ,
.
.
OpenXML()

XML.
InsertDatabase() Word, . ADO.
Workbook .
Name, CodeName, FullName .
Name, . FullName

.
. CodeName
Project Explorer , Properties,
(Name).
, (,
Properties).

CodeName

Path,
Excel.
Charts, Sheets, ActiveChart, ActiveSheet, CustomViews, BuiltinDocumentProperties CustomDocumentProperties, Windows, WebOptions

.
.

252

11

ConflictResolution

, ,
(shared workbook). , , . , , ,
( ), ,
:

SaveAs() ExclusiveAccess();
( MultiUserEditing);
( ,
)
UserStatus.
FileFormat (
, ). :
Excel, DBF, Lotus 1-2-3, TXT, CSV, XML
.
Names
. , , :
For Each Item In ThisWorkbook.Names
Debug.Print Item.Name
Next


.
Workbook , Activate(), Close(), Save(), SaveAs(), PrintOut(),
Protect() Unprotect(), Document Word.

11.5. Sheets Worksheet,



Word Application Document : Selection, Range . . Excel

Excel

253


Worksheet (). Worksheet Sheets.
Excel ( )
, , , , ,
.
:
Dim oExcel As New Excel.Application
oExcel.Visible = True
Dim oWbk As Excel.Workbook
Set oWbk = oExcel.Workbooks.Add()
Dim oSheet As Excel.Worksheet
Set oSheet = oWbk.Worksheets.Add()
oSheet.Name = " "

' Excel
'
'
'
' " "

Add() Worksheets , ,
.
, .
,
, . ,
Worksheets .
, Excel ,
"1" "
":
Dim oExcel As New Excel.Application
' Excel
oExcel.Visible = True
'
Dim oWbk As Excel.Workbook
Set oWbk = oExcel.Workbooks.Add()
'
Dim oSheet As Excel.Worksheet
Set oSheet = oWbk.Worksheets.Item("1") ' 1
oSheet.Name = " "
' " "

, Excel , "Sheet1", "Sheet2" . .


, , Excel,
.

11

254

Sheets VBA
(Count, Item, Add(), Delete()).
Worksheet (Visible(), Copy(), Move(), PrintOut(), PrintPreview(),
Select()), .

FillAcrossSheets() Range (, ) .
Worksheet .
Cells

.
, Application,
, . Columns Rows.
EnableCalculation

EnableSelection - ,
.
Next
Previous

,
.

PageSetup

Word, PageSetup, ,
| .

Protection

Protection, Excel.
,
Protection...
QueryTables . QueryTables QueryTable, , ,

, ( ,
).
Range
Range ( ),

Worksheet.
Excel ,
Word. . 11.6.
Type .
xlWorksheet ( ) xlChart ().
UsedRange

Range, , . .

Excel

255

Visible

(,
).

Worksheet .
Activate(), Calculate(), Copy(), Paste(), Delete(), Move(), Evaluate(),
Select(), SaveAs(), PrintOut(), PrintPreview(), Protect(), Unprotect()

. , .
PivotTables()
PivotTable ( ), . 11.8.
Scenarios() Scenarios,
Scenario (). -

,
( , , . .).
SetBackgroundPicture()

(, , , " ", ).

ShowAllData()

.
Worksheet , , Change.
,

Excel, . ,
,
(, ).
Target, . . Range, .
Range
, , , . .
Worksheet (
Document Word) BeforeRightClick()
BeforeDoubleClick(). , , . ( , , . .)
.

256

11

11.6. Range,
,
Excel Range. ,
( ) . Word
Range, Selection, Excel Range:
,
Range, ;
- , Range, ;
- , Range, .
Microsoft (www.microsoft.com/support) 291308, 22 Range
Excel. .
.
Range.
Application, Worksheet
Range (
). , Range, A1, :
Dim oRange As Range
Set oRange = Worksheets("1").Range("A1")

A1 D10 :
Dim oRange As Range
Set oRange = Worksheets("1").Range("A1:D10")

Range Range . , Excel Range . :


Set oRange1 = Worksheets("1").Range("C1")
Set oRange2 = oRange1.Range("B1")
oRange2.Value = 20

20 B1, ,
D1 (. . B1 , C1).

Excel

257

Cells Worksheet.
, .
( , . .). ,
D1 :
Dim oRange As Range
Set oRange = Worksheets("1").Cells(1, 4)

, , Range Cells :
Dim oRange
Set oRange = Range(Cells(1, 1), Cells(5, 3))


Range, . .
, , - .
Value, :
oRange.Value = " "

Range ,
( Excel
).
.
Address

. ,
$A$1:$C$5.
, $A$1.
,
,
. . .
AddressLocal , Excel.
,
.
.
, oRange, ,
:
sColumnName = Mid(oRange.Address,2,(InStr(2,oRange.Address,"$") 2))

258

11

:
sRowNumber = Mid(oRange.Address,(InStr(2,oRange.Address,"$") + 1))

, ,
( ) ,
, .
InStr(),
, ,
Mid().
AllowEdit , , ,
( ) . .
Areas

. , Range .
. Areas . Range
Areas.
"" :
If Selection.Areas.Count > 1 Then
Debug.Print " "
End If
Borders

Borders,
.

Cells

, , Worksheet.
Range , , :
Dim oRange, oRange2 As Range
Set oRange = Range(Cells(2, 2), Cells(5, 3))
Set oRange2 = oRange.Cells(1, 1) ' A1 B2
Debug.Print oRange2.Address
'

Row Rows, Column Columns.


Characters


: , . , A1 , :

Excel

259

Dim oRange As Range


Set oRange = Range("A1")
oRange.Value = " "
oRange.Characters(1, 1).Font.Color = vbRed

,
Value .
Count .
.
CurrentRegion

, , , ,
( , ).
Range, , (. . , ). ,
, :
Worksheets("1").Activate
ActiveCell.CurrentRegion.Select

, ,
, .
Dependents Range ( , ), ,
.
. ,
, , :
Worksheets("1").Activate
ActiveCell.Dependents.Select

,
Precedents. ,
DirectDependents DirectPrecedents.
End .
Range, .
, .
Errors , Errors
Error, .

11

260

Font Word,
Font,

(, , . .).

FormatConditions

, , .

Formula Range.
, . ,
( ) .
, .
:
Worksheets("1").Range("A3").Formula = "=$A$1+$A$2"
FormulaHidden
. .
HasFormula

().

Hidden . ,
,
.
Interior

, .
.

Item Range,
.
Locked

Name


Name. | .
Bookmark Word.
Next

. ,
, .

NumberFormat


. |
.

Offset Range . ,

Excel

261

,
:
Worksheets("1").Activate
ActiveCell.Offset(rowOffset:=-3, columnOffset:=-3).Activate
Orientation

.
. , , :

oRange.Orientation = -45
PageBreak
. :
Worksheets("1").Rows(50).PageBreak = xlPageBreakManual

Pivot...
PivotTable ( ). . 11.8.
QueryTable
QueryTable


, . QueryTable . 11.7.

Range

, ,
. .

Resize . ,
:
oRange.Resize(oRange.Rows.Count + 1, oRange.Columns.Count + 1).Select
ShrinkToFit
,
.
Style

Style, . ,
Style, | .
Text
String. Range .

Validation

Validation, .

Value

Range.
(, -

262

11

) . Value2,
Currency
Date.
WrapText

Range .
Activate()

AddComment() .
, . , .
| .
AutoFill() (, 1 2,
: 3, 4, 5 . .).
AutoFit()


, .
,
, .
AutoFormat()

, | .
BorderAround()

Clear... , , . .
Consolidate()

(
) , .

Copy() . , . Cut(),
.
CopyFromRecordset() ,
ADO.Recordset Excel,
.
DataSeries() ,
.

Excel

263

. ,
1 , .
Delete()

. ,
.
Dirty()

"".
. , Excel , .

Calculate().

Fill... (FillDown(), FillUp(), FillLeft(),



.

FillRight())
Find()

Range, ,
. , ,
,
. . FindNext() FindPrevious()
, Find(), .

GoalSeek()


Excel .
| .
Insert() ,
.
Justify() .
, ( ).
Merge() . .
UnMerge().
Parse() (, ).
PasteSpecial()

, Copy() Cut().
, , ( , , , . .).

11

264

PrintPreview()
.

PrintOut()

Replace()

, Find(). .

Select() . Selection Excel ,


Range,
.
Show() , .
ShowDependents() , ( )
. ShowPrecedents().
ShowErrors()

Sort()

.
. SortSpecial() .

Speak() , ( ,
). , Excel
.
SpecialCells() , Range, (,
, , , , ,
) . , Range, , :
Set oRange2 = oRange.SpecialCells(xlCellTypeBlanks)
oRange2.Select
',
SubTotal()

( ).

Table()

,
,
. .
TextToColumns() ,
. .

Excel

265

11.7. QueryTables
QueryTable

Application, Workbook, Worksheet Range. ,
ADO.Recordset Excel, VBA
. Excel ,
. ,

QueryTable, .
PivotTable Chart . 11.8
11.9.
QueryTable , . Excel
| | . QueryTable
, , Excel
(, , , . .). QueryTable
"" , Excel,
. , Excel
(, Change Worksheet), Access. ""
Excel.
, QueryTable
, QueryTables,
( Worksheet) . QueryTables ,
.
Add(),
QueryTable ( ). :
Connection QueryTable (
Variant). :

11

266

OLE DB ODBC (. . 9);


Recordset, ADO
DAO. Recordset,
QueryTable QueryTable.
QueryTable;
QueryTable (
);
;
Web- Microsoft Query (
DQY IQY). Excel | |
.
Destination
Range, ,

QueryTable.
.

SQL


SQL-, ODBC.

QueryTable.
, QueryTable
Recordset.
, ( Recordset),
,
Recordset. QueryTable Excel ( Recordset
Northwind.Customers, . 9.5):
Dim cn As ADODB.Connection
Set cn = CreateObject("ADODB.Connection")
cn.Provider = "SQLOLEDB"
cn.ConnectionString = "User ID=SA;Password=password;" _
& "Data Source = LONDON1;Initial Catalog = Northwind"
cn.Open
Dim rs As ADODB.Recordset
Set rs = CreateObject("ADODB.Recordset")
rs.Open "select * from dbo.customers", cn
Dim QT1 As QueryTable
Set QT1 = QueryTables.Add(rs, Range("A1"))
QT1.Refresh

Excel

267

QueryTable
QueryTable.Refresh(). QueryTable .
QueryTable .
BackgroundQuery

, , Excel
. True. False
, Excel -
.

CommandText

SQL, . . ,
. SQL ( ) .
QueryTable Recordset .
CommandType CommandText ( ,
SQL-, OLAP . .). Recordset .
Connection ,
Add() QueryTables.
Recordset .

Destination , Add(). Range, ,


QueryTable. QueryTable
.
EnableEditing

, QueryTable.
True. False,
QueryTable.
,
EnableRefresh
QueryTable, (


Recordset).

FetchedRowOverflow True, ,
, Excel (. . , 65 536 ). ,
,
.
FieldNames

. QueryTable.
True .

268

11

MaintainConnection

, . True . False,

.
Name QueryTable ( ,
). ExternalData_
.
Parameters

Parameters (
). , Recordset.
PreserveFormatting , (, . .)
QueryTable. .

PreserveColumnInfo

QueryType ,
QueryTable: Recordset, , SQL- . . -

.
Recordset

Recordset, QueryTable,
QueryTable ( Refresh()).
Refreshing

True . , CancelRefresh().
RefreshOnFileOpen ,
(
).
RefreshPeriod

, QueryTable .
0, . . .

RefreshStyle

, ,
QueryTable .

ResultRange , , QueryTable.
, Excel . ,
, QueryTable,
( ). ,

Excel

269

QueryTable Refresh().
, ,
. :
QT1.ResultRange.Select

QueryTable :
Set c1 = Sheets("1").QueryTables(1).ResultRange.Columns(1)
c1.Name = "Column1"
c1.End(xlDown).Offset(1, 0).Formula = "=SUM(Column1)"
RowNumbers

, , QueryTable.
QueryTable (),
, QueryTable.
SaveData
QueryTable,

, ,
Excel. True. False
, , .

SavePassword , (
ODBC). False, .
SourceDataFile

( Access, DBF
). - ( SQL
Server) Null.
Text... , QueryTable.
Web... , Web-.
Refresh(), CancelRefresh() Delete() QueryTable
- . ResetTimer() , SaveAsODC()
Microsoft Query ( Recordset, ).
QueryTable : BeforeRefresh AfterRefresh.
.

270

11

11.8.
( PivotTable)

(raw data) . ,
(
),
. .
,
, , .
: SQL-,
. Data Warehouse,
OLAP, .
OLAP ,
( , )
.
" ". ,
, ,
, . . ( SQL-)
, " -
- ".
, . OLAP .
SQL Server OLAP Microsoft,
Analysis Services. OLAP- Oracle, IBM, Sybase .
Excel . -
(
| ), - Pivot Table. , , , PivotTable.
, OLAP,
Excel , .
PivotTable
Panorama Software, Microsoft
Excel. PivotTable

Excel

271

Excel. , , . . , .
, ,
PivotCache, ,
OLAP. PivotCache
QueryTable. PivotTable
PivotCache. PivotCache
Add() PivotCaches:
Dim PC1 As PivotCache
Set PC1 = ActiveWorkbook.PivotCaches.Add(xlExternal)
PivotCaches , ,
, Add().
:
SourceType

, . PivotTable
Excel, , ,
PivotTable . . OLAP , (, Microsoft Analysis Services).
xlExternal.
SourceData

, ,
xlExternal. ,
PivotTable. Range.
PivotCache.
, QueryTable, .
.
ADOConnection

ADO.Connection, . .

Connection ,
QueryTable. ,
Recordset, , Web-, Microsoft Query.

OLAP (-

11

272

Recordset, ,
OLAP
).
FoodMart ( Analysis Services) LONDON
:
PC1.Connection = "OLEDB;Provider=MSOLAP.2;Data Source=LONDON1;" _
& "Initial Catalog = FoodMart 2000"

CommandText ,
, . , Sales , :
CommandType

PC1.CommandType = xlCmdCube
PC1.CommandText = Array("Sales")
LocalConnection (
cub), Excel. ,
"" . .
MemoryUsed ,
PivotCache. PivotTable PivotCache

, 0. ,
.
OLAP

True, PivotCache OLAP.

OptimizeCache

.
,
. OLE DB
.

PivotCache QueryTable, .
PivotCache CreatePivotTable().

( PivotTable). :
TableDestination .
Range,

.
TableName . ,
"1".

Excel

273

ReadData True, . , .
DefaultVersion . . .

:
PC1.CreatePivotTable Range("A1")

, .
, :
("",
), ;
, ;
,
(, -
- );
. (, ), .
,
, . ,
. .
CubeField. Orientation, ,
. ,
Customers :
PT1.CubeFields("[Customers]").Orientation = xlColumnField

Time :
PT1.CubeFields("[Time]").Orientation = xlRowField

Product :
PT1.CubeFields("[Product]").Orientation = xlPageField

, , Unit Sales ( ):
PT1.CubeFields("[Measures].[Unit Sales]").Orientation = xlDataField

274

11

, . . , ,
Quarter Time ( ). ,
, , ,
.
Time 1997 .
PivotField PivotItem:
PT1.PivotFields("[Time].[Year]").PivotItems("[Time].[1997]").
DrilledDown = True

11.9. ( Chart)
Excel .
, .
( ,
) .
Excel .
, Excel
( | ), - (Chart)
Chart. Excel
Diagram, (,
Excel
| ).
, Excel
.
Excel Chart.
:
Dim oChart As Chart

.
Add()
Charts:
Set oChart = ActiveWorkbook.Charts.Add(, ActiveSheet)

, ,
, . ,
.

Excel

275

( ) , SetSourceData(). Range (
). () ,
, . ,
:
oChart.SetSourceData Sheets("1").Range("A1:A10")

, ,
. . (
" ", . .
). ChartType,
73 . ,
, :
oChart.ChartType = xlLineMarkers


. Series , Values ( Range):
Dim oSeries As Series
Set oSeries = oChart.SeriesCollection.NewSeries
oSeries.Values = Worksheets(1).Range("B1:B10")

,
, , .
.
, ,
Location. ,
, :
oChart.Location xlLocationAsObject, "1"

, Location (xlLocationAsNewSheet
, xlLocationAsObject , . .
), , . , Excel, .
, Location, ,
-

276

11

, .
Chart
"Automation Error". Location
, . , , :
Dim oSeries As Series
Set oSeries = _
Worksheets(1).ChartObjects(1).Chart.SeriesCollection.NewSeries
oSeries.Values = Worksheets(1).Range("B1:B10")

, , .
Chart.
ChartArea

ChartArea, , , ( Font, Interior


. .). ,
, ,
PlotArea. .
, Top, Height,
Left Width ChartArea.
ChartTitle

,
( , Text,
Font, Border . .).
ChartType , . .
HasDataTable

True,
( ) , .
DataTable, . HasLegend,
HasPivotFields HasTitle.
Name

(
Excel).
"1", "2" . .
SizeWithWindow True, , . False.

Excel

277

Tab , .
Excel
( ). , , :
oChart.Tab.Color = RGB(0, 255, 0)
Visible

.
Chart.
Activate()

.
(. . ).

ApplyCustomType()


(
).

ApplyDataLabels()

. , ( . .).

Axes() , .
.
ChartWizard()

, .
,
.
Copy() (, ).
Location() Move().
CopyPicture() , .
, , Word .
Export(),
, , .
Delete()

Evaluate()

,
.

278

11

PrintOut() .
, .
Refresh()

, ,
.

Select() ( ). Deselect() (
<Esc>).
SetBackgroundPicture()

"" . , .

SetSourceData()

, , . .

Chart " "


, , , , . .,
.

11.10. Excel
Excel ,
.
.
.
CellFormat Excel
, , . .
, . .
FormatCondition.
ListObject ( Office 2003), (, ).
Excel SharePoint Portal Server.

Validation
.
Watch .
( | | ) , .

Excel

279

11:
Excel

:
, , ,
C:\Program Files\Microsoft Office\OFFICE11\SAMPLES. :



. ,
, ;

.
, ,
.
.

, .
Excel, :
1. Excel .
2. Excel :
" , "
. , .
,
, ,
False;
" "
.
. -

11

280

,
, .
( ) , SQL-
.
Excel ( , , ,
).

3.
:
" " , (
);
" " .
,
. 11.2.
, . 11.3.

. 11.2.

. 11.3.

Excel

281

11
1. Excel, ,
Excel. ,
.
2.
( )
Caption " ". Font, .
3. . Visual Basic
Click .
4. Tools References
Microsoft ActiveX Data Objects 2.1 Library.
5. Click , .
Private Sub CommandButton1_Click()
'
Cells.Select
Selection.Clear
' Connection
Dim cn As New ADODB.Connection
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=C:\Program Files\Microsoft Office\OFFICE11\SAMPLES\.mdb"
cn.Open
' Recordset
Dim rs As New ADODB.Recordset
rs.Open "SELECT [], [], [], []," _
& "[], [] FROM ", cn
' Recordset QueryTable
' , 4-
Dim QT1 As QueryTable
Set QT1 = QueryTables.Add(rs, Range("A4"))
QT1.Refresh
' QueryTable
Dim nRowCount As Integer
Dim oRange As Range

11

282
Set oRange = QT1.ResultRange
nRowCount = oRange.Rows.Count
' " , "
Range("G4").Value = " , "
Range("G4").Font.Bold = True
Range("G4").Columns.AutoFit
' " "
Range("H4").Value = " "
Range("H4").Font.Bold = True
Range("H4").Columns.AutoFit
' , G
' "" QueryTable
Set oRange = Range("G5", "G" & nRowCount + 3)
' ,
Dim oCell As Range
Dim sRowNumber As String
Dim cMoney As Currency
Dim cItogMoney As Currency
Dim cItogSklad As Currency

'
For Each oCell In oRange.Cells
'
sRowNumber = Replace(oCell.Address(True), "$G$", "")
'
If Range("E" & sRowNumber).Value > Range("D" & sRowNumber) And _
Range("F" & sRowNumber).Value = False Then
' G ( )
oCell.Value = (CInt(Range("E" & sRowNumber).Value) _
CInt(Range("D" & sRowNumber).Value))
' H ( )
cMoney = (CInt(Range("E" & sRowNumber).Value) _
CInt(Range("D" & sRowNumber).Value)) * _
CCur(Range("C" & sRowNumber).Value)
' H
Range("H" & sRowNumber).Value = cMoney
'
cItogMoney = cItogMoney + cMoney
End If

Excel

283

'
cItogSklad = cItogSklad + (Range("C" & sRowNumber).Value * _
Range("D" & sRowNumber).Value)
Next
'
Range("B" & nRowCount + 6).Value = " :"
Range("B" & nRowCount + 6).Font.Bold = True
Range("B" & nRowCount + 7).Value = " :"
Range("B" & nRowCount + 7).Font.Bold = True
Range("D" & nRowCount + 6).Value = cItogSklad
Range("D" & nRowCount + 6).Font.Bold = True
Range("D" & nRowCount + 7).Value = cItogMoney
Range("D" & nRowCount + 7).Font.Bold = True
' ...
Range("D" & nRowCount + 7).Select
'...
Range("D" & nRowCount + 7).Show
End Sub

12

Access
12.1.
Access
Access Word,
Excel Office. , Word, Excel, PowerPoint, Project . . , , , - . Access
, -
.
, Access
. Access
, :
( ),
, , . . .
, Access . Access ( MDB) , , . ,
, , Visual Basic, Delphi C++. Access, , , , , SQL Server, Oracle, IBM D2 . .
Access JET SQL,
Access.

Access

285

, , VBA
Access, ,
.
Access (, )
. . , Access
VBA Access, .
Access?
, Access
, .
, ,
, , Word Excel,
. Access
"" MDB-,
.
Access
, - , SQL Server, Oracle, IBM DB2. Microsoft, ( Access, FoxPro, Paradox
. .), 10 . ( ), ,
- .
( -
Access) :
, . .
, Web- (
);
, ;
VBA
() (,
);
,
( DTS), , . .

286

12

12.2.
Access
, (
Access - ), . , , , .
, :
, ,
, . .
, Microsoft Visio ERWin.
, .
, Jet,
Access, - , ,
. , , Web-, . .
- .
, , : , ,
, , , , . .
Access
. VBA , , , , , . . - Visio
ERWin.
,
. ,
VBA.
(. . 6).
.

Access

287

, ,
. , VBA.

12.3. Application,

Access Word Excel. , , Access
"" Microsoft, Word Excel,
.
, Access
Word Excel Application, Access.
Access
, .
Access :
Dim appAccess As Object
Set appAccess = CreateObject("Access.Application")
appAccess.Visible = True
MsgBox appAccess.Name

Word Excel,
( , ).
Access
Windows Explorer,
, mad, API . .
Access
, ,
Word, Excel . ., Access. Access MDB- ,
ADO, .
Application.
, Access Word
Excel.
AutomationSecurity . -

288

12

msoAutomationSecurityByUI , | . (msoAutomationSecurityForceDisable), msoAutomationSecurityLow,


.
BrokenReference , ( dll ).

Reference.
CodeContextObject , , (, . .)
. , , .
CodeData

. AllDatabaseDiagrams, AllFunctions, AllQueries,


AllStoredProcedures, AllTables AllViews. , AccessObject. ,
, , Excel. CodeData
:
For Each oTable In CodeData.AllTables
Debug.Print oTable.Name
Next
CodeProject

, CodeData, AllForms, AllReports,


AllMacros, AllModules AllDataAccessPages.
CommandBars

CommandBar, . .
Access.
,
Access.

CurrentData

CodeData CodeProject.
,
(SQL Server). CurrentProject.
CurrentObjectType ,
( -

CurrentObjectName

Access

289

). , ,
, . CurrentObjectType . ,
(
Nothing) , - True.
DataAccessPages

, Web- ( ) DataAccessPage.

DBEngine

DBEngine,
Jet,
Access. ,
, ,
. .
DoCmd DoCmd,

. " " Access


VBA. . 12.4. DoCmd
Application, :
Application.DoCmd.RunSQL "Delete from table1"
Forms Form.
AllForms :

;
AccessObject, AllForms, Form
.
MenuBar

( ), .
ShortcutMenuBar.
Modules Forms.
Module,
. Module
, AccessObject.
Printers Printer .

290

12

Printer ,
.
References

Reference
( ). .
Reports Forms Modules, Report.
Screen

Screen, Access: , , . . ( Word


Excel Active...
Application). .
UserControl

, Access:
( , , , Access
).

Version

Access (, ). Access 2003 11.0.


Visible

Access , , . Accesss, , ,
True.

Application ( ,
DoCmd).
.
AccessError()

. Access DAO, Err.Description "Application-defined or


object-defined error".
BuildCriteria()


, SQL-,
, . . .
CloseCurrentDatabase()
Access. ,
Access.

Access

291

CodeDb()

DAO.Database, , ( ,

, ). CurrentDb().
CompactRepair() Access
( ).
.
ConvertAccessProject()

, Access. acFileFormatAccess2 acFileFormatAccess2002.

CreateAccessProject()
Access ( SQL
Server). ,
NewAccessProject(),
OpenAccessProject().
CreateAdditionalData()

AdditionalData, ExportXML() XML-.


.

CreateControl()


. , .
CreateReportControl().
DeleteControl()
DeleteReportControl().
CreateForm()


Access . ,
. .
CreateReport().

CreateGroupLevel()

. , ,
,
.
CreateNewWorkgroupFile()

292

12

| | .
CurrentUser() . Admin.

D...
, SQL, Access:
DAvg(), DSum(), DCount(), DMax(), DMin() . .
( )
;
DLookup() ,
( , Word). , .
, ;
DFirst() DLast() ,
,
.
Echo() Access,
.
Eval()

.
,
VBA. Variant,
. :

Eval("1 + 1")

2, :
Eval("_()")

, . Eval() ,
, ,
, .
ImportXML()
( , , . .) XML- .
Access
Access, SQL Server, 6.5.
ExportXML()

Access

293

GetOptions() SetOptions() , | .
, <Enter>
( ), , :
Application.SetOption "Move After Enter", 2
hWndAccessApp()

, Windows
API. Access.

NewCurrentDatabase()


Access. OpenCurrentDatabase().
Nz()

. , (Null).
,
(, Memo), , .
Quit() Access. ,
.
RefreshDatabaseWindow()

. , . .

Run()

VBA 30 . ,
, Access , , DLL EXE.
RunCommand()


Access ( ,
). , Access, :
RunCommand acCmdAppMaximize
SysCmd()

: , Access, , . .

294

12

12.4. DoCmd
DoCmd " " Access.
Access
(actions), ( )
. , Access .
DoCmd , . Access DoCmd "" Application,
DoCmd.
Microsoft Application.
DoCmd
( ,
, ,
. . VBA).
:
<F1>. ( .
.
( DoCmd).
OutputTo() ( ), TransferText()
(), TransferDatabase() (), TransferSpreadsheet() () , -

( Excel, RTF, SNP,


TXT, DBF, ODBC . .).
. Word Excel.
RunSQL() (SQL), RunMacro() ()

SQL .

Open...() ( ...
, , , . .)
. (,
. .) . .

Access

295

,
,
.

12.5. Access VBA


( Form)
Access, , . Access ,
VBA
. Access, , , ,
VBA, Word Excel.
Access :
1. Access
. ,
. (, SQL Server
Oracle) , Access |
| .
2. .
Access , .
, , ,
.
.
3.
. , ,
(, Excel) . .
Access VBA?
, AccessObject, Access , , , ,
. , , , VBA . AllForms,

296

12

CodeProject CurrentProject. , Access :


Dim oA As AccessObject
For Each oA In CurrentProject.AllForms
Debug.Print oA.Name
Next

AllForms , , 0. :
Debug.Print CurrentProject.AllForms("1").IsLoaded

IsLoaded , (. . ).
.
Access Application.Forms Form. , , . , 1 , :
Debug.Print Application.Forms("1").Width

,
DoCmd.MoveSize(), (, , ):
DoCmd.MoveSize Width:=10000

: (, Click , ), ,
Form.
?
Word Excel , Access .
(. 12.1).
.
Access.
/. , , . 12.2.

Access

297

. 12.1.

. 12.2. Access

298

12

, , ,
, . , ,
Access <Shift>, .
- (, ), DoCmd.OpenForm().
:
DoCmd.OpenForm "1"

, , . DoCmd.OpenForm() ,
, (, ) . .
DoCmd.Close(). ,

, ,
Visible False.
. ,
.
( , , ,
), (
, , / . .).
Microsoft Access
. ,
(, ) , VBA (. 12.3).
( Access ), ,
.
Access ( VBA)
.

OLE- (, Word, Excel,
PowerPoint, , ),

Access

299

Access ( )
Access .

. 12.3.

, ,
OLE, Access . Word.
, Access
, . 12.4.
File Word,
. WordTemplate. ,
Word ,
.

12

300

. 12.4. Word

, ,
:
' oFrame
Dim oFrame As BoundObjectFrame
Set oFrame = oForm.Controls("WordTemplate")
' DLookup() File
' Templates, ( Num) = 1
oFrame = Application.DLookup("[File]", "Templates", "[Num] = 1")
' , . .
' Word ,
oFrame.Verb = acOLEVerbOpen
'
oFrame.Action = acOLEActivate
' Word oWord
Dim oWord As Word.Application
Set oWord = GetObject(, "Word.Application")
'
Dim oDoc As Word.Document
Set oDoc = oWord.ActiveDocument
' Word, ,
' ,

, ,
.

.
/
, .

Access

301

,
Access .
,

, .
.
Application.CreateControl(),
: , , , . .

Controls, :
cSumInNumber = oForm.Controls("SumNumber").Value

12.6. ,
, , Form
Access.
.
ActiveControl

,
. . , ,
Screen. Screen.ActiveControl , , :

MsgBox Screen.ActiveControl.Parent.Name

After... , -
(AfterInstall , AfterUpdate . .).
AllowAdditions

, .
, AllowDeletions,
AllowEdits. Allow...
.

12

302
AutoCenter

,
.

AutoResize

,
, .
, ,
.
Before... ,
After..., .
Bookmark . , Recordset ADO (. . 9). ( ) . ,
, ,
.
BorderStyle (, ).
Caption

ChartSpace

,
64 .
.

CloseButton

Close,
, . , , - (, ) .
ControlBox

Control ( , , . .). ,
, .
, , . , , . MinMaxButtons, ,
( ).

Controls

. Controls
.

Access

303

Count

.
, Controls, .

CurrentRecord

,
. .

CurrentView

. , : (Design View), (Form View)


(Datasheet View). . DoCmd.Close()
DoCmd.OpenForm() .
Cycle

, ,
<Tab>, :
( ),

() .

DataEntry


, .
.
DataSheet... ,
Datasheet View, . . .
DefaultControl

,
,
.
DefaultControl . , ,
,
DefaultControl. , , , . . :
'
Set oDefaultTextBox = oForm.DefaultControl(acTextBox)
oDefaultTextBox.FontSize = 12
' 12
Set oTextBox1 = CreateControl(oForm.Name, acTextBox, , , , 500, 500)

304

12

DefaultView

,
. ,
ViewsAllowed.
Dirty

True, ,
. , False. .
DividingLines

, ,
,
.

FetchDefaults ,
.
Filter

.
(, , ,
- , , ,
. .). ,
Where SQL.
FilterOn. , City
, "", :
oForm.Filter = "City = '-'"
oForm.FilterOn = True

,
.
SQL Server Oracle,
, ( ). ServerFilter
(. ).
Form , /.
FrozenColumns , . . ,
. .

.

Access

305

HasModule ,
( ). .
, VBA,
.

HelpContextId .

HelpFile

Hwnd Windows .
Windows API.
InputParameters

( ) ,
, .

KeyPreview

,
: ( )
, .
, , , :

Private Sub Form_Load()


Me.KeyPreview = True
End Sub
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Select Case KeyCode
Case vbKeyF5
MsgBox " F5!"
Case vbKeyF6
MsgBox " F6!"
End Select
End Sub
MenuBar

,

(. ShortcutMenuBar Toolbar).

Modal . True, . , ,
.
, Popup True.

306

12

Module

(. HasModule).
: ,

( ).
Moveable

,
.
: .
Name , , , .
NavigationButtons ,
( , , , . .)
.
NewRecord ,
. .

PaintPalette
Windows. Windows, Access . .
PaletteSource
.
ObjectPalette

On... (OnClick, OnClose, OnConnect . .)


, After... Before..., ,
Access VBA.
OnTimer , Access
, TimeInterval.
OpenArgs ,
DoCmd.OpenForm().
OrderBy

,
. , ,
, , :

oForm.OrderBy = "City DESC"


oForm.OrderByOn = True

Access

307

OrderByOn.
Page


.
. .
Pages, .
Painting

.
False . True.
Access ( Echo() DoCmd).
Picture... ( ) .
PivotTable

PivotTable,
. PivotTable Access Web- ( ActiveX) , . 11.8.

PopUp

, True, ,
(popup) Access.
Access . Modal.
Printer

( )
, (
Application). , , UseDefaultPrinter.
Properties

Property,
.
: Name ( ) Value ( ). ,
.
Prt...
. .
, .
RecordLocks

,

: 0

308

12

( , ); 1 , , , ; 2 ( 4 ),

.
RecordSelectors

, (Form
View) ,
.
Recordset

Recordset ADO (. . 9) DAO ( ,


), .
. ,
Recordset.
RecordsetType

Recordset,
, .

RecordSource


. , SQL.
Recordset, .

RecordSourceQualifier , Access SQL Server.


, .
ResyncCommand ,
, . ,
, , - .
ScrollBars , .
.
Section . ,
() ,
, :
oForm.Section(acPageHeader).Visible = False

Access

309

ServerFilter ,
(,
SQL Server Oracle).
, , Access
. ,
ServerFilterByForm True:
oForm.ServerFilter = "City = '-'"
oForm.ServerFilterByForm = True


OnOpen .
ShortutMenu False,
, .
ShortcutMenuBar

,
. ,
, .
Tag . , .
(,
).
2048 .
TimerInterval

( ),
( ).
Load .
Timer. (, , - , ), . .
Toolbar , . ,
.
UniqueTable ,
, ,
,
.
ViewsAllowed ,
: Form View, DatasheetView

12

310

( ).
.
( | | ).
Visible

, ,

.
WindowHeight, WindowLeft, WindowTop, WindowWidth

.
Form .
.
GoTo()

Move()

Recalc()
. ,
<F9>.
Refresh()

,
. (, ),
Requery().

Repaint() . ,
Painting.
SetFocus()

Undo()

,
( ). ,
Undo() .
,
.
VBA (, Load), , Query , , . . :
( Before...,
After..., On... . .) .
Project Explorer
, <F7>, (. 12.5).

Access

311

. 12.5.

12.7. ( Report)
Access ,
Report. Access , ,
(
, , , Crystal
Reports, Microsoft Reporting Services
VBA/ADO/Word VBA/ADO/Excel). Access , , Access,
, , SQL Server Oracle.
(, ) VBA.

.
Application.CurrentProject.AllReports ( AccessObject), Reports Report.
. -
, .
Application.CreateReport():
Dim oReport As Report
Set oReport = Application.CreateReport()

,
. -

312

12

( Access 1,
2 . .) , :
DoCmd.Close , , acSaveYes

, ,
. DoCmd.Close()
DoCmd.Save():
DoCmd.Save , "__"
DoCmd.Close

CreateReport() ,

. ,
. , , , .
Access ,
:
(Page Header) . ,
. ,
, , (
) ;
(Details), "" , . ,
;
(Page Footer) .
, .
/ ,
(. 12.6):
(Report Header) ,
.
: , , , ,
, , . .;
(Report Footer) ,
. , .
, .

Access

313

Access
.
.

. 12.6.

, ,
, Application.CreateReportControl().
( ), , ,
, ,
. ,

314

12


:
Set txt1 = CreateReportControl(oReport.Name, acTextBox, acDetail)
txt1.Name = "txtCustomerID"

, , , ,
.
DoCmd.OpenReport(). : , :
DoCmd.OpenReport "__"

, , , . - , :
DoCmd.OpenReport "__", acViewPreview

,
Controls. ,
:
oReport.Controls("__").Visible = False

, Report , Form, . 12.5. Report ,


Circle() ( ), Line() ( ), PSet()
( ) . ., .
,
. Image (),
.

12.8. Access
Access , VBA ,
Application, DoCmd, Form Report.
.
Access , , , , .

Access

315

(Data Access Pages).


Web-
(

Access Microsoft SQL Server). Web ActiveX, , . .
(, . .),
VBScript (
VBA).
, ,
ActiveX, Windows. ,
Click ADO.Recordset,
Word, Excel Access , . .
Access ( ), HTML-.
Access , .
Access DataAccessPage. Web,
. Web- WebOptions.
, -
(, ). , , .
FormatCondition,
FormatConditions.
GroupLevel
.
Module Access
. Modules,
Application.
Module

316

12

. ,
AddFromFile(), AddFromString(), CreateEventProc() . .
( ) Access References
Reference (). References
- ,
.

References.AddFromFile().
SmartTag - , Microsoft Office.
- , Office Microsoft.

12:
VBA Access
:
, Word (. . 10), ,
:
,
, .
, , Access;
:
( VBA), Normal.dot
DogovorTemplate.dot,
C:.
.
:
10 , Word, ,
Microsoft Access. Word, , Access. :

Access

. 12.7.

. 12.8.

317

12

318

, .
:
1. Access,
Word.
2. ,
. 12.7,
Word.
.
3. :

(. 12.8). .

12
1 ( ):
1. Microsoft Access | . .
C: Dogovors.mdb.
2.

.
(. 12.9).
.

. 12.9.

3.
.
, . 12.1.
12.1.

( )

10

30

Access

319

12.1 ()

50

50

50

50

100


.
4.
,
.
" ",
. ,
C:\DogovorTemplate.dot, 10. OK,
.
5. , ,
. ,
1, .
2 ( Access ):
1.
.
.
2. : ,
.
3. .
4. .
5. , -

12

320

6.
7.

8.

9.

.
.

.

. ,
. OLEObject1,
.
: . cmdCancel,
cmdDog.
.
,
(, , . .). , , , . 12.10.

. 12.10.

Access

321

10. Tools | References


Microsoft Word 11.0 Object Library.
11. .
OK. Click :
Private Sub cmdCancel_Click()
Form.Undo
End Sub

12. Click
:
Private Sub cmdDog_Click()
Dim dDate As Date
Dim , , , , , _
As String
'
If Form.Controls("").Value <> "" Then _
dDate = Form.Controls("").Value
If Form.Controls("").Value <> "" Then _
= Form.Controls("").Value
If Form.Controls("").Value <> "" Then _
= Form.Controls("").Value
If Form.Controls("").Value <> "" Then _
= Form.Controls("").Value
If Form.Controls("").Value <> "" Then _
= Form.Controls("").Value
If Form.Controls("").Value <> "" Then _
= Form.Controls("").Value
If Form.Controls("").Value <> "" Then _
= Form.Controls("").Value
'
Dim oBOF As BoundObjectFrame
Set oBOF = Form.Controls("OLEObject1")
oBOF = DLookup("[]", "", "[] = 1")
oBOF.Verb = acOLEVerbOpen
oBOF.Action = acOLEActivate
' Word
Dim oWord As Word.Application

12

322
Set oWord = GetObject(, "Word.Application")
Dim oDoc As Word.Document
Set oDoc = oWord.ActiveDocument
oWord.Visible = True
oWord.ActiveWindow.WindowState = wdWindowStateMaximize
oDoc.Activate
'
oDoc.Bookmarks("bNumber").Range.Text =
oDoc.Bookmarks("bCity").Range.Text =
oDoc.Bookmarks("bDate").Range.Text = dDate
oDoc.Bookmarks("bOrg").Range.Text =
oDoc.Bookmarks("bTitle").Range.Text =
oDoc.Bookmarks("bPerson").Range.Text =
oDoc.Bookmarks("bLaw").Range.Text =
End Sub

13. .
3 ( ):
1. Access .
2. ,
/
(. 12.11).

. 12.11.

Access

323

3. OK.
. , ,
, .

,
<Shift>.

13

Outlook
13.1. Outlook
Outlook ( , Outlook
Express) .
. ,
, Microsoft
(Personal Information Manager, PIM).
, . .
. Outlook
( ), (, Microsoft Project).
,
.
Outlook, (
Exchange Server)
. , , , , .
:
Outlook Exchange ,
( , ,
. .). , ,
:
, .

Outlook

325

, ,
. ,
.
Outlook ,
. , , ,
.
, , .
. Outlook .
, Outlook
, . , , ,
Exchange Server (
Exchange Server
Outlook). , (, ),
,
- , .
. , , (, Microsoft Project Project Server),
, , Outlook
. ,
() , . .
.
Office,
Outlook . . ,
, .
, .
, Outlook
. OutlookExchange Server -

326

13

, collaboration development
. ,
, .
, :
. : - , , , .
, ,
.
. Outlook
-:
1. -
Outlook
.
2. , ( , ).
3. , , .
4. (,
,
) .
5. , , , .

. , , , ( ),
. , , Outlook Exchange Server.
, : Outlook . -

Outlook

327

Outlook
, , (
VBA Access).
Outlook:
| , (,
) .
(. 13.1), , : , ( | )
. .

. 13.1. Outlook

, CommandButton1, , :
1. ( );

328

13

2. :
Function CommandButton1_Click()
MsgBox " Outlook"
End Function

,
. , , , .
3. , , .
, , , VBA ( VBScript).
Outlook ,
. , Outlook Exchange Server: , , ,
. . ,
.
Outlook . , Microsoft, C:\Program
Files\Microsoft Office\OFFICE11\1049\OLFM10.CHM, www.slipstick.com.
Outlook VBA, VBA
.
, VBA,
:
;
(, ,
), , ;
, ,
Excel Exchange;
;
- .
Outlook .

Outlook

329

13.2.
Outlook
Outlook ,
.
,
Outlook, . , Word ( , , Normal.dot),
Excel , Access MDB.
Outlook
PST, .
, , VBA Outlook
:
Outlook . , .
:
,
Project Explorer (. 13.2);

. 13.2.

330

13

, ,
Word Outlook,
Outlook .
VBA Outlook , Outlook
. Outlook
(, Exchange PST ). Outlook
, .
Outlook
MAPI (Messaging Application Programming Interface,
), Outlook
,
. Namespace,
, . 13.4. ,
Outlook Inbox ()
(
Microsoft Outlook 11.0 Object Library):
Dim oOutlook As New Outlook.Application
Set oNameSpace = oOutlook.GetNamespace("MAPI")
Set oInbox = oNameSpace.GetDefaultFolder(olFolderInbox)
oInbox.Display

Outlook . , Office Item () .


Outlook : Item ,
Outlook: ( MailItem), (
ContactItem), ( Appointment) . . !
Outlook . Outlook
, ,
,
. , Outlook
( VBA).
, Outlook
, . ( Outlook Object Model Guard) VBA. .

Outlook

331

Outlook CDO,
Windows 2000, XP 2003.
Outlook ,
Office (
New CreateObject()) Outlook,
Application.
.
, Outlook,
Access, , .
.

13.3. Application,

Office, Outlook Application. Outlook
(. ).
Application Outlook ( ,
Namespace).
Application .
Explorers Explorers
Explorer, Outlook,

. Explorer , Outlook
, , ,
(Explorer.Activate()) (Explorer.Close()).
ActiveExplorer() Application ,
, GetExplorer()
Explorer Outlook ( ).
Inspectors

, Explorers. Inspectors Inspector. ,


Inspector Outlook,
Explorer, (,
). Inspector , Explorer, Explorer. ActiveInspector() GetInspector()
Application.

332

13

Reminders Reminders
Reminder, .

, :
Dim oOutlook As New Outlook.Application
Dim oReminder As Outlook.Reminder
For Each oReminder In oOutlook.Reminders
oReminder.Dismiss
Next
Session

Namespace, (. .
MAPI). GetNamespace().
Namespace . 13.4.
Session
Namespace Outlook.
Outlook.Application.
Active...
Explorer Inspector.
AdvancedSearch()

.
Outlook ( ). Search Results
. 13.7.
CopyFile()

Outlook.
, , Exchange Server SharePoint Portal Server.

CreateItem() , .
Outlook. ,
, , , :
Dim oOutlook As New Outlook.Application
Dim oContact As Outlook.ContactItem
Set oContact = oOutlook.CreateItem(olContactItem)
oContact.FirstName = " "
oContact.Email1Address = "info@askit.ru"
oContact.Save
oContact.Display

Outlook

333

, Excel. Outlook .

.
:
Set oContact = Nothing
CreateItemFromTemplate() Outlook,
Outlook oft.
GetNameSpace()

, , ,
VBA Outlook.
MAPI. .

IsSearchSynchronous()

(. . 13.7).
Quit()

Outlook.

13.4. Namespace
, Outlook
, , Outlook,

. .
Outlook
MAPI, ,
- . Outlook
,
"" Application.
Namespace, :
1. GetNameSpace() Application:
Set oNameSpace = Application.GetNamespace("MAPI")

2. Session Application:
Set oNameSpace = Application.Session

, .

13

334

Namespace
: ,
, , . , Namespace Exchange,
Exchange.
Namespace . , Outlook
-
. . ""
. , ,
Web- , ,
, , . .
?
, .
Word Excel,
. , , Microsoft Outlook 11.0
Object Library.

VBA CommandButton1.
:
Outlook.Items General
Declarations . :
Public WithEvents oItems As Outlook.Items

oItems .
Click() .
, , :
Private Sub CommandButton1_Click()
' Outlook
Dim oOutlook As New Outlook.Application
' : , oItems
' Inbox Outlook
Set oItems = _
oOutlook.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items

Outlook

335

'
Dim oNamespace As Outlook.NameSpace
Set oNamespace = oOutlook.GetNamespace("MAPI")
oNamespace.SyncObjects(" ").Start
End Sub
'
Private Sub oItems_ItemAdd(ByVal Item As Object)
MsgBox Item.Subject
End Sub

Microsoft ItemAdd ,
,
, .
, Exchange Server,
Exchange . , ,
. , Exchange Server ,

- . Exchange, , , UNIX SendMail,
PostFix, CommunigatePro . . ,
, Outlook .
, ,
Namespace.
AddressLists AddressLists, AddressList, ,
. , (, Outlook ):
Dim
Dim
Dim
Set
For

oOutlook As New Outlook.Application


oNameSpace As Outlook.NameSpace
oAddress As Outlook.AddressList
oNameSpace = oOutlook.GetNamespace("MAPI")
Each oAddress In oNameSpace.AddressLists
Debug.Print oAddress.Name
Next

AddressList AddressEntries
AddressEntry, .
""
, , . .

336

13

Outlook ,
AddressLists ,
( ContactItem).
Outlook Exchange Server,
.
CurrentUser

. ( Outlook)
Recipient, , , , ,
( ). ,
:
Set oNameSpace = Application.GetNamespace("MAPI")
Set oRecipient = oNameSpace.CurrentUser
Debug.Print oRecipient.Address

, : Outlook?
, , . :
<Shift>+<Tab> <Enter> ( )
Outlook, . WshShell
Windows Script Host,
VBA , ""
Debug.Print, .
Windows API.
ExchangeConnectionMode . , Outlook Exchange
Server Exchange Server .
Folders , , Namespace. Folders MAPIFolder,
Outlook ( , ,
Folders,
Outlook). , Outlook
,
Items (-

Outlook

337

, , . .). Folders MAPIFolder .


Offline

, Outlook
.

SyncObjects
SyncObject ( ). -

(,
Outlook | /).
, SyncObject, .
, Outlook, Namespace .
AddStoreEx() PST
Outlook . , , Outlook
. AddStoreEx() ,
. PST-
RemoveStore().
AddStore()

CreateRecipient()
Recipient.
GetSharedDefaultFolder(). -

.
Dial()

, . , .

GetDefaultFolder()
MAPIFolder

,
( ) Outlook: , , , . . , ( ) :
Dim oOutlook As New Outlook.Application
Set oNameSpace = oOutlook.GetNamespace("MAPI")
Set oInbox = oNameSpace.GetDefaultFolder(olFolderContacts)
oInbox.Display

Get...FromID() ,
, -

338

13

CDO ( . 13.8),
Outlook.

GetSharedDefaultFolder()
GetDefaultFolder(),

,
, Outlook
. , , Inbox .
Logon() MAPI (. . Exchange Server). , , , . .
Logoff().
PickFolder() . OK,
MAPIFolder .

13.5. Folders MAPIFolder


, Outlook, , , . . Outlook
( , ). Outlook MAPIFolder, Folders.
Outlook . ( , ,
. ., , , ,
, , Mailbox Administrator). Folders, , Folders Namespace (. . 13.4):
Dim
Dim
Dim
Set
For

oOutlook As New Outlook.Application


oNameSpace As Outlook.NameSpace
oFolder As Outlook.MAPIFolder
oNameSpace = oOutlook.GetNamespace("MAPI")
Each oFolder In oNameSpace.Folders
Debug.Print oFolder.Name
Next

, Inbox, GetDefaultFolder() Namespace:

Outlook

339

Dim oOutlook As New Outlook.Application


Dim oNameSpace As Outlook.NameSpace
Dim oFolder As Outlook.MAPIFolder
Set oNameSpace = oOutlook.GetNamespace("MAPI")
Set oFolder = oNameSpace.GetDefaultFolder(olFolderInbox)
Debug.Print oFolder.Name


Outlook ( ),
( ) - , , , , .
Outlook , , , , . ,
:
Public Sub StartProc1()
Dim oOutlook As New Outlook.Application
Dim oNamespace As Outlook.NameSpace
Dim oChildFolder As Outlook.MAPIFolder
Set oNamespace = oOutlook.GetNamespace("MAPI")
'
' DoFolder()
For Each oChildFolder In oNamespace.Folders
DoFolder oChildFolder
Next
End Sub
'
'
Public Sub DoFolder(ByVal oFolder As MAPIFolder)
Dim oChildFolder As Outlook.MAPIFolder
For Each oChildFolder In oFolder.Folders
Debug.Print oChildFolder.Name
' DoFolder()
DoFolder oChildFolder
Next
End Sub

Folders
MAPIFolder.

340

13

Folders ,
(Count, Item(), Add(), Remove() . .). MAPIFolder
.
MAPIFolder .
AddressBookName .
( ).
CurrentView

View, , . MAPIFolder .
DefaultItemType (
) ( , . .). .
- (, , ).
DefaultMessageClass , DefaultItemType,
, . ,
.
Description .
Outlook .
EntryID

,
MAPI- (,
Outlook Exchange Server)
.

FolderPath Outlook, , "\\ \".


Folders

, . , , .

InAppFolderSyncObject , ( SyncObject)
Application Folders. (
| /) ,
.
IsSharePointFolder

,
Windows SharePoint Services

Outlook

341

( ). .
Items .
Items .

. 13.6.
Name

, , .

ShowAsOutlookAB

,
. True. , -
.
ShowItemCount

,
Outlook : ,
.

StoreID

MAPI- ,
.
(516 ). , , Exchange.
UnReadIemCount

. .

Views

View ( ),
.

WebViewOn

HTML ( Outlook ). ,
, WebViewURL. .
, CopyTo(), MoveTo(), Delete(), AddToFavorites(),
Display(), . GetExplorer()
Explorer, Outlook.

13.6. Items
Outlook
( , , . .) , -

13

342

Outlook.
.
Items
MAPIFolder, Items.
.
. 16
Outlook.
AppointmentItem , Outlook
. .
ContactItem . .
DistList ,
. .
DocumentItem

,
Outlook
Outlook. DocumentItem , , Word,
Excel, ZIP-, Acrobat Reader PDF, EXE-
. . , .
Outlook ( PST,
Exchange Server), , .
Outlook. , , , Outlook
, .
JournalItem

MailItem

.
.

MeetingItem (
). , , , Inbox.
(
AppointmentItem, ).
NoteItem

( ).
.

Outlook

343

PostItem

.
, .
MailItem , :
;
Send() Post().
RemoteItem .
( , , )
, 256 .
, Outlook
Exchange Server ( ). OST (. . Exchange Server
MAPI POP3/IMAP4),
.
ReportItem ,
:
(non-delivery report),
, .
,
.
TaskItem

TaskRequestAcceptItem, TaskRequestDeclineItem, TaskRequestItem, TaskRequestUpdateItem , -

.
.
, MailItem, ContactItem DocumentItem. .
. ,
Outlook ,
. , , , ,
. . : AppointmentItem,
ContactItem, MailItem TaskItem, . .
Outlook. ,
, , . ,

13

344

Outlook
:
Dim oOutlook As New Outlook.Application
Dim oMessage As Outlook.MailItem
'
Set oMessage = oOutlook.CreateItem(olMailItem)
'
oMessage.To = "Administrator@nwtraders.msft"
'
oMessage.Subject = " VBA"
' . Body ,
' .
' HTML RTF
oMessage.Body = " "
'
oMessage.Attachments.Add ("C:\installlog.txt")
'
oMessage.Send

, , . 13.3. ,
, .

. 13.3. Outlook

?
:
, VBA Outlook ( Outlook).
.
,
;

Outlook

345


Outlook,
VBA .
Outlook Redemption.
http://
www.dimastr.com/redemption. , , , , ;
.
Microsoft , VBA
VBScript . ,
Windows API (, , MAPI). VBA (C++
Delphi), VBA
API. , API .
Outlook
http://www.mapilab.com/ru/support/articles
/vb_outlook_security_1.html ( );
( )
CDO,
Windows 2000, XP 2003. . 13.8.
Outlook. (, ContactItem 100 ),
.
. ,
,
. , Outlook , , ,
Locals. . ,
ContactItem
.
, , ,
, , " " (. 13.4).

13

346

. 13.4.

, , ,
. , , ( Outlook) :
Dim oNamespace As NameSpace
Dim oFolder As MAPIFolder
Dim oContactItem As ContactItem
Set oNamespace = Application.GetNamespace("MAPI")
Set oFolder = oNamespace.GetDefaultFolder(olFolderContacts)
Set oContactItem = oFolder.Items("1")
Stop

Stop ,
.
, , ( View) Locals.
(. 13.5).
, oContactItem
, " ".

Outlook

,
13.6).

347

EMail1DisplayName (.

. 13.5. Locals

. 13.6. Locals


Item.

13.7. Outlook
Outlook:
Application Namespace Folders/MAPIFolder _.
,
.
Explorer Outlook.
( View). , , :
Dim oNamespace As NameSpace
Dim oFolder As MAPIFolder
Dim oExplorer As Explorer

348

13

Set oNamespace = Application.GetNamespace("MAPI")


Set oFolder = oNamespace.GetDefaultFolder(olFolderContacts)
Set oExplorer = oFolder.GetExplorer()
oExplorer.Display
oExplorer.CurrentView = " "

, ( View), :
Dim oNamespace As NameSpace
Dim oFolder As MAPIFolder
Dim oView As View
Set oNamespace = Application.GetNamespace("MAPI")
Set oFolder = oNamespace.GetDefaultFolder(olFolderContacts)
For Each oView In oFolder.Views
Debug.Print oView.Name
Next

Explorer ,
. ,
, , :
For Each Item In Application.ActiveExplorer.Selection
If TypeName(Item) = "MailItem" Then Debug.Print Item.Subject
Next

- Explorer Inspector.
Outlook,
( , . .). , Explorer, , ,
Outlook.
Outlook.
Outlook . , . . 13.5,
Folders MAPIFolder. ,
Outlook. Search Results,
AdvancedSearch() Application
AdvancedSearchComplete (

Outlook

349

100 , ,
). .
AdvancedSearch(). :
Scope , . . . ,
, Folders NameSpace MAPIFolder. ;
Filter . ,
. SQL Server (
LIKE), , , . , , -
, Microsoft :

http://msdn.microsoft.com/library/en-us/cdosys/html
/_cdosys_schema_mailheader.asp;
http://msdn.microsoft.com/library/en-us/cdosys/html
/_cdosys_schema_httpmail.asp.
, (
, ""),
:
"urn:schemas:mailheader:subject LIKE '%%'"

"", :
"urn:schemas:mailheader:subject = ''"
SearchSubFolders True,
.
Tag

. , ,
.
AdvancedSearch() Search:
Dim oSearch As Search
Set oSearch = Application.AdvancedSearch("Inbox", _
"urn:schemas:mailheader:subject LIKE '%%'", True, "Search1")

, ,
AdvancedSearch(), , -

13

350

.
AdvancedSearchComplete. Project Explorer
Microsoft Office Outlook Objects,
ThisOutlookSession
Application
AdvancedSearchComplete() (. 13.7).

. 13.7. AdvancedSearchComplete

Search
Results ( ). Item
Outlook ( MailItem),
.

13.8.
CDO
- Outlook , ,
, ,
. , , Outlook. (
. 13.6), , CDO, .
Outlook.
CDO (Collaboration Data Objects, )
Exchange Server. -

Outlook

351

, CDO, : Microsoft CDO for Exchange 2000 Library, Microsoft Office. , ,


Tools | References
VBA.
CDO :
Dim oMyMail As New CDO.Message
oMyMail.To = "Administrator@nwtraders.msft"
oMyMail.From = "Administrator@nwtraders.msft"
oMyMail.Subject = "Hello from CDO"
oMyMail.TextBody = "Our letter"
oMyMail.AddAttachment "C:\1.txt"
oMyMail.Send


, Exchange
Server 2000/2003 Internet Information Server
SMTP,
C:\Inetpub\mailroot\Pickup ( ),
Exchange Server IIS. ,
SMTP. Send() :
oMyMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2

"http://schemas.microsoft.com/cdo/configuration/sendusing"
, .
1, Pickup.
:
omyMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"smtp.YourServer.com"

CDO.Configuration:
oMyMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1

1 , ,
0 (), 2 NTLM.

352

13

:
oMyMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusername") = _
"YourLogin@YourDomain.com"
oMyMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendpassword") = _
"Password"


( 25), SSL -:
oMyMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 2525
oMyMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
oMyMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") =
60

, , :
oMyMail.Configuration.Fields.Update

Send():
oMyMail.Send

(,
, ),
:
oMyMail.TextBodyPart.Charset = "windows-1251"

, SMTP Pickup . POP3,


IMAP4, MAPI, ,
( Outlook)
. CDO
Microsoft CDO 1.21 Library. MAPI (. .
Exchange Server),
Exchange Server .
, , Microsoft
CDO 1.21 Library ( Tools | References). , , , :

Outlook

353

Dim oSession As New MAPI.Session


Dim oFolder As MAPI.Folder
Dim oMessage As MAPI.Message
'"Outlook" . ,
' .
'
oSession.Logon ("Outlook")
Set oFolder = oSession.Inbox
For Each oMessage In oFolder.Messages
If oMessage.Unread = True Then Debug.Print oMessage
Next

MSDN.

13:
Outlook
:

,
. ,
, ,
Outlook.
:
Outlook ImportContacts(), :
1. Outlook
.
2.
C:\Program Files\Microsoft Office\OFFICE11\SAMPLES\.mdb.
,
, .

, , Exchange Server ,
.

Outlook. VBA .

13

354

13
1. Outlook <Alt>+<F11>,
Visual Basic.
2. Tools | References
Microsoft ActiveX Data Objects 2.1 Library.
3. Project Explorer 1 Insert | Module. Module1.
4. ImportContacts()
. :
Public Sub ImportContacts()
Dim oFolder As MAPIFolder
Dim oNameSpace As NameSpace
Dim oContact As ContactItem
Set oNameSpace = Application.GetNamespace("MAPI")
'
Set oFolder = oNameSpace.Folders(" ").Folders. _
Add(" ", olFolderContacts)
'
Dim cn As New ADODB.Connection
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=C:\Program Files\Microsoft
Office\OFFICE11\SAMPLES\.mdb"
cn.Open
' Recordset
Dim rs As New ADODB.Recordset
rs.Open "", cn
' Recordset
Do While rs.EOF = False
'
Set oContact = Application.CreateItem(olContactItem)
' Recordset
oContact.CompanyName = rs.Fields("")
oContact.FullName = rs.Fields("")
oContact.BusinessTelephoneNumber = rs.Fields("")
'
oContact.Move oFolder
oContact.Save

Outlook
'
Set oContact = Nothing
' Recordset
rs.MoveNext
Loop
End Sub

355

14

PowerPoint
PowerPoint (. .
, ).
VBA PowerPoint
, Word Excel, . PowerPoint
,
. . , PowerPoint ,
, . .
PowerPoint , , .
(, ) .
PowerPoint:
(, );
, . .
, .
PowerPoint :
Application , Word Excel;

PowerPoint

357

Presentations Presentation.
, Workbook Excel;
Presentation Slides Slide. Worksheet Excel;
Slide Shapes Shape.
Shape ( 22 : , , , , , . .).
Application, Presentation, Slide Shape
PowerPoint.
PowerPoint ( ), PowerPoint
.
, PowerPoint JPG-, C:\Slides (,
). JPG- , , DSCN2440.JPG DSCN2480.JPG.
,
. . , JPG- (
), .
, VBA PowerPoint
PowerPoint, , VBA, ,
Word Excel. ,
.
:
1. Word Excel,
.
:
Microsoft PowerPoint 11.0 Object Library (msppt.olb) PowerPoint;
Microsoft Scripting Runtime (ScrRun.dll) ,
FileSystemObject
. ,
Windows 2000, .
.

358

14

2. , , PowerPoint.
, Word, Excel, Access . .:
Dim oApp As New PowerPoint.Application
oApp.Activate
oApp.Visible = msoTrue

3. :
Dim oPresent As PowerPoint.Presentation
Set oPresent = oApp.Presentations.Add()

, Word.
, PowerPoint.
4. .
, C:\Slides.
, .
Scripting Runtime ( Office, ) :
Dim oFSO As New Scripting.FileSystemObject
Dim oFolder As Scripting.Folder
Dim oFile As Scripting.File
Set oFolder = oFSO.GetFolder("C:\Slides")
For Each oFile In oFolder.Files
...
Next

, , :
MsgBox oFile.Name

,
.
5. - . Add() Slides. PowerPoint 2003
(
, VBA ),
,
: (
1), ppSlideLayout ( ), .
, :

PowerPoint

359

Dim nCounter As Integer


nCounter = 1
For Each oFile In oFolder.Files
Set oSlide = oApp.ActivePresentation.Slides.Add(nCounter, _
ppLayoutBlank)
...
nCounter = nCounter + 1
Next

6.
. AddPicture() Shapes :
oSlide.Shapes.AddPicture FileName:="C:\Slides\" & oFile.Name, _
LinkToFile:=msoFalse, SaveWithDocument:=msoTrue, _
Left:=10, Top:=10, Width:=700, Height:=520

FileName .
. LinkToFile , (msoFalse)
(msoTrue). ,
, ( PPT). SaveWithDocument ,
( ). Left, Top, Width
Height , (
).
,
5. , :
oFile.Delete

:
Dim oApp As New PowerPoint.Application
oApp.Activate
oApp.Visible = msoTrue
Dim oPresent As PowerPoint.Presentation
Set oPresent = oApp.Presentations.Add()
Dim oFSO As New Scripting.FileSystemObject
Dim oFolder As Scripting.Folder
Dim oFile As Scripting.File

14

360

Set oFolder = oFSO.GetFolder("C:\Slides")


For Each oFile In oFolder.Files
Set oSlide = oApp.ActivePresentation.Slides.Add(nCounter, _
ppLayoutBlank)
oSlide.Shapes.AddPicture FileName:="C:\Slides\" & oFile.Name, _
LinkToFile:=msoFalse, SaveWithDocument:=msoTrue, _
Left:=10, Top:=10, Width:=700, Height:=520
oFile.Delete
Next


.
, ,
. . . , , - . " "
. - . ,
:
ActiveWindow.Selection.SlideRange.Shapes.AddPicture ...

, , . .

14:


:
PowerPoint,
" , 2005" (. 14.1).

, , VBA, , Word Excel, . PowerPoint.

PowerPoint

. 14.1.

14
, , :
Public Sub InsertCopyRight()
Dim oSlide As Slide
Dim oShape As Shape
'
For Each oSlide In Application.ActivePresentation.Slides
' ( Shape)
' Left, Top, Width
'Height
Set oShape = oSlide.Shapes.AddTextbox(_
msoTextOrientationHorizontal, 500, 510, 210, 40)
' TextFrame TextRange
oShape.TextFrame.TextRange.Text = Chr(169) & _
" , 2005"
'
oShape.TextFrame.TextRange.Font.Size = 12
oShape.TextFrame.TextRange.Font.Bold = msoTrue
Next
End Sub

361

15

Project
15.1. Project
Professional. Application
Office Project. . ,
Project ( Project Server), , ,
, .
Project Professional 2003, Office, Application
. Application Project
Professional:
Dim pj As New MSProject.Application
pj.Visible = True
MsgBox pj.Name & " " & pj.Version

Office,
Microsoft Project 11.0 Object Library
( Tools | References).
Project, Application . , , VBA ,
Application. , VBA Project :
Application.ActiveProject.Visible = True

ActiveProject.Visible = True

Project

363

Project Professional ,
Word, Excel, PowerPoint Office.
. Project
Server,
Project Server.
VBA. , , Project,
, , Word
. ,
.
:
Module1
, .

15.2. Projects,
Project
, Application ( , Projet, ), .
, Add()
Projects:
Dim oProj As Project
Set oProj = Projects.Add()

Add()
.
,
:
1. ( mpp).
:
Application.FileOpen "D:\Project1.mpp"

(
FileOpen() ):
For Each Project In Application.Projects
If Project.Name = "Project1.mpp" Then
Set oProj = Project
Exit For
End If

364

15

Next
MsgBox oProj.Name

2. Project Server.
, , FileOpen()
:
Application.FileOpen "<>\."
"<>\." , , Project
Server. Project. Project ,
, . Profiles
Application, ,
, ( ,
), . . , ,
, , Project
Server, . Project
Server
Project Professional ( ), .

("<>\.")
, Project Server ( SaveAs() Project).
, : , .
:
Dim oTask As Task
Set oTask = oProj.Tasks.Add(" 1")

Task ,
. ,
ActualStart, ActualFinish, ActualDuration . . ,
,
.
, SetTaskField() Application.
, (
, ), Task.ID. , :
Application.SetTaskField "", Date, False, False, oTask.ID
Application.SetTaskField "", "2", False, False, oTask.ID

Project

365

, ,
.

XML- .
.
.
.
, Project Server.
( ).
Project Data Services, VBA.
:
Application.EnterpriseResourcesOpen EUID:="", OpenType:=pjReadWrite

( ), . ( )
, "
", , .

Application.EnterpriseResourcesImport(),
ID .
. .
Project Resources Add(),
Resource. ,
. SetResourceField(),
:
Dim oRes As Resource
Set oRes = oProj.Resources.Add(" ")
Application.SetResourceField "", "", False, False, oRes.ID

, , :
oRes.StandardRate = 100

.
Application.EnterpriseResourceGet(), ID ID . ID -

15

366

,
.
. :
Assignments
Add():
oTask.Assignments.Add oTask.ID, oRes.ID

Application.ResourceAssignment().
,
, ( , );

SetTaskField():
SetTaskField Field:=" ", Value:=" [100%]"

, , .
, ,
.
.
(,
oRes.EnterpriseText1 = " "),
SummaryTask:
ActiveProject.ProjectSummaryTask.EnterpriseCost1 = "500.00"

15:


:
, "" .mpp :
;
:
.
100 . . 2 (16 ). ;

Project

367

.
150 . . 2 (16 ). 2 .
800 . . ;
. 125 . . 1 (8 ).
2 100 .
;
.

15
, Project, :
Public Sub CreateProject()
Dim oProject As Project
Dim oTask As Task
Dim oRes, oResMaterial As Resource
Dim sID As String
Dim oA As Assignment
'
Set oProject = Application.Projects.Add()
'
Set oTask = oProject.Tasks.Add(" ")
Application.SetTaskField "", Date, False, False, oTask.ID
Application.SetTaskField "", "2", False, False, oTask.ID
'
Set oRes = oProject.Resources.Add(" ")
oRes.Type = pjResourceTypeWork
oRes.StandardRate = 100
'
oTask.Assignments.Add oTask.ID, oRes.ID
' ,
'
sID = oTask.ID
'
Set oTask = oProject.Tasks.Add(" ")

15

368

oTask.Predecessors = sID
Application.SetTaskField "", "2", False, False, oTask.ID
Set oRes = oProject.Resources.Add(" ")
oRes.Type = pjResourceTypeWork
oRes.StandardRate = 150
'
Set oResMaterial = oProject.Resources.Add("")
oResMaterial.Type = pjResourceTypeMaterial
oResMaterial.StandardRate = 800
oResMaterial.MaterialLabel = ". "
'
oTask.Assignments.Add oTask.ID, oRes.ID
'
Set oA = oTask.Assignments.Add(oTask.ID, oResMaterial.ID)
' ... !
' 120 (2 ), . . 2
oA.Work = 120
'
sID = oTask.ID
'
Set oTask = oProject.Tasks.Add(" ")
oTask.Predecessors = sID
Application.SetTaskField "", "1", False, False, oTask.ID
Set oRes = oProject.Resources.Add(" ")
oRes.Type = pjResourceTypeWork
oRes.StandardRate = 125
Set oResMaterial = oProject.Resources.Add("")
oResMaterial.Type = pjResourceTypeMaterial
oResMaterial.StandardRate = 100
oResMaterial.MaterialLabel = ""
oTask.Assignments.Add oTask.ID, oRes.ID
Set oA = oTask.Assignments.Add(oTask.ID, oResMaterial.ID)
oA.Work = 120
'
oProject.SaveAs "C:\.mpp"
End Sub

Вам также может понравиться