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

VBA Excel 2003

Excel 2003
Power Programming
with VBA
John Walkenbach



VBA Excel 2003

-
2005

32.973.26-018.2.75
62
681.3.07


..
. ..
..
:
info@dialektika.com, http://www.dialektika.com
115419, , / 783; 03150, , / 152

, .
62
VBA Excel 2003. : .
. . : , 2005. 800 . : . .
. .
ISBN 5-8459-0771-3 (.)
Excel . , ,
. VBA , .
VBA. VBA, .
,
VBA-,
. VBA,
,
. VBA,
,
.
32.973.26-018.2.75

.
, , , JOHN WILEY&Sons, Inc.
Copyright 2005 by Dialektika Computer Publishing.
Original English language edition Copyright 2004 by Wiley Publishing, Inc.
All rights reserved including the right of reproduction in whole or in part in any form. This translation
is published by arrangement with Wiley Publishing, Inc.
ISBN 5-8459-0771-3 (.)
ISBN 0-7645-4072-6 (.)

- , 2005
Wiley Publishing, Inc., 2004


I. Excel

1.
2.
3.
4.

Excel 2003:
Excel

Excel

II. Excel
5.
6.

III. Visual Basic for Applications

7. Visual Basic for Applications


8. VBA
9. VBA
10.
11. VBA

IV.

12.
13.
14.
15.




UserForm

V.

16.
17.
18.
19.
20.
21.

Excel VBA


Excel

VI.

22.
23.
24.
25.

31
33
45
67
87
105
107
119
139
141
187
223
255
283
333
335
353
383
409
441
443
457
469
515
543
563
585
587
615
643
659

VII.

669

26.
27. VBA
28. Visual Basic
29.
30. Excel
. , Excel
. VBA
. VBA
. -

671
681
701
719
731
763
769
777
781
792

I. Excel
1. Excel 2003:

VisiCalc
Lotus 1-2-3
Quattro Pro
Microsoft Excel

Excel
Excel Microsoft

2. Excel

23
24
30
31
33
33
33
34
37
38

41
43
45
45
46



XLM
Excel 5/95

47
47
48
48

Excel

48

48
49
49
50
51
51
51
52

52
53
55
55
55
55
56

56
57
57
58

58
59

Internet
XML

60
60


Analysis ToolPack



VBA-

3.




R1C1



1900

4. Excel
Excel

Lotus 1-2-3
Quattro Pro


, Excel
XLS

60
60
60
61
61
62

62
62
63
63
64
64
64

65
67
67
68
68
69
70
70

71
72
72
73
74
74
74
75
76

76
77
78
79
79

80
80
81
82

82
82
83

84
87
87
88
89
90
90
90
91

91
91

Excel HTML
?
HTML-
?

XML-
XML
XML-
XML-
XML- Excel

Excel

Excel

II. Excel
5.









-
-


-


6.

,



ActiveX



92
92
93
93

94
94
95
96

98
98
99
100
101

102
102
103

105
107
107
109
109
110
110

111
112
113
113
113
114
114
115
115
116
116
116
117

119
120
121
123
124
125
126
128
129
129

130
130
131
133
133


Excel,
,

III. Visual Basic for Applications


7. Visual Basic for Applications
BASIC
VBA

VBA XLM

VBA
Visual Basic
VBE
VBE

Project Explorer
VBA
VBA



VBA
VBA

VBE

Editor
Editor Format
General
Docking

Comment:
Comment
Comment
Comment
Comments
Comment
, Comment
?
Comment
Application

10

134
134
135

135
135
136
136
136

139
141
141
142
142
142

143
146
146
147

148
149
149
149

150
150
150
151

156
156
159
160
160

161
161
162
165
166

167
168
168
169

169
169
170

172
172
173
173
173
174
175
176
177
177

Range

179

Range
Cells
Offset

179
180
182

8. VBA
VBA.





With-End With
For Each-Next


GoTo
If-Then
Select Case

9. VBA


183
184

187
187
188
190
191
193
195
198
199
200

201
202

183

203
203

204
205
205
208
208
209

210
211
211
214
216

223
223
224
225

225
RunRun Sub/UserForm







226
226
227
228
229
233
234
235
235

235
239

239
240

242
242
242

11

10.
:




VBA









VBA,
,

Excel




Windows API
Windows API
Windows
<Shift>
API

11. VBA






12

243
243
244
244
245
246
247
250
250
253
253

255
255
255
256
256
256
257
258

259
259
260
260

262
262
262
263
264
266
267
267
269
271
272

273
275
276
276
277

279
279
280
280
281
281

283
284
284
285
285
286
288
289

,





,




Variant

VBA
Boolean




, VBA
FileExists
FileNameOnly
PathExists
RangeNameExists
SheetExists
WorkbookIsOpen

Excel






?
n-

SHEETOFFSET


Windows API




290
291
292
293
295
295
296
296
297
299
299
300
300

302
302
303
303
304

304
305
305
306
307
308
309

310
310
311
311
311
312
312
313

314
314
315
316
317
317
318
319
320
321
322
322
323
325

326
326
327
328
328
330

13

IV.

333

12.

335
335
336

...

InputBox VBA
InputBox Excel

336
337

VBA MsgBox
Excel GetOpenFilename
Excel GetSaveAsFilename

339
342
345
345

Windows API
FileDialog

345
347

Excel

348

Dialogs



348
350
350
351

13.
Excel
UserForm


CheckBox
ComboBox
CommandButton
Frame
Image
Label
ListBox
MultiPage
OptionButton
RefEdit
ScrollBar
SpinButton
TabStrip
TextBox
ToggleButton

355
356
356
356
356
356
356
356
357
357
357
357
357
357
357



Properties


14

353
353
354
355
355

358
359
360
361
362
362

364

364
365
366

366

366
369
369
370

UserForm

UserForm
SpinButton
SpinButton TextBox


Toolbox



ActiveX

14.
UserForm
CommandButton
ListBox






ListBox
ListBox
ListBox


ListBox
ListBox
ListBox
ListBox,

ListBox

ListBox

MultiPage

15. UserForm



MultiPage

MultiPage


MultiPage



MsgBox
MyMsgBox

372
372

372
372
373
374
375

378
379
379
379
379
380

381
381
383
383
383
384

385
386
388
389
390
391
392
392
396
397
398
398
399
401
402
404

406
409
409
410
412
414

415
416
416
417
418
420

420
421

15


MyMsgBox

423
426
427

429
430

1:
2: OWC ChartSpace

431
432

V.
16. Excel VBA
Excel
VBA

:

Text Tools

Text Tools

ThisWorkbook
Module1
UserForm1
Text Tools
Text Tools


Text Tools

17.



435
438
438
439
439

441
443
443
444
444
445
446
446
446
447
447
449
450
451
451
453
453
455
456

457
457
457
459
459

460

460
460
461
462

18.


16

422
423

463
465
467
469
469
469
470

471

VBA



ChartObject


ChartObject



,
ComboBox



Chart

Chart

19. Excel
Excel





,

Workbook

Open
Activate
SheetActivate
NewSheet
BeforeSave
Deactivate
BeforePrint
BeforeClose

Worksheet
Change

SelectionChange

472
473

474
474
475
476
476
477
478
478

480
480
481
483
484
487
488

491
491
493
495

497
497
497
499
500
501
502

504
504
505
506
511

515
516
516
516
517
518
519
520

521
522
523
523
523
524
524
525
525

527
527
528
531

17

BeforeRightClick

Chart
Application
Application

Application

UserForm
,
OnTime
OnKey

20.

Shell
API- ShellExecute


AppActivate
Microsoft Office




Word Excel
Excel
Outlook

ADO
Excel
SendKeys

21.


536
536
537

538
539
539
541

543
543
543
545

546
546
547

547
548
549
549
552
552
555
557

558
560
560
563
563
563
564

Excel

565
566
567

567
568
568
568
569
570
570

XLA XLS

VBA-

VBA
AddIns
AddIn
AddIn

18

532

533
533

572
572
572
572
573
573

576
576
577
580

580

,


Excel

VI.
22.


Excel

CommandBars

CommandBar









23.
Excel
Excel

VBA





580
581

582
582
583
583

585
587
587
588
588
588
589

590
590
593

595
595
595
596
597
598
598
603
604
604
605
606
606

615
615
616
616
617
618
618

619
619
619
623
623
626
628

628

628
629
630

633
634
636

637
638

19

639
639
639
640

24.

643
643
645

Excel
, Excel




Office

?
HTML Help System


WinHelp HTML Help
Help

25.
,




VII.
26.


Excel

Mac


VBA


27. VBA

VBA
FileSearch
FileSystemObject

20

646
646
647
647
651

653
653
655
656
657
657
657

659
659
659
660
661
662
666

666
667
669
671
671
672
672
674
674
675
676
677
677
678
680

681
681
682
684
685





Excel

256
HTML
XML-

28. Visual Basic


IDE
IDE
VBProjects



VBA VBA
UserForm

UserForm

100 CommandButton

UserForm

29.

: NumLock

VBA
NumLock

: CSVFile



CSVFileClass

30. Excel
Excel
Visual Basic

687

688
688
689
689
689
690
690

691
691
691
692
693
694
694
696
699

701
701
702
703

704
705
707
709
710
711

712
713
714

719
719
720
720
721
723

724
724
724
726
726

726
727
727
727
729

731
732
735

21

, ,

CommandBar

738
742
745
753
758
759

. , Excel

763
763

Microsoft

Microsoft
Microsoft Excel
Microsoft Office

763
764
764
764

764

,
Microsoft

764
764
765

Web-

766

Spreadsheet Page
Web- , Excel
Web- , Excel
,

. VBA
Excel VBA

769
772

. VBA

777

. -

781
781


- Windows

22

766
767
767
767

781
781

792


. JWalk and Associates Inc. , -
. 30 ,
, 300 , PC World, InfoWorld,
PC Magazine, Windows PC/Computing. Web-
The Spreadsheet Page (www.j-walk.com/ss/). Power Utility Pak, Microsoft.
,
.


VBA Excel 2003 !
, , , , Excel , , .


Excel . ,
. , VBA
( ,
). , Excel, . , , . ,
-.
Excel.
, , ,
( ) ,
. , Excel
, .
, . ?


Excel.
, Excel 2003.
( ), Excel ( ).
, Excel.
. , :
, , ..;
;
;
Excel;
Excel;
;
Windows, , , .
, , , , . , , .
, Excel 2003, 2.


Excel.
, Excel 2003,
Excel 97 .
Excel, . ,
, , Excel Macintosh. , Mac .
Windows, . Excel
, .
(800600 ,
1024768 , 16001024 ). , 640480.

,
, ,
, .

,
. , .

, , , ,
=(B2:B50) B51.
. ,
.
=((A1:A8)+(B1:B8))/25

VBA
VBA,
. , .
, , . ,
, ,
.
, VBA : ,
. ,
. , .
If Right(ActiveCell, 1) = "!" Then ActiveCell _
= Left(ActiveCell, Len(ActiveCell) 1)

, (.. ), ,
.

25

,
Excel
(: C20 ). ,
, VBA
( GetTotals). , ,
, .

,
, , , , .
: , ,
, ..


. , .


, ,
Windows XP, . ,
.
.

, , , Excel 2003. , Excel,


.
, ,
, , .

-
, , , .

, ,
, .

,
, .

26

, -.


.
.

I
. 1
,
Excel . 2
Excel 2003 , Excel. 3,
, , . 4 ,
Excel.

II
. 5 . 6 , .

III
7 11.
VBA. VBA,
VBA. 11
VBA .

IV

( UserForm). 12
.
, , 13. 14 15
, .

V
, . , VBA
. 19 , , ,
. 20 (, , Word). V 21, .

27

VI
, . 22 23 . 24 . 25
, ,
.

VII
,
. 26. 27 VBA . 28,
, VBA Visual
Basic, . 29
. ,
Excel.

. Internet, Excel.
VBA ( ).
VBA . , ,
-.

-, , . , ,
, . ,
, , ,
. , .
- ,
, .

- .


, .
, . , .
,
, , .
,
.

28


, . , , Web-
. , . ,
. ,
, ,
105 000 .
, ,
. . , . , .
, Web- (http://www.j-walk.com/ss/),
, Excel.

!
, , .
, , .
, .
.
Web-
. ,
, , ,
.
, ,
. .
:
E-mail:
WWW:

info@dialektika.com
http://www.dialektika.com

:
:
:

115419, , / 783
03150, , / 152

29


-, ,
.
, .
, , , Excel. , .
.
, ,
(Susan Christophersen), . (Bill Manville), .
, .

-,

I
Excel
...
1. Excel 2003:
2. Excel
3.
4. Excel

Excel 2003:

...
,
Excel 2003, ,
Microsoft.
.
.
Excel .
,
, .
, . ,
,
.



. , , , , ,
.
, .

VisiCalc
VisiCalc (Dan Bricklin) (Bob Frankston)
1978 , .
VisiCalc Apple II , . (, Apple II
.) VisiCalc, , , ,
. VisiCalc , Apple II ,
.
VisiCalc , Apple II
.

; CP/M. Sorcim SuperCalc


, .
1981 IBM PC, , VisiCorp
VisiCalc .
Sorcim SuperCalc, .
VisiCalc, SuperCalc . , , , ,
.. .
, .

Lotus 16263
VisiCalc, ,
, ,
. (Mitch Kapor)
(Jonathan Sachs),
.
, The Wall Street Journal Lotus 1-2-3, . ,
.
1983 Lotus Development Corporation,
. 495 (,
), VisiCalc,
.
Lotus 1-2-3 VisiCalc
SuperCalc , , 16-
IBM PC AT. , Lotus 1-2-3 DOS ,
, . ,
. , ,
Lotus 1-2-3 . , .
, . , Lotus 1-2-3
, .
Lotus 1-2-3 , . (1)
(2) ,
(3). , , 1, 2, 3?
Lotus , Lotus 1-2-3
1983 1A.
Lotus
. 1985 1A
2, 2.01, . 2, ,

34

I. Excel

(add-ins) ,
, . , 2 , , . ,
.
, Lotus 1-2-3
, , , . -
Twin Mosaic Software VP Planner Paperback Software. , (
Lotus 1-2-3) Lotus Paperback Software .
, Lotus, Paperback.
1989 Lotus DOS- OS/2- 3
Lotus 1-2-3. ,
, ;
.
, . Boeing
Calc, , SuperCalc 5 CubeCalc.
3 Lotus 1-2-3 , , , .
, ,
,
. ,
: .
3 ,
80286 1 1989 .
Lotus , .
3 ,
2.01 (
Lotus 1-2-3 2.2). , 3 2. Lotus
, : ,
, ,
.
, 2.2 Lotus 1-2-3 , - .
Allways, ,
, . ,
WYSIWYG (What You See Is What You Get , ). ,
, .
, , Lotus 1-2-3
, , ,
- .

1. Excel 2003:

35


, . , .
, , , Microsoft Office XP .
,
.
, .
, Microsoft ,
. (Lotus 1-2-3 WordPerfect), . , , , .
,
. , - . ,
, Microsoft. ? .
, ? , . ? . ? .

1990 Microsoft Windows 3.0. , , ,


. , , Lotus , Windows , , Windows. Lotus 1-2-3 for
Windows 1991 . , ,
, . Windows . Excel, Windows , Windows- ( ). Lotus, 1993
: Lotus 1-2-3 4 Windows. . 5 Windows 1994 .
Lotus 4.0 DOS (Lotus 1-2-3
Release 4.0 for DOS). ( ) , Windows. ;
3.4.
Windows , , ,
Lotus 1-2-3 DOS, .
Lotus (
Notes). 1995 IBM Lotus Development Corporation. Lotus 1-2-3, , ,
, , . Excel
, Lotus 1-2-3 .
Lotus 1-2-3 , LotusScript
, VBA. ,
. ,
Lotus, , Microsoft VBA.

36

I. Excel

Quattro Pro

(, , ) Borland International. 1994
Novell WordPerfect International Borland , . 1996 WordPerfect, Quattro Pro Corel Corporation.
Borland 1987 , , Quattro. , , Lotus 1-2-3, , , . ,
. , , Lotus 1-2-3, , ,
,
Lotus 1-2-3.
1989 Borland Quattro Pro ,
, Quattro, Lotus 1-2-3 . , Quattro Pro
, ,
. , (Graphical User Interface GUI). : Quattro Pro Surpass, Borland.
1990 2.0 Quattro Pro (Quattro Pro
Version 2.0),
Paradox Borland. Quattro Pro 3.0,

-. 1992 4, , . 5, 1994 , , , (.. ).
Lotus, Borland Windows. , 1992 Quattro Pro for Windows , Windows-,
: Excel 4.0 Lotus 1-2-3 1.1 Windows. ,
Quattro Pro Windows ,
UI Builder ( ).
.
, Lotus Borland.
Lotus , Borland Quattro Pro
Lotus 1-2-3 , Lotus 1-2-3.
, 1994 , , Quattro Pro
, Lotus 1-2-3
( - ). , ,
.
Borland 5 Quattro Pro
Windows. , Novell Borland ,
, 5 6.
Quattro Pro ,
WordPerfect Office 2000. -

1. Excel 2003:

37

, 1 18 278 (, Excel ). Quattro Pro .


Quattro Pro . Excel 5.

Microsoft Excel
.
, Microsoft
1980- .
Microsoft : MultiPlan, , Excel 2003,
.
, 1982 Microsoft MultiPlan
. ,
CP/M, MultiPlan , , Apple II, Apple III, XENIX
MS DOS.
MultiPlan . ,
. , Lotus 1-2-3.
MultiPlan Excel, Macintosh 1985 . Mac-, Excel
( MultiPlan). 1987 Microsoft Excel, Windows ( Excel 2.0
for Windows, ,
Macintosh). Windows , Excel 2.0 Windows, Excel. Microsoft
Excel, 2.1 (Excel Version 2.1). 1990
(2.1b), Windows 3.0.
2.x (. 1.1)
,
,
. Excel (XLM), , . , . ,
XML VBA, .
, Microsoft Excel ( 2.20) OS/2 Presentation Manager. 1989 ,
( 2.21). ,
IBM, OS/2 .
1990 Microsoft Excel 3 Windows
, , (. 1.2). , ,
, , (Object Linking and
Embedding OLE), , , , . , Excel 3 ( Q+E).
Excel OS/2.

38

I. Excel

. 1.1. Excel 2.1 Windows. , Excel


? ( Microsoft)

. 1.3. Excel 3 . (
Microsoft)

1. Excel 2003:

39

4, 1992 , ,
, (. 1.3).
, , Excel 4
. Microsoft IBM
; Excel 4 OS/2 ,
Microsoft Excel, .
Excel 5 1994
. ,
, . Lotus 1-2-3 5
Windows Quattro Pro Windows ,
, , Excel 5
. , ,
VBA.
Excel 95 ( Excel 7)
Microsoft Windows 95. Microsoft , , Office, .
, Excel 95 Excel 5.
, . , Excel 95 ,
Excel 5. , Excel . , , VBA . ,
Excel 95 ,
Excel 5 ( , ).

. 1.3. Excel 4, Excel 5


. ( Microsoft)

40

I. Excel

1997 Microsoft
Office 97, Excel 97. , Excel 97
Excel 8. , VBA.

( , ). Microsoft Excel 97 ,
. , Excel 5 Excel 95, Excel 97
, .
26.

Excel 2000 1999 ;


Office 2000. , Excel 2000, , , Internet, .
Excel 2002 2001 . ,
, , . , ,
. ,

Excel. Excel
.
, Excel 2003,
. 2003 , . XML. , , Microsoft . . , ., .

Microsoft Excel 2003.


XML
Excel 2003 ( Excel 2003, Office 2003
Professional). , ,
, .

Excel


. Excel 2003 , , , , VBA.

1. Excel 2003:

41

Excel.
.
.
, . VBA , .
Visual Basic for Application (VBA). Excel. , Excel
(, Lotus 1-2-3 LotusScript), .
. Excel
, , ,
, .. .
. , .
Excel 2003, ( Excel 97),
, .
. VBA
.
.
,
. , Excel .
. Excel , , .
.
, . , ,
Excel .
. Excel, , ,
.
Microsoft Query.
. ,
Web-.
Data Access Objects (DAO) ActiveX Data Objects (ADO). , VBA.
. . , , Excel .
.
XLA- , .

42

I. Excel

. VBA, , . ,
Excel Microsoft Word.
Web-. Excel HTML.

Excel Microsoft
Excel Microsoft
Office , ( ,
Office). , , . Microsoft . Office VBA.
, Excel VBA, .

1. Excel 2003:

43

Excel

Excel 2003.
Excel.
Excel; .
, .
, Excel,
(,
Lotus 1-2-3, Excel).
, Excel, ,
.


Excel (
VBA), Excel,
.
Excel:
Excel;
Excel;
;
;
ListBox () ( );
;
.
, :
Excel ,
, , , .
Excel. Excel
,
VBA.
Office 2003, Office.

VBA
VBA Excel 5. ( Excel 95) VBA
. VBA, , , ,
VBA-. Excel 97, VBA .
VBE (Visual Basic Editor Visual Basic).
VBA VBE,
<Alt+F11>.
.

.
, , Excel, ,
VBA. .


Excel . ,
Excel, , ,
.xls. Excel
. :
;
;
XLM (, );
( , ).
( ),
. ,
. ,
, .
.
, .
Excel 2002, .
.
,
.
, .
. ,
, .

?
: ? (25665 536) ,
16 777 216 ( ).
.
VGA , 9 18 ( 162 ).
0,001% . , 104 000 VGA .

46

I. Excel

( ), , -, 194 .
36 000 .
.
, ,
. , , , Excel . , .


. , .
, .
Excel 256 65 536 . , , . , ,
.
, , ,
Excel, Microsoft ( ) .

, Excel 97, 16 384


.


, .

. , , ,
, .

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

( , ). ( )
, .


.
, . ,
, . ,
.

2. Excel

47

XLM
XLM ( MS Excel 4) , . , XLM , .
, , .
, XLM
XLM. XLM ,
Excel (4.0 ). , Excel 2003
XLM, . XLM . VBA.

Excel 5/95
Excel 5 Excel 95
. , Excel 97
, (UserForm). Visual Basic
.
, Excel 5/95,
.

Excel 5/95,
.

.
Excel 5.0.

,
Excel 5/95.

Excel
. , , , , ..
Excel , , Windows, ,
Excel - Windows.

Excel 97, . ,
.
Excel .
( , ,
). Windows , , , , . (,
<Ctrl+Z>).

48

I. Excel

, , .
, (, , ). , .

. .
, , ,
. , Excel
, . , Excel 5 Excel 95,
Excel 2002 2003.

, Excel 5 Excel 95,


Excel 5 Excel 95.
, .

Excel ,
. , .
VBA .
23.

Excel 2003
( ). ,
, .

. , .
( )
. Excel
.

, , . Excel ,
(. 2.1). , Excel , , ,
.
22.

2. Excel

49

. 2.1.
, ,
,

Excel .
, , .
. ,
. , . ,
.
Excel . .
, , (. 2.2).
13 . ,
.

( Excel 97). , ( MultiPage).


IV.

. 2.2. , , ,

50

I. Excel


Excel, ,
, , . <Ctrl>, .
, Excel
. <Ctrl>,
.

;
.

Windows,
.
( ) OLE-.


Excel . ,
, <Ctrl+C>.
Excel ,
, . Excel.
,
.

6
- , . -
, . ,
- (. 2.3).

. 2.3. -

2. Excel

51

Excel -. .
-, Excel .
-.


Excel 2002. , ,
.
. , , , XML- ..

Excel 2003 .


Excel . Excel :
( / );
;
;
( ).


, Excel, .
,
<Enter>. ,
<Shift+Enter>, <Tab>,
<Shift+Tab>.
,
. , . , , .
,
, ,
<Ctrl+Enter>.

, <F2>, <Ctrl+Enter>.
,
, , <Ctrl>, .
,
.

52

I. Excel

, . , <Ctrl+D>, , <Ctrl+R> .

( ). , <Ctrl+Alt+Tab>. ,
<Alt+Enter>. .
0, ,
( </>). .
,
( ).
; , .
<Ctrl+;> <Ctrl+Shift+;> .
( ), .

(=). , Excel
, Lotus 1-2-3, (&), (+)
(). , <Enter>,
.

,
. Excel ,
. ,
, ( , ).

3,
.

, Excel , .
, .
Excel 2002 ,
. , ,
, (. 2.4).
,
- . Excel
. , Analysis
ToolPack, (
).

2. Excel

53

. 2.4.


, . 2.5.
, (

<Shift+F3>). ,
.
Excel 2002 ,
, . ,
, ASCII ,
.

, Excel VBA
(. 10).

, , ,
, . , , , .
, .
3.

. 2.5.


54

I. Excel


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


, Windows. , . ,
, . , <Ctrl>. , ,
, , ,
<Shift>, .

, Excel 97,
. Excel 97, .
, <Ctrl>.

Excel : .


, .
, (. 2.6). .

,
. ,
(
), .

. 2.6. Excel

2. Excel

55


, .
, ,
, . ,

, . .

: <Ctrl+1>. xxx ( xxx
). ,
. ,
.
Excel , .
, . ,
. ,
, .

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

(. 2.7), .
, : . ,
, .
, ,
.
Excel ,
.
(
<Shift>). , .
, ,
.
,
, , , .

56

I. Excel

Excel
. , (. 2.7). , , ,
.

. 2.7.

Excel .
, , .

, (
).
(. 2.8).
.

, .

Excel.
. - . 2.8.
.


. Excel : XLM VBA. XLM
. VBA. , Excel
XLM, .
VBA.
VBA III.

2. Excel

57



( Lotus 1-2-3).
Excel.
, ,
.
. , . Excel 65 535
256 ( ).
. .


, , Excel
. ,
, ,
, , .
Excel, , .
, ,
. , .
. ,
, . . 2.9
, .

. 2.9. Excel

,

58

I. Excel


, ,
.

Excel 2003 . .
,
(. 2.10). , ,
. ,
, .


,
.
Microsoft Query , . .
DAO (Data Access Objects )
ADO (ActiveX Data Objects ActiveX),
, Excel.
VBA , , , ADO
, .
Web-, ,
Internet.

. 2.10.

2. Excel

59

Internet

Excel , Internet,
,
HTML, Web-. ,
, (
).
Excel HTML, . , Web- Office, Web-
(
Web- Office).
HTML 4.

XML
Excel 2003. XML-
.

XML- Excel 2003


.

4 XML.


, Excel (
).
, Excel
.


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


Excel ( )
, . , Excel
,
(. 2.11).

60

I. Excel

. 2.11. Excel

Analysis ToolPack
Analysis ToolPack ( ) 19 ( , ), . Excel .


. Excel 2003.

Excel . ,
(. 2.12). . , , VBA. , , -,
.

, VBA , 17.

2. Excel

61

. 2.12. Excel


Excel
,
, .

, Excel
. , .
, Excel, ,
Web- Microsoft. , ; ,
Internet. , 21.

, Excel,
. Excel
, .
Excel , , .
, Excel 97, Excel 20002002 ,
.
, Excel, , .
Excel , (
4).

62

I. Excel


Excel. ,
26.


Excel . ,
,
VBA-.


.
,
.
1. , .
2. .
.
3.
.
4. .
5. . , . 2.13.
( Excel 2002) .

. 2.13.

6.
.

, .

Excel 2003 .
, . ,

( ).

2. Excel

63

, . .

.



. .
, . 2.14. ,
. , .

. 2.14.



.
.
.
, . 2.15.
.
.

. 2.15. , ,

VBA6
,
VBA-. Visual Basic Project
. Toolsxxx Properties ( ).
.
Protection (. 2.16).
Lock Project for Viewing (). . VBA- .

64

I. Excel

, Excel
. ,
.
,
Internet.

. 2.16. VBA-

Project Properties


! .
( , ). .
<Enter> (
VBA). , (. 2.17).

Excel 2003 , .
.

Internet ,
.

2. Excel

65

. 2.17. ,

66

I. Excel



,
.
.
Excel.
.
.
.
.
.
.
Excel .


Excel 2003, .


. ,
(
, ).
Excel , ( , ).
, :
+ () * ();
( );
;
(, ).
1024- .
. , , .


, , , .
, ,
. ,
. , , . , , .
(,
), Excel
.
Excel , , . , .
. , D12 D11,
D11, D12.
, Excel , , . , , , . ( ).
, .
.
<F9>
.
<Shift+F9>
.
.
<Ctrl+Shift+F9> .
. , Excel - ,
, , VBA.

Excel ()
.
, .


.
( ),
, . .
. .
,
(: A1).

68

I. Excel

. . , (: $A$1).
. .
, , , ,
(: A$1).
. .
, , , ,
(: $A1).
.
, .
-: , , <F4> ,
.


, , , -
(. 3.1).
C4 .
=C$3*$B4

( B) ( 3).
, C8, , F8. ( 3, B, ),
.
, , .

. 3.1.

3.

69

R1C1
, Excel A1. ,
, , , ,
. , Excel
R1C1. ( R row, .. , C column, .. ).
A1 R1C1, A2 , R2C1 ..
R1C1, ,
R1C1. , . , .
. 3.1 , R1C1. , B1
( R1C2).

3.1. ,

R1C1

=A1+1
=$A$1+1
=$A1+1
=A$1+1
=(A1:A10)
($A$1:$A$10)

=RC[-1]+1
=R1C1+1
=RC1+1
=R1C[-1]+1
=(RC[-1]:R[9]C[-1])
=(R1C1:R10C1)

R1C1 ,
. ,
, .
.
, R[-5]C[-3] ,
, .
, R[5]C[3] ,
. , . , R[5]C
, .
, R1C1 ,
. .
R1C1,
.
(, ). R1C1 . - ,
, , .
, VBA , ,
, R1C1.


, ,
, .
,
, .
, .
=2!A1+1

70

I. Excel

, , .
( ), .
=[.xls]1!A1+1
, , ,
( ) .
='[ 2002 ]1'!A1+1
,
.
='C:\MSOffice\Excel\[ 2002 ]1'!A1+1
.
. .
( , ).


Excel 2002 ,
.
( Excel),
.
Excel, ,
( ). ,
, , .
, , Badfile.xls, 1
1
A1 .
='C:\Files\[Badfile.xls]1'!A1
,
. ,
.

. ,

, , ( ). : ,
.


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

3.

71



( <Ctrl+F3>). ,
( , ).
, , <Enter>.
,
. .
, . 3.2 , C4:F4 , C5:F5
.. , C4:C7 1,
D4:D7 2 ..

. 3.2. Excel

VBA,
.
? : , VBA, , VBA- . , VBA-
C4, Range("C4"),

. ,
, , Range("InterestRate").


, Excel , . , F10 .
=A1-A2
A1 , A2 , =-. , . ,
. .
,
, OK. , , .

72

I. Excel

, . ,
,
. , , , #?.


Excel . ,
, .
, .
. , . , , , .
VBA.

Sub DeleteHiddenNames()
Dim n As Name
Dim Count As Integer
For Each n In ActiveWorkbook.Names
If Not n.Visible Then
n.Delete
Count = Count + 1
End If
Next n
MsgBox " " & Count & " "
End Sub

Power Utility Pak ( -)


,
.


Excel ( ).
, . . , .
. 3.2.
=2
440 2 . (), .
=()


Excel 97, , . Excel .
(.. ). , (
).
=
,
.

3.

73

, .
, ,
VBA. , Microsoft
.
. .


Excel . 1 4:7.
, 2 D ..
4,
5 ..
, , ,
.
, ,
. , , ,
7, 1.



, .
, . ,
(, 1!).
, ,
. ,
,
, , . ,
, .
.

, , ,
, .


Excel , ( Excel ). , ,
, ,
(.. ).
,
.
(, ), .
, .
=*A3

74

I. Excel

(. 3.3). ,
.
, , .

. ,
.
=,
.


, .

.
, , .
, ,
.
. 3.4 (=A1^B1),
. C1, , ( ,
). =, , ,
, . , B10 C10
, , 3 4, D10
, 81 (3 4- ).
=

. 3.3. Excel
,

. 3.4.
,

,
, , . , D32,
.
=1!B32^1!C32
, . ,
,
, .

3.

75

, 1,
( ).
=!A1^!B1

, , ,
. , .
, .

- ,
.


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


, , , , .
, VBA.
, ,
, ( ). , , . ,
<Enter>.

, ,
, .
<Enter>.


, , , ,
. , ,
, .

, ,

76

I. Excel

. ,
, .
. 3.2 - , .

3.2. Excel,

#/0!

(,
). ,

#/

( ) ,
, .
, . , #/
,

#?

, Excel .
, , , ,

#!

,
( )

#!

(,
, )

#!

. ,

#!

. ,
. , ,
VBA-


, . ,
. , ,
(Excel ).
, 15 15,
15. ,
; . , . A1:A5 B1:B5.
.
=A1:A5*B1:B5

<Ctrl+Shift+Enter>.
, ,
({}), . !

3.

77


Excel
, ,
. , .
. 3.5 A1:A5.
, , , . ,
, B, .

. 3.5. B1 ,
, A1:A5

,
, , . 3.5, .
1.

B1:B5.

2.

.
=(A1:A5)

3.

<Ctrl+Shift+Enter>.

.
, B1:B5,
, A1:A5 25 .
,
B1:B5 , .
, (
<Ctrl+Shift+Enter>).
=((A1:A5))
.
{=((A1:A5))}
( ) , , A1:A5.
25.

78

I. Excel

. 3.6 ,
. , , , 42- .

-, ,
, .

. 3.6. ,



.
.
.
.
,
- .

, .
.
.
,
<Ctrl+Shift+Enter>.

3.

79


, Internet, .
. ,
, .


Excel, , , ,
,
.
:
, , ;
,
.
:
;
,
;
, .
. 3.3 . , (
). ,
,
, .

3.3.

=(;12)

, , 12

=(;1)+
(;12)
=COUNTIF(;"<0")

, 1 12

=(;"<>0")

=(;">=1")(;">10")
=(;"yes")

, 1 10

=(;"*")

=(;"*s*")

, s (
)

=(;"???")

80

, yes (
)

I. Excel


, , ,
( ). , , , <Ctrl+Shift+Enter>.
(
), .
=((();1;0))
, ,
.
=((();1;0))
( ; ),
.
(((;)>0;1;0))
. 3.4 , , . 3.7.

. 3.7.
,

-
.

3.4. ,

=((A2:A10="")*
(B2:B10="")*C2:C10)

=((A2:A10="")*
(B2:B10<>"")*C2:C10)

=((A2:A10="")*
(B2:B10=""))

=((A2:A10="")*
(B2:B10="")+(B2:B10="")))

3.

81

. 3.4

=((A2:A10="")*
(C2:C10>=200)*(C2:C10))

,
$200

=((C2:C10>=300)*(C2:C10<=400)*
(C2:C10))
=((C2:C10>=300)*(C2:C10<=400))

, $300 $400
,
$300 $400


.
, .
(
) , , ,
.
, .
.
,
, .. . 3
.
,
( , Excel).


Excel . , Excel, 1
1900 . 1. 2 1900
2 ..
,
. , Excel . , 1 1999 , 01.06.1999 ( ).
Excel 36312, .

, Excel 2003. (
Excel) .


, ,
. ,
Excel, .
, , .
, Excel , ,

82

I. Excel

, , :
, . , 1 1999 36312. ( ) 36312,5.
, .
, . ,
.
=2-1

, .
, 0 1900 . , . Excel ( #########). ? 1904 .
,
1904. ,
.

, ,
24- . 24- Excel
. , :
,
. , , 24- :
[]:

1900
, 1 1900 . ,
Excel, , , , 1 1900 . ,
. , Excel , .
4 1776 .

, , , .
, ,
, , , .

- Extended Date Functions ( ). ,


,
100- 9999- . . 3.8 ,
1900 .

3.

83

. 3.8. Extended Date Functions 1900


, .. ,
, , - . ,
,
, .
? (, ,
), . ,
. ? , .
. , ( ) . ,
. ,
. ,
,
. , .
. 3.9
, . 3.5.
A, H. B G,
.

. 3.9.

84

I. Excel

3.5. ,
1 (. 3.9)

B1

=(A1)

C1

=(" ";B1;1)

D1

=(" ";B1;C1+1)

E1

=((D1);C1;D1)

F1

=(B1;C1)

G1

=(B1;(B1)-E1)

(.. )

H1

=F1&G1

, . : ,

, (
). , .
, H1 ,
A1.
.
=((A1);(" ";(A1);1))
&((A1);((A1))
-(((" ";(A1);(" ";
(A1);1)+1));(" ";(A1);1);
(" ";(A1);(" ";(A1);1)+1)))

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

, :
Excel 1024 .
VBA .
, .
NOMIDDLE(A1)
,
.

, . .
, 65536 . , . VBA-. . 3.6
.

3.

85

3.6.
VBA-

( )

10,8

24,4

6,2

8,9

VBA-

106,7

8,6

, ,
. .
, ,
. VBA- . VBA-
; , Excel.

86

- , .

I. Excel

Excel

.
Excel.
, Excel.
HTML.
Excel Windows.
Excel, ,
. , , Excel. .

Excel
Excel - ( ).
Excel.exe.
, Excel Windows
. ( , .)
; , .
, . .
Xlstart ( Excel) ,
, .
, . ,
. .

, ( ) , .
, Xlstart Book.xlt.
.

Excel .
. 4.1.

4.1. Excel

/automation

Excel , Xlstart .
Excel

/e

Excel . , Excel

/embedded

Excel ( )

/m


Excel 4.0 ( )

/o

Excel Windows. .
(. /regserver)

/p

/r
/s

/regserver

Excel Windows, . , , Excel , , ,


/unregserver

Windows,

Excel ; , Xlstart

, , , Excel. , , Xlfiles Excel


, /p
,
. , , . , .
"C:\Program Files\Microsoft Office\Office\EXCEL.EXE" /p C:\Xlfiles

Windows Excel. . , ,
, Excel. .



Excel XLS,
, .

88

I. Excel

,
. , , , ?
, , , Excel (
XLS) , , ,
Excel.

, XLS (
XLS), ( , ).

,
, Excel.

Lotus 16263
Lotus.
WKS , Lotus
1-2-3 1.x DOS. Excel , .

, Excel Microsoft Works, WKS.

WK1 , Lotus
1-2-3 2.x DOS.
*.all ( Allways) *.fm1 ( WYSIWYG (What You See Is What You Get, ,
). Excel .
*.wk1, , .
WK3 Lotus 1-2-3 3.x DOS, Lotus 1-2-3
4.x DOS Lotus 1-2-3 1.x Windows. . *.fm3 ( WYSIWYG). Excel
WK3, ( )
FM3.
WK4 Lotus 1-2-3 4.x Windows Lotus 1-2-3 5.x Windows ( Lotus, -, ).
. Excel
. Excel WK4,
: Lotus 1-2-3 4 Windows (
) WK3, Excel .
123 Lotus 1-2-3 97 Lotus 1-2-3 Millennium Edition.
. Excel
. Excel 123,
. Lotus 1-2-3,
WK3, Excel .

4. Excel

89

Quattro Pro
Quattro Pro .
WQ1 , Quattro Pro
DOS 1, 2, 3 4. Excel ,
.
WQ2 Quattro Pro DOS 5.
Excel , .
WB1 Quattro Pro Windows 1 5 ( 2
4 ). Excel ,
.
WB2 Quattro Pro Windows 6. Excel , .
WB3 Quattro Pro Windows 7 8.
Excel , .

Web- Microsoft Quattro Pro. WB3, Quattro Pro 97.


DBF , dBASE . Excel
DBF dBASE 4 .
,
Excel . , Microsoft Query, Excel . Microsoft Query
Excel,
.


. , .
, , ,
. Excel , , . , Excel
, *.txt.
, , , . ( ,
, .) . Excel ,
, . , Excel
, CSV.

90

I. Excel

, , ,
. Excel , ,
. , Excel , PRN.
Excel , ,
.

, : <Shift>, OK
.

. .


Excel .
DIF (Data Interchange Format ) VisiCalc. . Excel
, .
SYLK (SYmbolic LinK ) MultiPlan.
SYLK .
Excel , .

, Excel
Excel . .

XLS
XLS, Excel 2003,
, Excel 2002, Excel 2000 Excel 97. Excel, Excel 97. , , Excel. , .

Excel .
, XLS XLA.

XLS
, , , Excel
XLS. Excel,
XLS, , , , , . ,
VBA Excel, .

4. Excel

91

, . Visual Basic
Editor ( Visual Basic) <Alt+F11>, , Immediate, <Ctrl+G>. , <Enter>,
VBA:
Print ActiveWorkbook.FileFormat
Immediate , . , .

Excel

16

Excel 2

29

Excel 3

33

Excel 4

39

Excel 5, 95

-4143

Excel 97, 2000, 2002, 2003


, Excel. ,
, .
XLW.
.
Excel .

, , Excel. ,
, ,
XLW. ,
.


(
XLT). , ,
. , . , , .
.
,
, .
Excel 2002 Excel 2003 ,
. , , Web- Microsoft.

92

, ,
<Ctrl+N>, . , .

I. Excel

Book.xlt,
. , Sheet.xlt, , . , , Excel -, .
.
Xlstart.
Book.xlt Sheet.xlt. , .
Templates. ,
.

Templates Excel.
, VBA:
MsgBox Application.TemplatesPath


Excel
XLB. Excel 2003,
Excel10.xlb.
Excel; , *.xlb. ( )
, .
XLB,
Excel, Excel 2003. xlb.

XLB , Excel .
, XLB.
. .


, .
IsAddin True (), .
, Excel
. , .
Workbooks ( ).
Excel . ;
.
. , Excel, -

4. Excel

93

, . XLA, .

Excel XLA, XLL


( Excel 2000) COM.
Excel. , XLA.

21.

Excel HTML
HTML World Wide Web. , ,
HTML. HTML-
, . , .
Excel 2000 , HTML
. ,
HTML, HTML- Excel,
, . , Excel (, , , ), . HTML
. , ,
Excel ,
, .
, HTML
, Microsoft,
, ,
. , , HTML .

?
, Excel HTML ,
. ,
. , , HTML. -, . . 4.1 ,
, . HTML-,
Excel.

. 4.1.
HTML

94

I. Excel

,
HTML.

HTML-.
. , HTML-
, . HTML-
HTML-. , , . HTML- ,
Web- .
HTML-, Excel.
Excel HTML. , HTML- . ,
. , HTML- .
<head> </head>.
. ,
<style> </style>, ,
, <head> </head>.
, , ( <table> </table>).
<td>.
,
Excel .
HTML-, ,
4000 , Web-
, . , , Excel HTML-.

HTML6
, , . , HTML-.
, A1:A3
<F11>, . . , Excel ( !).
HTML- ( 10 000 ). , ( , ). , ,

HTML- Excel.
HTML-, , ,
. JavaScript- (JavaScript , Internet Explorer Netscape Navigator).

4. Excel

95

HTML- ,
HTML-. , , .
HTML- ( , ,
).
GIF- ().
CSS- ( , ).
XML-. XML eXtensible Markup Language, .. ( ). ,
.
, Excel
HTML-. , MSO (MSO Microsoft
Office). ,
Excel (, , , ,
..).
, , , Excel HTML
. ,
, . , Excel
. HTML- , XLS-. :
HTML , .

?
HTML ,
. Excel HTML-,
, . , HTML- ,
, , ,
.
, ( ),
, ( ).

Excel 2003 HTML- . HTML


.

, HTML , ,
.
-.
: , .
. -.
, .
HTML-,
Internet Explorer.

Excel,

96

I. Excel

HTML-, , ,
. . 4.2 ,
Microsoft Internet Explorer.

Script Editor?
, , Excel, Microsoft Script Editor (
Microsoft). ,
<Alt+Shift+F11>. HTML- JavaScript ( VBScript). , , , .. . Excel VBA
, Web.

, , , HTML-, , ,
. .
HTML-. , , .
ActiveX. , Excel-,
Office 2000 .

HTML,
Excel 2000-2003. ,
( ).

. 4.2. Excel,

4. Excel

97

XML6
Excel 2003
XML-.
.

Excel 2003. XML-


. .

XML
XML .
XML , HTML, .
XML , . XML- ,
. HTML-, () , XML
. , XML
.
XML-, .
<?xml version="1.0" encoding="UTF-8"?>
<message>
<to>Bill Smith</to>
<from>Mark Jackson</from>
<subject>Meeting date</subject>
<body>The meeting will be at 8:00 a.m. on Tuesday</body>
</message>

Internet Explorer (. 4.3).

-.

. 4.3. XML-
Internet Explorer

98

I. Excel

HTML, XML
. , XML . XML ,
.

XML.
.
XML,
.

XML- Excel.

XML6
, . 4.4.
. ,
XML-, . .
<?xml version="1.0"?>
<Customer>
<Name>Joe Smith</Name>
<AccNo>32374-94</Name>
<LoanAmt>$325,983</LoanAmt>
<IntRate>6,25%</IntRate>
<Term>30</Term>
</Customer>

: Name, AccNo, LoanAmt, IntRate Term.


(Prepared Number of Pmt Periods)
, .
XML. ,
XML. ( XML
XML.)

. 4.4. XML-

4. Excel

99

XML .
1. XML
. XML.
2. XML.
3. XML-.
. .
4. .
XML- (. 4.5).

. 4.5. XML-

.
1. Name 3.
2. AccNo B5.
3. LoanAmt B6.
4. IntRate B7.
5. Term B8.
, XML-. XML. XML-. XML-
.
XML-.

XML6
XML-,
. XML- .
, . .
XML-
.
. XML,
. 4.6. .
XML-. Excel .
, . ,
.
XML-. Excel XML-,
.
.

. 4.6. XML

. 4.7 XML-.

100

I. Excel

. 4.7. XML-

XML6 Excel

XML-,
XML. .
XML.
, XML
. , , XML- (
XML). XML- c
Excel.

27 XML-
.
, XML. , Microsoft XMLSS. , XML.

4. Excel

101

Excel
Windows.
, , Excel
.


Windows 3.1 OLE- .
Windows 95 ( ),
,
, .
,
. : System.dat ( ) User.dat ( ). Windows. ,
Policy.pol , , .
(
Regedit.exe, Windows). ,
. , ,
. ,
. . 4.8 .
, . .
HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

. 4.8.

102

I. Excel

Excel
, Excel 2003,

HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Excel
, , Excel .

,
Regedit.exe ,
, .
, , , .
. -, ,
. (
, .) Windows .
-, . ASCII- .
, , ,
ASCII-,
( ). Regedit.

, Excel,
.

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

. 4.2 ,
Excel 2003. , .

4.2. , Excel

Add-in Manager ( )

, ,
. , Excel.
,
,

4. Excel

103

. 4.2

Converters ()

()
, Excel

AutoSave ()

Delete Commands ( )

Error Checking ( )

Init Commands
( )

Init Menus ( )

Line Print ( )

,
Lotus
1-2-3. Excel ,
Lotus 1-2-3, /wgdu (Worksheet Global Default Update,
,
)

Options ()

,
.
, ,
Excel
(, )

Recent Files
( )


( )

Resiliency ()

Security ()

Spell Checker ( )

UserInfo ( )

, Excel, ( ) ( Excel
).
: ,
, .

104

I. Excel

II

Excel

5.
6.



. . , . , ,
, .

Excel .
.


,
,


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


, ,
(, , C, Pascal BASIC)
. ,
,
.


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

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

108

II. Excel


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


15- .
, . .
, .
. , , .
, , .
, , . , , .
.
, .
( ) ,
.

, .

, , , .
,
. , ,
, , . ,
, , .
, .
.
, .
.

.

.
( ).

5.

109

.
, .
.
.
6.
,
( Excel). , Microsoft,
, . Excel , , ,
, ,
. , ,
. ,
.


, ( -, ) : .
. , , . 5.1. . , ,
( ). ,
,
.

5.1.

,
, . ,
, , . ,
, . , ,
, .


, . ,
, , .

110

II. Excel

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



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

5.

111

.
, . ,
.
.
Excel, , , PageMaker.
. ,
, , .
. , Excel
. Internet ( ) ,
Excel .
, , , .
,
. ,
. , , .


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

112

II. Excel


, .
.
, .
. ,
. ,
. 12 ,
, .
, , , ,
, . ,
- .

. .


, , , , . , , . ,
, ,
, .. ,
, ( ,
..) .
, ,
, ,
. ( ).
: ,
, , ,
. , .
,
. , Excel,
.
, :
, .
, , , . , ,
.


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

5.

113

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

6
-.
,
; , . .
, . ,
, , ,
. ,
. , ,
- , .
, -, ,
. , ,
. , . ,
- , ,
.

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

114

Power Utility Pak - Excel.


, .
, Excel. -
- . .

II. Excel

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

, .
16 , VBA
Excel.

, Excel ,
. , , .
, VBA.
, .

10
, .


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

5.

115

6
- , .

, ,
. , - ( ). , ,
, ?. , .
,
.
- , , .
, .
, ,
, .



,
.
, , . Excel 97,
65 536 . .
,

. , Excel
,
.
, , ,
,
, Access.


. Excel
, ,
. , ,
(executive information system EIS).
.

.
Excel,
, .

116

II. Excel


.
, , .
, ,
. ,
,
, .

. , . .

5.

117


, , ,
, ,
Excel.

,


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

,
.
. ,
.


,

. ,
.
.
, .
(, ,
), , , .
, .
, .
, .
, ,
.
, ( ) . , , ,
. , , .
, . , , , - , .
, ,
. , , .
, ( ) Excel . ,
Microsoft , , .
, Microsoft Office .
. .
, .
. ? , . ,

120

II. Excel

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

, , .. , . .
,
. , ,
, .
, , , , .
Excel! , .
Excel
, , , ,
, , .
, , Excel . ,
, ,
. ,
, .
, .
. , : ,
.
. ,
. ,
.
VBA. , :
VBA? .
XLS.
, .

6.

121

Excel. Excel-: Excel 2003, Excel 2000


Excel 97? Excel 95 Excel 5? Macintosh? ,
Excel , .
.
. ,
, . , ,
, .
.
,
Excel, . Excel, ,
.
.
,
,
.
. , , , Excel , . , ,
, , . , , .

Excel.
, Excel .

, , . , .
, . ,
. , ,
. . , . , , , , .
,
.


. Excel .
18 24 . , , , , .
Excel 5, VBA, Excel
. ,

122

II. Excel

Excel, , , XLM,
Excel 2, 3 4. Excel 5, , .
Excel 97
. , Visual Basic,
, . Excel 2000 Excel
2002 ,
, .
Excel 2003 , , . Microsoft
.NET, , Office .
, VBA VSA (Visual Studio for Applications).
VBA , , ; .
VBA . , , ,
VBA , . VBA , . VBA,
, VBA.
VBA .

, . , ,
, , , . . .
. , DDE OLE. , .
.

, , .
, , , ..
. ,
, , ,
, .
Excel: , , .. ,
, . , , , ,
, Excel. , ,
( ) .
,
.

6.

123

Excel , :
( );
(, , ListBox ( ) CommandButton ( )), ;
;
;
.
,
.


- Excel,
. ,
.

Excel 97 . (UserForm).
, , Excel 5/95, . ,
.


, ,
. ( ). Visual Basic (Visual Basic Editor VBE),
<Alt+F11>. ,
, ( , , ..).
ActiveX. , Excel. ,
.
, , ( , ). , ,
, .
VBA-.

IV.

124

II. Excel

ActiveX

Excel ActiveX,
, . . 6.1 .
, , , .

, ,
-.

, CommandButton. ,
.

. ,
ActiveX . ,
, ,
.
ActiveX
. ,
, Excel 5/95.
ActiveX . . (. 6.1).

. 6.1. ,
,
,

6.

125

6.1. Excel
ActiveX
ActiveX

Excel

Excel

97, 2000, 2002

5, 95, 97, 2000, 2002


VBA-


(,
CommandButton1_Click)

,
Properties


Click ()
Change ()



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

Excel 97, Microsoft ,


. 22,
. . 6.2
, Excel.
Power Utility Pak.
- .

Excel.
VBA ( ).
VBA (. 22).
VBA :
() .
,
(. 6.3), . ,
(, ),
Excel.

126

Excel 97, ,
Excel 5. Excel 97 , , ,
. , , , , :
Excel 5 , .

II. Excel

. 6.2.

. 6.3.
Excel

, ,
Excel, , . ,
VBA ( ). . 6.4
,
. ,
, .

6.

127

. 6.4.

23.


Windows, Excel .
. , ,
, . Excel , ..
.
, , , ,
. , ,
. ,
,
. , ,
, .

Excel 97, .

, .
, ,
(. 6.5).
,
.

128

II. Excel

. 6.5.

22.


, , . . Excel , <Ctrl> ( <Shift+Ctrl>).
, . , , , .
, ,
, ,
.
, ,
. , <Ctrl+S> . ,
. , , , , Excel.
,
, , , <Ctrl+Shift+S>.


, ,
, ,
,
. , , , .
,
.
, , ,
, .
. , .

6.

129


,
,
.



? , , . ,
,
. , , Excel, , , .
, .
. , , . , VBA ,
, , .

? Excel?
, , , , Excel,
, ( ) . . Excel ,
. , , .
, Excel,
Microsoft .
. ,
, , .
, . ,
. , ,
.
. Excel ,
.
Excel. , , ,
.
Excel - . ,
.
? , .
, , , , ,
. ? . ? .
.

. .
: (1) ,
( ) , ; (2)
, , .

130

II. Excel

. ,
, .
, .
Excel (. ? Excel?).
,
, . , .
, ,
, ,
( ). , .
, ,
. , , ,
. ,
, <Ctrl+F6>
. ? ,
,
.

-?

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


. ,

. ,
, .
, , , , .

6.

131

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

Excel
, Microsoft Excel . Excel . ,
. , Excel 2003
, . , ? Excel
. , .
- , , , .

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

132

Excel 2002, , .
. ,
. ,
. ,
.

II. Excel


, , , , . ,
.

. ,
Excel. , , . , , .

,
. . ,
,
.
. , , , Excel. , , .
, . , ,
- .

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


,
: . Windows-.
Excel-
. , ,
, .
, . ,
?

6.

133

, , . ,
.

24 .

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

, ,
. Excel, , ,
, , , ,
, . : .

?
. , . , , . VBA,
( , , ). VBA , , , .


.
? . .
. , ,
. .
.
,
VBA.
Excel 2000 Microsoft Authenticode,
.
,
, , . ,
. ( , ).
Web- Microsoft.

134

II. Excel

Excel?
,
, Excel.
Excel . , , : Microsoft Excel? , , . , Excel (
).
, Microsoft Excel
.
: , - . , ,
, .
Microsoft
Excel. Excel Excel. , . Web- Microsoft
(http://officeupdate.microsoft.com).


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


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

Excel,
Excel . Excel 2003 ,
- Excel 95,
Excel 97 .

6.

135

, , , , , Excel 95, Excel.


, Excel 95, Excel 97, Excel 2000
Excel 2002, (Excel 95),
.
, Excel. Microsoft . , Excel 2000, Excel 2000 SR-1 Excel 2000 SR-2.
26.

, ,
Excel. ,
. .
26.


,
. , , , .
,
. , ,
. ,
, , . ,
, .

VBA, , . . , ,
.

Windows : 640480 (.. VGA), 800600 1024768. , VGA, ,


VGA-, .
, . ,
, 800600,
VGA- . ,
, (.. ) -

136

II. Excel

. ,
, , , VGA-.
, Windows
, VGA . , VGA. ,
,
. , , ,
, VGA.
( 10),
VBA. , , .

6.

137

III
Visual Basic for
Applications

7. Visual Basic for Applications


8. VBA
9. VBA
10.
11.
VBA

Visual Basic
for Applications

Excel, , . , , Excel.
VBA , Excel
VBA
Visual Basic
Visual Basic
Excel
, ,
Comment
Range
, Excel
VBA, ,
Excel.

BASIC

BASIC . ( Beginners All-purpose Symbolic
Instruction Code )
, . , BASIC 1960- . BASIC
, .
BASIC . ,
. , .
BASIC . , .
BASIC 1991 , Microsoft
Visual Basic Windows. Windows. Visual Basic BASIC, , VBA.

VBA
Excel 5 ,
Visual Basic for Applications (VBA). VBA
Microsoft, Office 2003 . , VBA Excel,
Microsoft (, ).
, ,
.


VBA . , VBA
, (Excel, Word, Access, PowerPoint ..)
.
, .
, Excel
, , , , , ,
, , . VBA . VBA Excel
.
. , , !

VBA XLM
Excel 5 (
) XLM. Excel
XLM, , Excel 97, XLM. XLM ( , , ), VBA.
. 7.1 7.2 , XLM VBA.
.
. , , VBA . ( ), VBA .

. 7.1. ,
XLM Excel

142

III. Visual Basic for Applications

. 7.2. , VBA Excel


VBA

VBA
,
, . , .
VBA.
VBA VBA.
( ) VBA, VBA.
VBA .
, , , .
Test:
, .
Sub Test()
Sum = 1 + 1
MsgBox ": " & Sum
End Sub

Sub VBA .
( ). VBA .
AddTwo.
Function AddTwo(arg1, arg2)
AddTwo = arg1 + arg2
End Function

VBA ,
( Excel).
Excel , ,
, , , . , VBA.
.
. , Excel
Application, , ,

7. Visual Basic for Applications

143

Workbook ( ). Workbook ,
, Worksheet ( ) Chart (). Worksheet
, , Range (), PivotTable (
) .. Excel.
.
, Worksheets
, CommandBars CommandBar.
.
, ,
-.
, 1.xls
.
Application.Workbooks("1.xls")

1.xls Workbooks.
Workbooks Application.
, 1 1.xls.
Application.Workbooks("1.xls").Worksheets("1")

, .
Application.Workbooks("1.xls").Worksheets("1").Range("A1")

Excel .
1 ,
.
Worksheets("1").Range("A1")

, 1 ,
.
Range("A1")

.
. ,
, Value () Name ().
, HasTitle () Type ().
VBA, .
.
, 1 1 :
Worksheets("1").Range("A1").Value

144

III. Visual Basic for Applications


, . , , VBA. Excel
.
Excel Workbook ( ).
. Excel
; Workbook (
Workbooks).
Restaurants.
Excel , , ,
, , VBA .. ,
. , Worksheet ( ) Range (), PivotTable ( ), Shape () ..
: ( )
, , Kitchen, DiningArea Tables (
). ,
Restaurant. , Tables .
. , Kitchen
Stove (), VentilationFan (), Chef (-), Sink () ..
. , .
Excel . , Range
Value Name, Shape Width, Height ..
. , Stove
, Temperature
NumberOfBurners. VentilationFan (TurnedOn
(), RPM ( ) ..).
, Excel ,
. , ClearContents Range.
.
ChangeThermostat ( ) Stove SwitchOn ()
VentilationFan.
Excel . ClearContents
Range Value Range. ,
ChangeThermostat Stove Temperature.
VBA Excel. ( ).

VBA. , .
1 1
Interest, VBA.
Interest = Worksheets("1").Range("A1").Value

.
, . ,
Range ClearContents.
.

7. Visual Basic for Applications

145

, .
, 1
.
Range("A1").ClearContents

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

Visual Basic
Excel 97, VBA- ,
Excel. VBA
Visual Basic (VBE Visual Basic Editor).
, . VBE VBA- Excel.

VBA ;
, VBE.

VBE
Excel VBE
.
<Alt+F11>.
Visual Basic.
Visual Basic, Visual Basic.

Visual Basic Editor Microsoft Script


Editor. . HTML, VBScript JavaScript.
.

. 7.3 Visual Basic. , VBE


, . : , , ,
..

146

III. Visual Basic for Applications

. 7.3. Microsoft Visual Basic

VBE
VBE .
Visual Basic.


VBE, , , . , VBE. , . , ViewImmediate Window ( ) <Ctrl+G>.

VBE .
VBE, ,
.


Standard,
, , VBE
( ). VBE , Excel: , , .. VBE ViewToolbarsCustomize
( ).

7. Visual Basic for Applications

147

PROJECT EXPLORER
Project Explorer Excel ( ).
.
Visual Basic Project Explorer ,
<Ctrl+R>. ,
( Hide
() ).

( Module) VBA.
. , Project Explorer. , 1, 1
Project Explorer. VBA-, .

Project Explorer, View Code ( ) Project Explorer.
.


VBA,
. .
Immediate ,
<Ctrl+G>. Immediate,
(
Hide ).

Project Explorer
Visual Basic Excel . , .
, Project Explorer.
.
, Toggle
Folders ( ) Project Explorer.
, , .
. 7.4 Project Explorer (
).

VBE
,
Project Explorer. ,
, Project Explorer.
. 7.4. Project Explorer

148

III. Visual Basic for Applications

Excel , Project Explorer


. , Project Explorer . ,
.
Microsoft Excel Objects. ( ),
, ActiveWorkbook.
VBA, Modules,
. Forms, UserForm ( ,
). ,
Class Modules.

VBA
VBA,
Project Explorer InsertModule ().
InsertModule
.

Excel VBA
.

VBA
VBA ,
Project Explorer FileRemove xxx ( xxx
). , Remove xxx .

. ,
( ), (,
1).


, References,
. . ,
. ,
(, VBA UserForm) .
, Project Explorer
FileExport File ( <Ctrl+E>).
, . ,
( ).
UserForm, , UserForm.
, Project Explorer
FileImport File. , . ,
FileExport File.

7. Visual Basic for Applications

149

UserForm,
. ,
, Project Explorer .


VBA, , . .
:
( Project Explorer);
(, 1 1
Project);
VBA;
( ,
);
UserForm.


VBE , .
Excel. , , ,
.. , , ,
. ,
. ,
.
, .
,
.
, . ,
,
. ,
Project Explorer.
VBE . Excel . Immediate,
. Immediate,
VBA ( ) <Enter>.
Workbooks("myaddin.xla").Close

, Close Workbook, . .

VBA
, .
. , .

150

III. Visual Basic for Applications

. ,
( VBA Excel).
. , .
, VBA. ,
, .
VBA ,
. VBA .
VBA VBA;
.

, , . .
Excel . :
Sub ( ),
. . ,
Sub .
9 10.

,
VBA,
. , . , , , . ,
( 19) UserForm ( IV).

VBA
,
VBA . VBA .
VBA. ( )
VBA.
VBA .
: .
Excel,
VBA.
,
.


.
, ..
. <Tab> , (, If End If).

7. Visual Basic for Applications

151

, ,
. .
VBA .
, , ,
.
VBA .
. , <Enter> . ,
VBA, .
MsgBox " " & UCase(SHORTCUTMENUFILE) _
& vbCrLf & vbCrLf & " _
" & ThisWorkbook.Path & vbCrLf & vbCrLf & _
", BudgetMan", vbCritical, APPNAME

, . , ,
.

Excel, VBE .
, ,
Undo () <Ctrl+Z>, .
Redo (),
, . , .

: VBA, .
Sub SayHello()
Msg = " " & Application.UserName & "?"
Ans = MsgBox(Msg, vbYesNo)
If Ans = vbNo Then
MsgBox " ."
Else
MsgBox ", !"
End If
End Sub

. 7.5 , VBA.

. 7.5. VBA

152

III. Visual Basic for Applications

, VBE . , (=), VBE . , . , .

SayHello , . .
1. <F5>.
2. RunRun Sub/UserForm.
3. Run Sub/UserForm .
, . (. 7.6), , .
Excel. ,
Excel. ;
, .

. 7.6.
, . 7.6

Excel.
, VBE.

VBA ( ). , VBE . ,
VBE, Excel , . , .

( ).
( ).
(Msg Ans).
( &).
VBA (MsgBox).
VBA (vbYesNo vbNo).
If-Then-Else.
( ).
, ?

7. Visual Basic for Applications

153


VBA
Excel.
, SayHello . ,
. .
, ,
. ,
.
1. ( ).
2. .
3. Excel .
4. , .
5. Excel VBA .
, Excel VBA.
, ,
,
( ).
6. .
7. Excel .
8. ,
.
9. (
).
10. Excel .
, VBE ( <Alt+F11>) Project Explorer. Modules, .
Module1, (
Module1, Module2).
, , 7.1.
Excel 2003, , .
7.1.
Sub 1()
'
' 1
' 19.08.2003
'
'
With ActiveSheet.PageSetup
.PrintTitleRows = ""
.PrintTitleColumns = ""
End With
ActiveSheet.PageSetup.PrintArea = ""
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = ""
.RightHeader = ""
.LeftFooter = ""

154

III. Visual Basic for Applications

.CenterFooter = ""
.RightFooter = ""
.LeftMargin = Application.InchesToPoints(0.787401575)
.RightMargin = Application.InchesToPoints(0.787401575)
.TopMargin = Application.InchesToPoints(0.984251969)
.BottomMargin = Application.InchesToPoints(0.984251969)
.HeaderMargin = Application.InchesToPoints(0.5)
.FooterMargin = Application.InchesToPoints(0.5)
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 1200
.CenterHorizontally = False
.CenterVertically = False
.Orientation = xlLandscape
.Draft = False
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = 100
.PrintErrors = xlPrintErrorsDisplayed
End With
End Sub

, , ( ). , , Excel
, .
, , , .
, , , . , . .
Sub 1
With ActiveSheet.PageSetup
.Orientation = xlLandscape
End With
End Sub

, , Orientation.
,
With-End With .
Sub 1
ActiveSheet.PageSetup.Orientation = xlLandscape
End Sub

Orientation PageSetup
. , xlLandscape , . xlLandscape
2, xlPortrait 1. ,
1.
Sub 1
ActiveSheet.PageSetup.Orientation = 2
End Sub

7. Visual Basic for Applications

155

,
. , .
VBA,
, , .
. ,
PageSetup Orientation.

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

VBA
VBA.
VBA . , , . , ,
,
, VBA.
, .

, ,
.

VBE
Excel , VBE. , .
VBE ToolsOptions ().
: Editor (), Editor Format
( ), General () Docking ().
.
, Excel,
Excel .
, , .

Editor
. 7.7 , Editor Options.

AUTO SYNTAX CHECK


Auto Syntax Check ( ) ,
, VBE

156

III. Visual Basic for Applications

VBA. .
, VBE , ,
, .

. 7.7. Editor Options

Auto Syntax Check, , . VBA, .

REQUIRE VARIABLE DECLARATION


Require Variable Declaration ( ) VBE .
Option Explicit

,
. , , , , . , Variant; ,
(. ).

Require Variable Declaration , .

AUTO LIST MEMBERS


Auto List Members ( ), VBE
VBA,
. ,
.
, . . 7.8 Auto List Members ( , VBA ).
VBE Application. , ( ).

7. Visual Basic for Applications

157

. 7.8. Auto List Members

AUTO QUICK INFO


Auto Quick Info ( ), VBE
, , . , . . 7.9 :
Range.

. 7.9. Auto Quick Info, Range

AUTO DATA TIPS


Auto Data Tips, VBE
, . VBE, . .

AUTO INDENT
Auto Indent ( ) , VBE ,
. , ,
.
( 4).

158

<Tab>, , . ,

<Shift+Tab>, .

III. Visual Basic for Applications

DRAG6AND6DROP TEXT EDITING


Drag-and-Drop Text Editing ( ) ,
. , ,
, .

DEFAULT TO FULL MODULE VIEW


Default to Full Module View (
) . ,
. ,
.
.

PROCEDURE SEPARATOR
Procedure Separator ( ) , . , .

Editor Format
. 7.10 Editor Format Options.

CODE COLORS
Code Colors ( )
( ) ,
VBA. , , . , . .

FONT
Font () ,
VBA.
(, Courier New).
, ,
, , .

. 7.10. Editor Format Options

7. Visual Basic for Applications

159

SIZE
Size () VBA.
, , , . 10.

MARGIN INDICATOR BAR


,
. ;
.

General

. 7.11 , General () Options.


.

Error Trapping ( ) , . , ,
Break on Unhandled Errors (
). Break on All Errors (
) (
). 9.

Docking
. 7.12 Docking Options.
VBE , . , VBE.
, .
, ,
. , .
. ,
Project Explorer . . ,
.

. 7.11. General
Options

160

. 7.12. Docking
Options

III. Visual Basic for Applications

VBE
. . , ,
:
, .


, Excel VBA. .

Visual Basic Excel


. , ,
Visual Basic.

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

.
, .


, Excel , , VBA. , .
.
1. .
2. , Excel . , .
3. <Alt+F11>, VBE, , .
4. Excel VBE , .
( .)
5. Excel,
, .

6. Excel ( Module1)
.
7. VBE.
8. Project Explorer Module1, .
9. Project Explorer, .

7. Visual Basic for Applications

161

Visual Basic , . 7.13.


.
, Excel. , , VBA. : , , .
, ,
.. ,
.

?
Excel
. , Excel
( , ). ,
. .
1. .
2. 1.
3. 1 .
4. 1 .
5. , 1:G1 .

. 7.13.

162

III. Visual Basic for Applications

6. 1, .
7. .
Excel .
Sub Macro()
Range("B1").Select
ActiveCell.FormulaR1C1
Range("C1").Select
ActiveCell.FormulaR1C1
Range("D1").Select
ActiveCell.FormulaR1C1
Range("E1").Select
ActiveCell.FormulaR1C1
Range("F1").Select
ActiveCell.FormulaR1C1
Range("G1").Select
ActiveCell.FormulaR1C1
Range("B1").Select
End Sub

= ""
= ""
= ""
= ""
= ""
= ""

,
( <Alt+F8>), 1 ( )
.
, .
,
.
.
, . , . .
,
. Excel,
.
-. ,
. , . , .
, B1:D1,
.
1. B1.
2. .
3. , .
4. (
), .
5. .
6. B1:G1 ( ).
7. 1.
8. .

7. Visual Basic for Applications

163

, Excel
.
Sub Macro2()
ActiveCell.FormulaR1C1 = ""
ActiveCell.OffSet(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = ""
ActiveCell.OffSet(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = ""
ActiveCell.OffSet(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = ""
ActiveCell.OffSet(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = ""
ActiveCell.OffSet(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = ""
ActiveCell.OffSet(0, 1).Range("A1").Select
End Sub

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

, ,
1 , 1
. . ( Offset .)
, , .

, , Excel, , , .
, ,
. ,
, .
Sub Macro3()
ActiveCell.Offset(0,
ActiveCell.Offset(0,
ActiveCell.Offset(0,
ActiveCell.Offset(0,
ActiveCell.Offset(0,
ActiveCell.Offset(0,
End Sub

0)
1)
2)
3)
4)
5)

=
=
=
=
=
=

""
""
""
""
""
""

, With-End With.
Sub Macro4()
With ActiveCell
.Offset(0, 0) =
.Offset(0, 1) =
.Offset(0, 2) =
.Offset(0, 3) =

164

""
""
""
""

III. Visual Basic for Applications

.Offset(0, 4) = "Ma"
.Offset(0, 5) = ""
End Sub

VBA ( ),
, .
Sub Macro54()
ActiveCell.Resize( ,6)=Array("", "", "", "", "", "")
End Sub

, ,
, .
, .


VBA
. , . .
.


.
Excel 1, 2 .. . . .



. , w ( ),
<Ctrl+W>. W
( ) <Ctrl+Shift+W>.
,
.


Excel, , . Excel
.
(Excel ), .


VBA, ,
.
Personal.xls, Xlstart.
. Personal.xls ,
.

Excel ( ).
, . , . -

7. Visual Basic for Applications

165

,
.
Excel, , Excel 97,
, .
Excel , ,
(. 23).


, ,
( )
VBA. ,
.
, . , : , Excel , (.. ),
Selection.
, ( ) .
Range("A1:C5").Select
Selection.NumberFormat = "#,##0.00"
Selection.Font.Bold = True
Selection.Font.Italic = True

, , Excel .
.

.
With-End With.
Range("A1:C5").Select
With Selection
.NumberFormat = "#,##0.00"
.Font.Bold = True
.Font.Italic = True
End With

Select .
With Range("A1:C5")
.NumberFormat = "#,##0.00"
.Font.Bold = True
.Font.Italic = True
End With

,
VBA,
.
, VBA,
. , VBA
.

166

III. Visual Basic for Applications


VBA,
.
.
, .
.
Range("A1").Value
, .
MsgBox.
MsgBox Range("A1").Value
, VBA
.
Sub Test()
'
End Sub
<F5>, .
, , . , 1, ,
1.
. Immediate. Immediate . Immediate , , VBE, <Ctrl+G>.
Immediate VBA <Enter>.
Immediate, (?).
Print. , Immediate .
? Range("A1").Value
Immediate.


, VBA VBA Visual
Basic. , VBA
, .
.
VBA, Excel. . Application
, Excel. VBA, VBE Microsoft
Word, Application Word.

7. Visual Basic for Applications

167


Application (.. Excel) .
, Application.
Workbooks ( Workbook );
Windows ( Window );
AddIns ( AddIn ).
. ,
Workbooks Workbook, Workbook , .
Worksheets ( Worksheet );
Charts ( Chart );
Names ( Name ).
, , .
Worksheets Worksheet
Workbook. Worksheet , .
ChartObjects ( ChartObject );
Range ;
PageSetup ;
PivotTables ( PivotTable ).
, ,
,
. , Excel
.


VBA
. (
). , Workbooks Workbook. Worksheets
Worksheet, Workbook. . ,
.
Worksheets("1")

1 ,
.
Worksheets(1)

Workbook Worksheets(2) ..

168

III. Visual Basic for Applications

, Sheets,
: . 1
, .
Sheets(1)


VBA,
, . , Excel , 1? .
Workbooks("1").Worksheets("1")

Visual Basic 1
.
(, 1)
1 1,
.
Workbooks("1").Worksheets("1").Range("A1")

Application .
Application.Workbooks("1").Worksheets("1").Range("A1")

Application
( ). 1 , .
Worksheets("1").Range("A1")

1 ,
.
Range("A1")

Excel .
Range, .

( ) .
,
, .


: .
, .


. , Range
Value. VBA, Value
Value . ,

7. Visual Basic for Applications

169

VBA MsgBox ,
1 1 .
Sub ShowValue()
MsgBox Worksheets("1").Range("A1").Value
End Sub

MsgBox ,
VBA. .

Value 1 1 . , 1,
.
, Value? 1 Value.
Sub ChangeValue()
Worksheets("1").Range("A1").Value = 123
End Sub

1 1 123.
.

. Range
Value. , .Value
, .
, .


, . ,
.
Clear .
1:3 1 ,
.

Sub ZapRange()
Worksheets("1").Range("A1:C3").Clear
End Sub

, ,
ClearContents Range.
,
. , 1
1 Copy Range. Copy ( , ).
, ( ). , .
Sub CopyOne()
Worksheets("1").Range("A1").Copy _
Worksheets("1").Range("B1")
End Sub

170

III. Visual Basic for Applications


VBA .
; . .
,
. , , . Protect .
, Protect : , , .
.
, MyBook.xls,
.
Workbooks("MyBook.xls").Protect "xyzzy", True, False
( 1).
( 2), ( 3).
, .
Workbooks("MyBook.xls").Protect , True, False
, , .
( )
. .
Workbooks("MyBook.xls").Protect , Structure:=True, Windows:=False
, , .

.
, , . , Address Range .
, .
MsgBox Range("A1").Address False

'

.
MsgBox Range("A1").Address(False)
, .
MsgBox Range("A1").Address(rowAbsolute:=False)
,
, .

7. Visual Basic for Applications

171

Comment:
, Comment. Comment
Excel .

. , . .

Comment
. . 7.14 Comment.
,
, . ,
Properties,
Comment, Methods, .


,
<F1>. , .
, , , , ,
, . Comment
<F1>. Comment ,
. ,
Comment; , Comment.

. 7.14. Comment

172

III. Visual Basic for Applications

Comment
Comment . . 7.1 . ,
, VBA , .

7.1. Comment

Application

, ,
(.. Excel)

Author

Creator

, , . Excel
Windows ( Excel Macintosh)

Parent


( Range)

Shape

Shape,
,

Visible

True,

Comment
. 7.2 , Comment.
,
.

7.2. Comment

Delete

Next

Comment,

Previous

Comment,

Text

( )

, , Text , . :
, .
, .
, ,
.

Comments
, .
Comments, Comment . , .
, 1
.
Worksheets("1").Comments(1)

7. Visual Basic for Applications

173

,
1.
MsgBox Worksheets("1").Comments(1).Text

, Comment Name.
, , ,
Comment
Range (. ).
Comments , . , .
MsgBox ActiveSheet.Comments.Count

Count Comments,
Comment .
, .
MsgBox ActiveSheet.Comments(1).Parent.Address

Comments(1) Comment
Comments. Parent Comment , Range. Address
Range. , .
, , For Each-Next ( 8).
.
For Each cmt in ActiveSheet.Comments
MsgBox cmt.Text
Next cmt

,
, Intermediate.
For Each cmt in ActiveSheet.Comments
Debug.Print cmt.Text
Next cmt

Comment
Comment. ,
Range Comment. , Comment Comment. ,
Comment 1.
Range("A1").Comment

, Comment
.
Comments(1)

1 ,
.
MsgBox Range("A1").Comment.Text

174

III. Visual Basic for Applications

1 , .

, , (,
, VBA).

, Comment
,
. ,
1. Comment, , . .
1. Shape Comment, Shape,
.
2. Fill Shape, FillFormat.
3. ForeColor FillFormat,
ColorFormat.
4. RGB ( SchemeColor) ColorFormat,
.
, Comment , .
.
Application (Excel)
Workbook
Worksheet
Comment
Shape
FillFormat
ColorFormat
, !
VBA ,
.
Worksheets("1").Comments(1).Shape.Fill.ForeColor _
.RGB = RGB(0, 255, 0)

SchemeColor (
0 80).
Worksheets("1").Comments(1).Shape.Fill.ForeColor _
.SchemeColor = 12

,
. , , , Excel
.

7. Visual Basic for Applications

175

?
VBA
, . : Excel 56- , .
, (
, ). VBA? ,
VBA, , .
. , , .
Shape RGB SchemeColor.
RGB , . RGB, ,
0 255. RGB 0
16777215. Excel, , 56 .
, RGB, 56- . SchemeColor
0 80. , .
.
Range
Interior. : Color
ColorIndex. ColorIndex 0 56
(0 ). .
, , , ColorIndex, ColorIndex
. ,
.
ColorIndex , .
Color
RGB. ,
, .

, , TextFrame
Comment, Characters, , ,
Font. Color ColorIndex Font.
, ColorIndex 5.
Worksheets("1").Comments(1) _
.Shape.TextFrame.Characters.Font.ColorIndex = 5

?
1 .
MsgBox Range("A1").Comment.Text

1 , : Object variable or With block variable


not set.
, , ,
, Comment, .. Nothing ( -

176

III. Visual Basic for Applications

VBA). True,
1 .
MsgBox Range("A1").Comment Is Nothing

, Is,
.

Comment
, , Comment
. ,
AddComment Range.
() 1 .
Range("A1").AddComment

, , AddComment
, . , .
Range("A1").AddComment " JW"

AddComment , .

Comment
, -.
Comment VBA. , , , VBA .

Application
, Excel
. ,
( ).
VBA , . , ,
, . VBA
Application . , Application ActiveCell, .
1 .
ActiveCell.Value = 1

, Application,
. ,
, . , VBA
, , ,
.
, . ,
( ).
Application Selection, , .. (),
ChartObject, TextBox, Shape.

7. Visual Basic for Applications

177

. 7.3 Application,
.

7.3. Application

ActiveCell

ActiveChart


. , Nothing

ActiveSheet

( )

ActiveWindow

ActiveWorkbook

RangeSelection

,
(
Window)

Selection

( Range, Shape, ChartObject ..)

ThisWorkbook


, , ,
, . VBA, ,
. , , .
ActiveCell.ClearContents

,
.
MsgBox ActiveSheet.Name

, .
MsgBox ActiveBook.Name

, , . Selection
Application Range, . Value Range, , .
Selection.Value = 12

: (, ChartObject
Shape), , ChartObject Shape
Value.
Range, ( ), 12.
, RangeSelection
Window.
ActiveWindow.RangeSelection.Value = 12

178

III. Visual Basic for Applications

, ,
Count.
MsgBox ActiveWindow.RangeSelection.Count

Range
, , VBA,
, . VBA , .
Range Worksheet
. Range VBA.
Range Worksheet Range.
Cells Worksheet.
Offset Range.

Range
Range Range.
Range ,
.
.Range(1);
.Range(1, 2).

Range : Worksheet
Range. 1 2 , Excel ( )
( ).
Range.
, .
, : 1
1 1 .
Worksheets("1").Range("A1").Value = 1

Range , .
, .
Worksheets("1").Range("").Value = 1

20-
. , .
ActiveSheet.Range("A1:B10").Value = 2

, .
Range("A1", "B10") = 2

7. Visual Basic for Applications

179

, , . , , ( Range Value).
Range.
,
.

Excel (). 6.
, 3 6.
Range("C1:C10 A6:E6") = 3

, 4 , .. . .
Range("A1,A3,A5,A7,A9") = 4


Range Worksheet. Range
Range. , .
Range Range ( Range ). Range . ,
2, 5. , Range. ,
5 , .
ActiveCell.Range("B2") = 5

Offset (. ).

Cells
Cells.
Range, Cells Worksheet
Range. Cells.
.Cells(_, _);
.Cells(_);
.Cells.

Cells.
A1 1 9.
, ( 1 65536)
( 1 256).
Worksheets("1").Cells(1, 1) = 9

, 7 D3 (.. 3, 4) .
ActiveSheet.Cells(3, 4) = 7

Cells Range.
Range, Cells,
Range, . ? .

180

III. Visual Basic for Applications

. 5 . ,
1 .
ActiveCell.Cells(1, 1) = 5

, (. 8). .
.

5 , ,
.
ActiveCell.Cells(2, 1) = 5

: ,
1.
.
Cells ,
1 16777216.
(65536 256 ). , 1 ,
. 256- IV1, 257- 2.
3 (520- )
2.
ActiveSheet.Cells(520) = 2

(IV65536),

MsgBox ActiveSheet.Cells(16777216)

Range. Range. ,
Range A1:D10 (40 ), Cells
1 40 Range.
2000 2, 2 ( ,
) .
Range("A1:D10").Cells(5) = 2000

Cells
1 40. , , , . , ,
, ,
A1:D10.

Cells
. , , . ClearContents ,
Cells .
.
ActiveSheet.Cells.ClearContents

7. Visual Basic for Applications

181

Offset
Offset ( Range Cells) Range.
, Offset Range
. .
.Offset(_, _)

Offset
Range. ( ), ( ) .
12 ,
.
ActiveCell.Offset(1,0).Value = 12

15 .
ActiveCell.Offset(-1,0).Value = 15

1, Offset
, Range.
Offset
(. ).
Excel
Offset (.. ). , .
( 1), 1:3,
1.
Sub Macro1()
ActiveCell.FormulaR1C1 = "1"
ActiveCell.Offset(1, 0).Range("A1").Select
ActiveCell.FormulaR1C1 = "2"
ActiveCell.Offset(1, 0).Range("A1").Select
ActiveCell.FormulaR1C1 = "3"
ActiveCell.Offset(-2, 0).Range("A1").Select
End Sub

FormulaR1C1. ,
Value. FormulaR1C1
Formula .
, 1
, .
, . Range("A1"),
.
Sub Modified Macro1()
ActiveCell.FormulaR1C1 = "1"
ActiveCell.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "2"
ActiveCell.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "3"
ActiveCell.Offset(-2, 0).Select
End Sub

182

III. Visual Basic for Applications

( , ), .
Sub Macro1()
ActiveCell = 1
ActiveCell.Offset(1, 0) = 2
ActiveCell.Offset(-2, 0) = 3
End Sub


( ), . .

,
, , VBA. VBA,
.
.
.
(, Name)
(, Delete).
.

Excel, XLM.
, ,
. Excel .
, .
.
, , . ,
Workbook Myfile
Workbooks .
Workbooks("Myfile.xls")

, .
. ,
Font Font, Range.
Range("A1").Font.Bold = True

,
.
, Sales, . Summary.
.

7. Visual Basic for Applications

183

Workbooks("Sales.xls").Worksheets("Summary")
Workbooks(1).Worksheets(1)
Workbooks(1).Sheets(1)
Application.ActiveWorkbook.ActiveSheet
ActiveWorkbook.ActiveSheet
ActiveSheet

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


VBA, , . ,
, .
, .
, , .


, Visual Basic for Applications.
,
.


, VBA
, Excel.
, , . , VBA, .


,
Excel .
. 7.15 Value.
,
See Also (. ), Applies To ( ) Example (). See Also,
( ). Applies To , , .
Example,
( VBA,
).


Object Browser ( ) , . VBE
Object Browser .

184

III. Visual Basic for Applications

<F2>.
ViewObject Browser.
Object Browser .
Object Browser . 7.16.

. 7.15. VBE

. 7.16.

7. Visual Basic for Applications

185

Object Browser , .
Excel.
MSForms ( ).
Office (, Microsoft Office).
Stdole ( OLE).
VBA.
( ,
).
, Classes
(), Classes
Members of ( ).
,
, . , . , ,
.
1. . ,
, <All Libraries>.
2. Comment .
3. , .
Search Results ( ) ,
. ,
Classes. , (, ).
, . <F1>, .
Object Browser , , ,
.

IMMEDIATE
,
Immediate VBE VBA. Immediate ,
.

186

III. Visual Basic for Applications

VBA

VBA,
.
VBA.
VBA: , ,
VBA


,
. VBA
,
.

VBA.
7 , .
.
: VBA, ,
VBA.
.
VBA 100 .
.
Sub VBA_Demo()
' VBA
Dim Total As Integer, i As Integer
Total = 0
For i = 1 To 100
Total = Total + i
Next i
MsgBox Total
End Sub

,
( ), (Total),
(Total = 0 Total = Total + i), (For-Next)
VBA (MsgBox).
.

VBA . ,
.

, . VBA . (
).
. . VBA
, , . ,
, .
Msg = "Can't continue"

VBA .
Sub Comments()
'

x = 0
'x
'

MsgBox x
End Sub

, ,
Rem.
Rem

Rem , , BASIC;
VBA . , Rem
, ,
.
,
. ,
, .
. , ,
.
Sub BadComments()
'

Dim x As Integer
Dim y As Integer
Dim z As Integer
'

x = 100 ' x 100
y = 200 ' y 200
'
x y z
z = x + y
'

MsgBox z
End Sub

188

III. Visual Basic for Applications

VBA
VBA, VBA, .
. , . .
Sub OneLine()
x=1: y=2: z=3: MsgBox x + y + z
End Sub
, ,
.
Sub OneLine()
x=1
y=2
z=3
MsgBox x + y + z
End Sub
; VBA ,
. VBA: ( _).
Sub LongLine()
SummedValue = _
Worksheets("1").Range("A1").Value + _
Worksheets("2").Range("A1").Value
End Sub
Excel
.
Visual Basic .
. , Ans=1+2
( ), VBE .
Ans = 1 + 2
VBA , .

Result=activesheet.range("a1").value=12
VBA
Result = ActiveSheet.Range("a1").Value = 12
, ( , "a1") .
VBA ,
, ,
, .
, myvalue (
) MyValue ( ), VBA
MyValue.

8. VBA

189

, Dim , ,
.
VBE . VBE
, , ,
. ToolsOptions VBE,
Options. ,
( Editor Format) ( Auto Syntax Check Editor).

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

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

Edit VBE .
, Comment Block,
. Uncomment Block . ,
.

,
VBA . , , . .

. , , (True False)
(. ).
( ).
,
. , VBA
, .
,
, .

190

III. Visual Basic for Applications

VBA . ,
(, InterestRate,
interestrate).
. , (Interest_Rate).
(#, $, %, & !) .
254 !
, .
.
, .
x =1
InterestRate = 0.075
LoanPayoffAmount = 234089
DataEntered = False
x = x + 1
MyNum = YourNum * 1.25
UserName = "Bob Johnson"
DateStarted = #3/14/98#

VBA , .. ,
.
, .
, , Next , .
Next = 132

, . : Compile
error: Expected Variable ( : ).
, , , VBA .


VBA ,
.
. ,
, ..
.
, : , , .. VBA , . , VBA ,
.
, . -

8. VBA

191


, VBA ,
.
. 8.1 VBA ( ,
,
).

8.1. VBA

Byte

0 255

Boolean

True () False ()

Integer

32768 32767

Long

2147483648 2147483647

Single

3,40282338 1,401298-45 ( ); 1,401298-45


3,40282338 ( )

Double

1,79769313486232308
4,94065645841247-324 (
); 4,94065645841247-324
1,79769313486232308 (
)

Currency

922337203685477,5808
922337203685477,5807

Decimal

14

+/79228162514264337593543950335
;
+/7,9228162514264337593543950335
28-

Date

1 100 31 9999

Object

String ( 10 +
)
String

( )

0 2 .
1 65400

Variant ()

16

Double

Variant ()

22 +

0 2 .

Decimal Excel 2000


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

,
,
. VBA
,
VBA. , ,
VBA .

192

III. Visual Basic for Applications

Excel
Double. VBA
.
Integer, , , , 32767. Long.
Excel
Long, ,
Integer.


, VBA,
Variant. Variant
: , , . , .
Sub VariantDemo()
MyVar = "123"
MyVar = MyVar / 2
MyVar = ": " & MyVar
MsgBox MyVar
End Sub

VariantDemo MyVar
. .
MyVar , MyVar
. MsgBox : : 61,5.
,
Variant, .
Sub VariantDemo2()
MyVar = "123"
MyVar = MyVar + MyVar
MyVar = ": " & MyVar
MsgBox MyVar
End Sub

:
123123. , , .
, Variant, + .


VBA TypeName.
.
MyVar. ,
, Double
.
Sub VariantDemo2()
MyVar = "123"
MsgBox TypeName(MyVar)
MyVar = MyVar / 2
MsgBox TypeName(MyVar)
MyVar = ": " & MyVar
MsgBox TypeName(MyVar)
MsgBox MyVar
End Sub

8. VBA

193

VBA .
, ,
.


, , ,
.
Sub TimeTest()
Dim x As Integer, y As Integer
Dim A As Integer, B As Integer, C As Integer
Dim i As Integer, j As Integer
Dim StartTime As Date, EndTime As Date
'

StartTime = Timer
'

x = 0
y = 0
For i = 1 To 5000
For j = 1 To 1000
A = x + y + i
B = y x i
C = x y i
Next j
Next i
'

EndTime = Timer
'

MsgBox Format(EndTime StartTime, "0.0")
End Sub
4,0 ( , , ). Dim,
(.. Dim , ), VBA Variant.
. 8,3
.
, , VBA- ,
!

.
. .
. , Variant, , ,
, .
,
,
.

194

III. Visual Basic for Applications

, . , Option
Explicit, (.
). , CurrentRate.
CurentRate = 0.75. , , ,
.


, VBA.
Option Explicit

,
. VBA ;
.

Option Explicit VBA, Require Variable Declaration (


) Editor Options VBE.
.


,
. .

Dim Static

Dim
Private

Public

,
VBA,
.
. ,
. , .
.


, .
, .
,
Excel .

8. VBA

195

, Static (. Static).

Dim Sub End Sub. Dim Sub, .


Dim, ,
Dimension (). BASIC
. VBA
Dim , .
,
Dim.
Sub MySub()
Dim x As Integer
Dim First As Long
Dim InterestRate As Single
Dim TodaysDate As Single
Dim UserName As String * 20
Dim MyValue
'
-[ ] End Sub

, Dim
, . Variant.
, ,
Dim.
Dim x As Integer, y As Integer, z As Integer
Dim First As Long, Last As Double


BASIC, VBA , . ,
MyVar , %.
Dim MyVar%
VBA
( ).

Integer
Long
Single
Double
Currency
String

%
&
!
#
@
$

BASIC;
, .

196

III. Visual Basic for Applications

, VBA
, . , , , Integer.
Dim i, j, k As Integer

VBA k ,
Variant. i, j k Integer, .
Dim i As Integer, j As Integer, k As Integer

,
, .
, , VBA , , .


, .
(
).
Dim .
MySub YourSub CurrentValue.
Dim CurrentValue As Integer
Sub MySub()
'
-[ ] End Sub
Sub YourSub()
'
-[ ] End Sub

PUBLIC
VBA ,
Public, Dim.
Public CurrentRate as Long

Public CurrentRate
, ,
. . ,
VBA,
.

STATIC
Static .
.
Sub MySub()
Static Counter As Integer
-[ ] End Sub

8. VBA

197


(
, ). , .


Const.
.
Const NumQuarters as Integer = 4
Const Rate = .0725, Period = 12
Const ModName as String = "Budget Macros"
Public Const AppName as String = "Budget Application"

. , Variant. , .
, . , ,
Sub Function .
, .
,
Public .
Public Const InterestRate As Double = 0.0725

VBA
( ). , .

. ,
, , ,
, .
,
, .


Excel VBA ,
.
. , .
(xlLandscape).
Sub SetToLandscape()
ActiveSheet.PageSetup.Orientation = xlLandscape
End Sub

198

III. Visual Basic for Applications


,
. .

. , , , bWasSaved. , ,
Boolean.
.

Boolean
Integer
Long
Single
Double
Currency
Date/Time
String
Object
Variant

b
i
l
s
d
c
dt
str
obj
v
u

xlLandscape . . , AutoList Members,


. VBA , .
xlLandscape 2. xlPortrait 1. , .

Object Browser, 7,
Excel VBA. Object Browser, VBE <F2>.


Excel, VBA , ().
VBA .
. 65535 .
2 . .
1 , , .
Dim , (
), -

8. VBA

199

( ). .
MyString 50 . YourString , .
Dim MyString As String * 50
Dim YourString As String


, , . Date
.
, Date, 8
1 100 31 9999 .
10000 ! Date . VBA
, # (. ).

Excel
Excel ( ) ,
1900 . Excel 29 1900 . Excel
29- 1900- .
=(1900;2;29)
VBA . Excel VBA
DateSerial. () 1 1900 .
=DateSerial(1900,2,29)
, Excel
VBA. 1
1900 1 1900 .

, VBA, , Excel, 1 1900 . , , Excel.


Date.
Dim Today As Date
Dim StartTime As Date
Const FirstDay As Date = #1/1/2001#
Const Noon = #12:00:00#

200

//, (,
//).

III. Visual Basic for Applications

, , . , (12- 24-).

Windows.

- Extended Data Functions.


VBA. Excel
, ,
1 1900 .


VBA, . Excel
, ,
. , . , .
. , VBA, ( ) .
, Excel, VBA. Excel . , VBA
.
VBA (=).
(
).
x = 1
x = x + 1
x = (y * 2) / (z * 2)
FileOpen = True
FileOpen = Not FileOpen
Range("The Year").Value = 2001

.
, (
).

.
VBA, Excel , VBA.
VBA .

VBA .
, (+), (*),
(/), (), (^) (&).
: (\) , Mod .
Mod . , 2.
17 Mod 3

8. VBA

201

VBA , Excel:
(=), (>), (<), (>=), (<=)
(<>).
, VBA (. 8.2).
( ) VBA.

8.2. VBA

Not

And

Or

XoR

Eqv

Imp

VBA , Excel. , , .
Not
. DisplayGridLines True False.
, Not True False, False True.
ActiveWindow.DisplayGridLines = _
Not ActiveWindow.DisplayGridLines

And. MsgBox True, 1


1. , MsgBox
False.
MsgBox ActiveSheet.Name = "1" And ActiveCell.Row = 1

Or. MsgBox
True, 1 2.
MsgBox ActiveSheet.Name = "1" _
Or ActiveSheet.Name = "2"

, ; , . ,
12- , . MonthNames,
MonthNames(0), MonthNames(1)
.., MonthNames(11).

202

III. Visual Basic for Applications


, , Dim
Public. , :
, To
. , , 100
.
Dim MyArray(1 To 100) As Integer

,
VBA . ,
.
Dim MyArray(0 To 100) As Integer
Dim MyArray(100) As Integer
101- .

,
,
.
Option Base 1


.
VBA 60- ,
( ).
100- .
Dim MyArray(1 To 10, 1 To 10) As Integer

1010.
, . ,
.
MyArray(3, 4) = 125

, , .
. .
Dim MyArray() As Integer

,
, ReDim, VBA,
( ReDim Preserve,
). ReDim ,
, , .
.

8. VBA

203


, , ,
. :
;
.
, ,
Dim Public. ,
InputArea Range.
Public InputArea As Range

, , , .
Sub NoObjVar()
Worksheets("1").Range("A1").Value = 124
Worksheets("1").Range("A1").Font.Bold = True
Worksheets("1").Range("A1").Font.Italic = True
End Sub

1 1 ,
.
. ,
.
Sub ObjVar()
Dim MyCell As Range
Set MyCell = Worksheets("1").Range("A1")
MyCell.Value = 124
MyCell.Font.Bold = True
MyCell.Font.Italic = True
End Sub

MyCell Range Set .


MyCell Worksheets("1").Range("A1").

VBA ,
. , , . . , VBA
(, Sheets(1).Range("A1")),
.
. , .
With-End With,
. .

204

III. Visual Basic for Applications


VBA , ,
( Pascal C). . , , CustomerInfo.
Type CustomerInfo
Company As String * 25
Contact As String * 15
RegionCode As Integer
Sales As Long
End Type

,
Dim.
.
Dim Customers(1 To 100) As CustomerInfo

100 (
CustomerInfo). .
Customers(1).Company = "Acme Tools"
Customers(1).Contact = "Tim Robertson"
Customers(1).RegionCode = 3
Customers(1).Sales = 150677

. , Customers(1) Customers(2),
.
Customers(2) = Customers(1)

.
Customers(2).Company = Customers(1).Company
Customers(2).Contact = Customers(1).Contact
Customers(2).RegionCode = Customers(1).RegionCode
Customers(2).Sales = Customers(1).Sales

, VBA
, .
, - .
VBA ( ) Excel. , VBA
UCase, , Excel .
VBA .
.

8. VBA

205

VBA , VBA (.).


VBE VBA ,
(. 8.1). . , , Auto List Members.
ToolsOptions, Editor.

. 8.1. VBA VBE

VBA , Excel
. , VBA.
, Sqr VBA, .
Sub ShowRoot()
MyValue = 25
SquareRoot = Sqr(MyValue)
MsgBox SquareRoot
End Sub

Sqr VBA Excel.


( ) Excel VBA.
WorksheetFunction, Application,
, VBA.
Excel VBA,
.
Application.WorksheetFunction
, Excel VBA. Excel ROMAN
.
Sub ShowRoman()
DecValue = 2001
RomanValue = Application.WorksheetFunction.Roman(DecValue)
MsgBox RomanValue
End Sub

206

III. Visual Basic for Applications

MsgBox
MsgBox VBA.
.
. , , MsgBox,
.
, , . MsgBox , , . , MsgBox,
.
MsgBox, , .
MsgBox (
):
MsgBox([, ][, ][, _, ])
( ) , .
( ) , , ( ) .
(, vbYesNo).
( ) ,
. Microsoft Excel.
_ ( ) , .
( ) .
.
. Ans.
Ans = MsgBox("?", vbYesNo + vbQuestion, "!")
If Ans = vbNo Then Exit Sub
, (vbYesNo + vbQuestion). vbYesNo
: . vbQuestion
(. ). , Ans , vbYes vbNo.
, .

, , MsgBox.

MsgBox MMI.
, , Excel , .

8. VBA

207

, Excel,
VBA . , VBA
(SQRT), VBA
: Sqr. , .

MsgBox Application.WorksheetFunction.Sqrt(123) '

10, VBA , , Excel.


, .
. VBA ,
.
With-End With.
For Each-Next.

With6End With
With-End With
. , , ,
(,
Range).
Sub ChangeFont1()
Selection.Font.Name = "Times New Roman"
Selection.Font.FontStyle = "Bold Italic"
Selection.Font.Size = 12
Selection.Font.Underline = xlUnderlineStyleSingle
Selection.Font.ColorIndex = 5
End Sub

With-End
, , , .

With.

Sub ChangeFont2()
With Selection.Font
.Name = "Times New Roman"
.FontStyle = "Bold Italic"
.Size = 12
.Underline = xlUnderlineStyleSingle
.ColorIndex = 5
End With
End Sub

, .
, .
, , With-End With,

, .

208

III. Visual Basic for Applications

VBA Excel With-End With


. ,
.

For Each6Next
, , . , Workbooks Workbook.
, .
For Each-Next, ,
.
, ,
. For Each-Next.
For Each-Next .
For Each In
[]
[Exit For]
[]
Next []

For Each-Next
.
Sub Macro1()
Dim MyArray(5)
For i = 0 To 5
MyArray(i) = Rnd
Next i
For Each n In MyArray
Debug.Print n
Next n
End Sub

, , For Each-Next Sheets . MsgBox Name . (


, MsgBox .)
Sub CountSheets()
Dim Item as WorkSheet
For Each Item In ActiveWorkBook.WorkSheets
MsgBox Item.Name
Next Item
End Sub

Item (,
Worksheet). Item ;
.

For Each-Next Windows.


Sub HiddenWindows()
Dim AllVisible As Boolean

8. VBA

209

Dim Item As Window


AllVisible = True
For Each Item In Windows
If Item.Visible = False Then
AllVisible = False
Exit For
End If
Next Item
MsgBox AllVisible
End Sub

, AllVisible False
For Each-Next. True
( ) False ( ). Exit For
. For Each-Next.
If-Then (.
).
, .
If-Then
Workbooks.
Sub CloseInActive()
Dim Book as Workbook
For Each Book In Workbooks
If Book.Name <> ActiveWorkbook.Name Then Book.Close
Next Book
End Sub

For Each-Next
, .
Selection , Range,
Range. VBA UCase ,
, (
).
Sub MakeUpperCase()
Dim Cell as Range
For Each Cell In Selection
Cell.Value = UCase(Cell.Value)
Next Cell
End Sub


VBA . (, , ).
, , , .
For Each-Next,
. , VBA.
GoTo.
If-Then.

210

III. Visual Basic for Applications

Select Case.
For-Next.
Do While.
Do Until.

GoTo
GoTo. , ( ,
, , ). VBA
, GoTo
.
VBA InputBox
. ,
WrongName, .
. Exit Sub
.
Sub GoToDemo()
UserName = InputBox(" :")
If UserName <> "" Then GoTo WrongName
MsgBox (", .")
'
-[ ]
Exit Sub
WrongName:
MsgBox ", ."
End Sub

, GoTo, , ,
. , GoTo VBA , (. 9).

If6Then
, If-Then
VBA.
. . Excel, , .
If-Then .
If Then _ [Else _]

If-Then
. Else .
.
If-Then Else.
. VBA
, Excel. , 0.5. VBA Time , . -

8. VBA

211

, .
0.5, , .
Sub GreetMe1()
If Time < 0.5 Then MsgBox " "
End Sub

, .
If-Then.
Sub GreetMe2()
If Time < 0.5 Then MsgBox " "
If Time >= 0.5 Then MsgBox " "
End Sub

, If-Then
>= ( ), ,
12.00.
Else If-Then.
Sub GreetMe3()
If Time < 0.5 Then MsgBox " " Else _
MsgBox " "
End Sub

, If-Then-Else
.
(,
, ), If-Then, If-Then-Else. .
Sub GreetMe4()
If Time < 0.5 Then MsgBox " "
If Time >= 0.5 And Time < 0.75 Then MsgBox " "
If Time >= 0.75 Then MsgBox " "
End Sub

0.75 18:00 ,
.
, .
, ,
. , , ,
, . ,
,
, .
.
If Then
[_]
[Elseif -n Then
[_]]
[Else
[__]]
End If

GreetMe.
Sub GreetMe5()
If Time < 0.5 Then
MsgBox " "
Elseif Time >=0.5 And Time < 0.75 Then

212

III. Visual Basic for Applications

MsgBox " "


Else
MsgBox " "
End If
End Sub

, , If-Then . ,
. , .
.
If-Then-Else ( ElseIf). , . , If End If.
Sub GreetMe6()
If Time < 0.5 Then
MsgBox " "
Else
If Time >=0.5 And Time < 0.75 Then
MsgBox " "
Else
If Time >=0.75 Then
MsgBox " "
End If
End If
End If
End Sub

, If-Then.
Quantity .
InputBox , Quantity , . ,
(, ).
Sub Discount1()
Quantity = InputBox(" : ")
If Quantity = "" Then Exit Sub
If Quantity >= 0 Then Discount = 0.1
If Quantity >= 25 Then Discount = 0.15
If Quantity >= 50 Then Discount = 0.2
If Quantity >= 75 Then Discount = 0.25
MsgBox ": " & Discount
End Sub

, If-Then
, Discount .
.
, .
_.
Sub Discount2()
Quantity = InputBox(" : ")
If Quantity = "" Then Exit Sub
If Quantity >= 0 And Quantity < 25 Then
Discount = 0.1
ElseIf Quantity < 50 Then

8. VBA

213

Discount = 0.15
ElseIf Quantity < 75 Then
Discount = 0.2
ElseIf Quantity >= 75 Then
Discount = 0.25
End If
MsgBox ": " & Discount
End Sub

If-Then .
. , Select Case.

Select Case
Select Case .
If-Then-Else. Select Case .
Select Case _
[Case -n
[-n]]
[Case Else
[__]]
End Select

VBA IIf
VBA If-Then IIf.
Excel. .
IIf(, _True, _False),
( ) , ;
_True ( ) ,
, True;
_False ( ) ,
, False.
IIf. , 1 , -, 1
.
MsgBox IIf (Range("A1") = 0, "", "-")
, (_False) ,
(_True) . , ,
n .
MsgBox IIf (n = 0, 0, 1/n)

Select Case, GreetMe, .

214

III. Visual Basic for Applications

Sub GreetMe()
Select Case Time
Case Is < 0.5
Msg = " "
Case 0.5 To 0.75
Msg = " "
Case Else
Msg = " "
End Select
MsgBox Msg
End Sub

Discount,
Select Case. , Quantity . ,
.
Sub Discount3()
Quantity = InputBox(" : ")
Select Case Quantity
Case ""
Exit Sub
Case 0 To 24
Discount = 0.1
Case 25 To 49
Discount = 0.15
Case 50 To 74
Discount = 0.2
Case Is >= 75
Discount = 0.25
End Select
MsgBox ": " & Discount
End Sub

Case Or. , ( ),
VBA WeekDay, . Or,
.
Sub GreetUser()
Select Case Weekday(Now)
Case 1 Or 7
MsgBox " ."
Case Else
MsgBox " ."
End Select
End Sub

Case ,
Case, True.
Case ( ), , Case (
VBA ).
.
Sub Discount3()
Quantity = InputBox(" : ")
Select Case Quantity
Case "": Exit Sub
Case 0 To 24: Discount = 0.1
Case 25 To 49: Discount = 0.15

8. VBA

215

Case 50 To 74: Discount = 0.2


Case Is >= 75: Discount = 0.25
End Select
MsgBox ": " & Discount
End Sub

VBA Select Case, Case,


True. ,
.

Select Case . ,
Excel (, , ), . Excel ,
.
Sub AppWindow()
Select Case Application.WindowState
Case xlMaximized: MsgBox " "
Case xlMinimized: MsgBox " "
Case xlNormal: MsgBox " "
Select Case ActiveWindow.WindowState
Case xlMaximized: MsgBox " "
Case xlMinimized: MsgBox " "
Case xlNormal: MsgBox " "
End Select
End Select
End Sub

Select Case , , Select Case End Select.


, ,
. , , .
Sub AppWindow()
Select Case Application.WindowState
Case xlMaximized: MsgBox " "
Case xlMinimized: MsgBox " "
Case xlNormal: MsgBox " "
Select Case ActiveWindow.WindowState
Case xlMaximized: MsgBox " "
Case xlMinimized: MsgBox " "
Case xlNormal: MsgBox " "
End Select
End Select
End Sub


. , ,
,
.
, ,
, .
(StartVal) ,
(NumToFill). GoTo. Cnt,
, , , , DoAnother.

216

III. Visual Basic for Applications

Sub BadLoop()
StartVal = 1
NumToFill = 100
ActiveCell.Value = StartVal
Cnt = 1
DoAnother:
ActiveCell.Offset(Cnt,0).Value = StartVal + Cnt
Cnt = Cnt + 1
If Cnt < NumToFill Then GoTo DoAnother Else Exit Sub
End Sub

.
? GoTo,
. GoTo
. ,
. ,
. (
) .
VBA ,
GoTo.


, . , , , .

VBA?
,
. ,
, . ,
GoTo. ,
, , .
, . , .
VBA . ,
, If-Then-Else Select Case, For-Next, Do Until Do While.
, VBA .
,
.

FOR6NEXT
For-Next ( ). .
For = To [Step ]
[]
[Exit For]
[]
Next []

8. VBA

217

For-Next,
Exit For.
Sum = Sum + Sqr(Count) 100 100 .
Sub SumSquareRoots()
Dim Sum As Double, Count As Integer
Sum = 0
For Count = 1 To 100
Sum = Sum + Sqr(Count)
Next Count
MsgBox Sum
End Sub

Count (- ) 1
1 . Sum
Count.

For-Next, ,
, . , For Next.
,
. ,
, .

, . , , 1 100.
Sub SumOddSquareRoots()
Sum = 0
For Count = 1 To 100 Step 2
Sum = Sum + Sqr(Count)
Next Count
MsgBox Sum
End Sub

Count 1, 3, 5, 7 .. Count, , 99.


, Count 101.
, BadLoop, .
GoTo, .
For-Next.
Sub GoodLoop()
StartVal = 1
NumToFill = 100
ActiveCell.Value = StartVal
For Cnt = 0 To NumToFill - 1
ActiveCell.Offset(Cnt,0).Value = StartVal + Cnt
Next Cnt
End Sub

For-Next Exit For.


, ,
. , .

218

III. Visual Basic for Applications

Sub ExitForDemo()
MaxVal = Application.WorksheetFunction.Max(Range("A:A"))
For Row = 1 To 65536
Set TheCell = Range("A1").Offset(Row 1, 0)
If TheCell.Value = MaxVal Then
MsgBox " " & Row
TheCell.Activate
Exit For
End If
Next Row
End Sub

Excel MAX.
MaxVal. For-Next
. MaxVal, Exit
For .
.
ExitForDemo
For-Next.
. .
Range("A:A").Find(Application.WorksheetFunction.Max _
(Range("A:A"))).Activate

.
For-Next
For-Next. ,
For-Next 101010 -1. 1000 MyArray -1.
Sub NestedLoops()
Dim MyArray(1 To 10, 1 To 10, 1 To 10)
Dim i As Integer, j As Integer, k As Integer
For i = 1 To 10
For j = 1 To 10
For k = 1 To 10
MyArray(i, j, k) = -1
Next k
Next j
Next i
End Sub

DO WHILE
Do While ,
VBA. For-Next, Do While ,
. Do While .
Do [While ]
[]
[Exit Do]
[]
Loop

Do
[]
[Exit Do]
[]
Loop [While ]

8. VBA

219

, VBA While .
,
. .
( ).
Do While .
Sub DoWhileDemo()
Do While Not IsEmpty(ActiveCell)
ActiveCell.Value = 0
ActiveCell.OffSet(1, 0).Select
Loop
End Sub


, .
. ,
VBA IsEmpty , .
Do While.
, .
Sub DoWhileDemo2()
Do
ActiveCell.Value = 0
ActiveCell.OffSet(1, 0).Select
Loop While Not IsEmpty(ActiveCell)
End Sub

Do While. , , , , 1,
. VBA EOF,
True, . .

Sub DoWhileDemo1()
Open "c:\data\textfile.txt" For Input As #1
LineCt = 0
Do While Not EOF(1)
Line Input #1, LineOfText
Range("A1").Offset(LineCt, 0) = UCase(LineOfText)
LineCt = LineCt + 1
Loop
Close #1
End Sub

VBA 27.

DO UNTIL
Do Until Do While. , . Do While
, . Do Until
, .
Do Until .
Do [Until ]
[]
[Exit Do]
[]
Loop

220

III. Visual Basic for Applications


Do
[]
[Exit Do]
[]
Loop [Until ]

, , Do While,
Do Until.
Do. , , Do While.
Sub DoUntilDemo1()
Open "c:\data\textfile.txt" For Input As #1
LineCt = 0
Do Until EOF(1)
Line Input #1, LineOfText
Range("A1").Offset(LineCt, 0) = UCase(LineOfText)
LineCt = LineCt + 1
Loop
Close #1
End Sub

8. VBA

221


VBA

VBA,
. VBA . , , .
VBA



11 ,
.


VBA,
VBA, VBE.
.
, , . ( ).

,
, . ,
,
, ,
. .

. , . , Excel.
,
.


Sub
.
[Private | Public][Static] Sub ([_])
[]
[Exit Sub]
[]
End Sub

Private ( ) ,
.
Public ( ) , .
, Option Private Module, .
Static ( ) ,
.
Sub ( ) .
.
_ , , .
. ,
.
() VBA.
Exit Sub ( ) .
End Sub ( ) .

, VBA
. ,
,
(, Option Explicit).


. , ,
, . , , . ,
(, ProcessDate ,
PrintReport , Sort_Array CheckFilename
). (Dolt, Update, Fix ..).
, , (, WriteReportToTextFile , Get_Print_Options_and_Print_Report
).
, .

224

III. Visual Basic for Applications


,
, .
, .

PUBLIC
Public, ..
.
Public , . Public.
Sub First()
' ...[ ]..
End Sub
Public Sub Second()
' ...[ ]..
End Sub

PRIVATE
Private
, .

Excel
Public-. , ,
,
, Private
.

Private MySub.
Private Sub MySub()
' ...[ ]
End Sub

Private
, Public.
Sub.
Option Private Module
,
Private .

Excel
1, 2 .. Public
.


, , VBA.
RunRun Sub/UserForm ( VBE).
<F5>. Excel , .
, .

9. VBA

225

Excel ( ,
).
<Alt+F8>.
<Ctrl>
( ).
.
.
.
.
.
.
, , ,
, .
Immediate Visual Basic. ,
<Enter>.

.

, . , , , . ,
,
.


RunRun Sub/UserForm
RunRun Sub/UserForm VBE
. Visual Basic, .
RunRun Sub/UserForm ( <F5>) VBE, ( , , ).
RunRun Sub/UserForm , VBE ,
.


Excel
. 9.1 ( ,
<Alt+F8>). . ,
(, ).
. , Private, , , .

226

III. Visual Basic for Applications

, ,
, , .
.

. 9.1.


, ,
<Ctrl+ >. ,
Update <Ctrl+U>, <Ctrl+U> .

, . .
( ), .
1. Excel .
2. .
3. ,
, . 9.2.
4. Ctrl+.
5. , Ctrl+, .
s ,
<Ctrl+S>. S , <Ctrl+Shift+S>.

. 9.2.

( )

6. ( ). , .
7. , ,
, .

9. VBA

227


Excel, . , <Ctrl+S> Excel
. ,
<Ctrl+S> .
Excel <Ctrl+>: E, J, L, M, Q T.
Excel <Ctrl+Shift+>,
, F, O P.


23, Excel :
VBA. , .
,
. ,
:
; OpenCustomerFile.
1. . Excel
.
2. . ,
.
3. .
4. .
5.
.
. .
6. (
), .
7. : &
, . 9.3.
8. .
9. OpenCustomerFile
.
10. , ,
, .

, , , .
, ,
, .
, , .
23 VBA , , .

228

III. Visual Basic for Applications

. 9.3.



. .
(
) .
Call,
( ), .
Run Application.
VBA XLM. Run ,
, .
Run .
. MySub
( ),
UpdateSheet .
Sub MySub()
' ...[]...
UpdateSheet
' ...[]...
End Sub

9. VBA

229

Sub UpdateSheet()
' ...[]...
End Sub

. Call
Update, ; . .
Sub MySub()
MonthNum = InputBox(" : ")
Call UpdateSheet(MonthNum)
' ...[]...
End Sub
Sub UpdateSheet(MonthSeq)
' ...[]...
End Sub

Call,
( ).

Run,
UpdateSheet MonthNum .

Sub MySub()
MonthNum = InputBox(" : ")
Result = Application.Run("UpdateSheet", MonthNum)
' ...[]...
End Sub
Sub UpdateSheet(MonthSeq)
' ...[]...
End Sub

, Run .
(. ). Main VBA
WeekDay ( 1 7, ).
SubToCall , .
Run (Weekend Daily).
Sub Main()
Select Case Weekday(Now)
Case 1: SubToCall = "Weekend"
Case 7: SubToCall = "Weekend"
Case Else: SubToCall = "Daily"
End Select
Application.Run SubToCall
End Sub
Sub Weekend()
MsgBox " "
' ,
End Sub
Sub Daily()
MsgBox " "
' ,
End Sub

230

III. Visual Basic for Applications


VBA ,
Public .
Private
.
, , . VBA , .. , . . ,
MySub : Module1 Module2. ,
MySub Module2 MySub Module1,
.
Module1.MySub
Call Module1.MySub

,
: Ambiguous Name Detected (
).


, ,
. :
Run
.
, VBE
ToolsReferences. References,
. 9.4,
. , , , . , , .

. 9.4. References

9. VBA

231

, ,
. Browse
References, .
, , VBE. VBAProject. , . , Properties VBE. ,
References,
ActiveX, . Excel 2003
:
Visual Basic for Applications;
Microsoft Excel 10.0 Object Library;
OLE Automation;
Microsoft Office 10.0 Object Library;
Microsoft Forms 2.0 Object Library (; ,
UserForm).

Excel 2003 , ,
Project Explorer VBE. References.

, , YourSub,
YourSub.
YourSub
Call YourSub

,
, , .
MyProject.MyModule.MySub

Call.
Call MyProject.MyModule.MySub

Run Application.
. , Consolidate,
budget macros.xls.
Application.Run "'budget macros.xls'!Consolidate"


, , . : ?
-, . , . .

232

III. Visual Basic for Applications

, . .
Sub Main()
Call GetUserOptions
Call ProcessData
Call CleanUp
Call CloseItDown
End Sub
. , . , , , .
, . , , ,
.

. ,
, .



Excel, , . .
, . .
1. , .
2. Excel
. ,
.
3. .
4. .
5.
.
6. , .
7. . ,
, .
; ,
.
8. , , . Excel
.

9. VBA

233

9. .
10. , .
11. , .


, , , .
, ,
, .
, , .
22.


Excel , . .
.
.
.
.
, ,
.
.


ActiveX, UserForm. , , ( ActiveX).
Excel 5
Excel 95. ( ).
.
ActiveX 13.

Button (), , .
1. , .
2. .
3. .

<Alt>,
. <Shift>,
.

Excel . ,
, .
, .
.

234

III. Visual Basic for Applications


, () . ,
, , CommandButton
. , , -
, . .
, , . , ,
, Workbook_Open.

.
19.


, (Immediate)
VBE. , <Ctrl+G>.
Immediate VBA, .
, Immediate <Enter>.
, Immediate ,
. .
Sub ChangeCase()
MyString = " "
MyString = UCase(MyString)
Debug.Print MyString
End Sub

. 9.5 ChangeCase Immediate.


Debug.Print .


, .
:
;
;
;
.

9. VBA

235

. 9.5. Immediate

, Excel :
;
;
;
;
.
, Excel,
(, ). (, ) .
(, ) ( 30). Excel . ,
( ).
, , : Sub,
. , .
, , . Main ProcessFile ( Call For-Next).
ProcessFile .
.

236

III. Visual Basic for Applications

ProcessFile ( TheFile). ,
Sub. ProcessFile
, Call.
Sub Main
File(1) = "dept1.xls"
File(2) = "dept2.xls"
File(3) = "dept3.xls"
For i = 1 To 3
Call ProcessFile(File(i))
Next i
End Sub
Sub ProcessFile(TheFile)
Workbooks.Open FileName:=TheFile
' ...[]...
End Sub

, ( ).
Sub Main
Call ProcessFile("budget.xls")
End Sub

: .
( )
.
. , .
.
Process ( ). , Main MyValue 10, Process
MyValue . Process
( YourValue) 10. Process
Main, MsgBox MyValue: 100.
Sub Main
MyValue = 10
Call Process(MyValue)
MsgBox MyValue
End Sub
Sub Process(YourValue)
YourValue = YourValue * 10
End Sub

, , , ,
, .
ByVal.
, . , , , YourValue Process,
MyValue Main. MsgBox
10, 100.
Sub Process(ByVal YourValue)
YourValue = YourValue * 10
End Sub

9. VBA

237

, ,
. ,
,
, .
,
. , ByVal, ; .

,
.
.

, Variant. ,
, .
Sub , . Integer, String.
Sub Process(Iterations As Integer, TheFile As String)

, ,
, . , Process
String : ByRef argument type mismatch.

, .
. 10, , , .

Public
8 , , Public ( ),
.
Public, .
, MonthVal ProcessMonth.
Sub MySub()
Dim MonthVal as Integer
' ...[]
MonthVal = 4
Call ProcessMonth(MonthVal)
' ...[]
End Sub
:
Public MonthVal as Integer
Sub MySub()
' ...[]
MonthVal = 4
Call ProcessMonth
' ...[]
End Sub

238

III. Visual Basic for Applications

, MonthVal Public, ProcessMonth , .


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

,
Break on All Errors. VBE ToolsOptions,
General Options. Break on All Errors , VBA . Break on Unhandled Errors.

, VBA,
,
.
, , .

, VBA.
VBA .


, ,
On Error. .
VBA .
Err, ,
, .
,
.
.
, .
On Error Resume Next

, .
, .
Err . Err.Number ( Err), Error.
, ,
Visual Basic (
).
MsgBox "" & Err & ": " & Error(Err)

9. VBA

239

. 9.6 VBA, . 9.7


, , Excel. , , .

. 9.6. , VBA,

. 9.7.

Err Number Err. , .


MsgBox Err
MsgBox Err.Number

On Error , . ,
.
On Error GoTo ErrorHandler


, . SpecialCells , . (,
, , , , .)
SpecialCells , , .
, VBA . On Error Resume Next
.
Sub SelectFormulas()
On Error Resume Next
Selection.SpecialCells(xlFormulas, xlNumbers).Select
On Error GoTo 0
' ...[]
End Sub

, On Error GoTo 0
.

240

III. Visual Basic for Applications


: .
Sub SelectFormulas2()
On Error Resume Next
Selection.SpecialCells(xlFormulas, xlNumbers).Select
If Err <> 0 Then MsgBox " ."
On Error GoTo 0
' ...[]
End Sub

Err , ,
.
.
Sub ErrorDemo()
On Error GoTo Handler
Selection.Value = 123
Exit Sub
Handler:
MsgBox " ."
End Sub


. (,
), . On Error Handler . , Exit Sub. ,
. , .
.
, .
.
Sub CheckForFile()
FileName = "BUDGET.XLS"
FileExists = False
'
For Each book In Workbooks
If UCase(book.Name) = FileName Then
FileExists = True
End If
Next book
'
If FileExists Then _
MsgBox FileName & " ." Else _
MsgBox FileName & " ."
End Sub

For Each-Next Workbooks. , FileExists


True. , ,
.
,
.
On Error Resume Next VBA .
, ( -

9. VBA

241

Set). , .
If-Then-Else Err
.

Sub CheckForFile()
Dim x as Workbook
FileName = "BUDGET.XLS"
On Error Resume Next
Set x = Workbooks(FileName)
If Err = 0 Then
MsgBox FileNAme & " ."
Else
MsgBox FileNAme & " ."
End If
On Error GoTo 0
End Sub

11 ,
.

. ,
. . ,
.
,
( , 5). ,
VBA. , : ,
. , , .

-.

, , (
Excel ).
, ,
. , .


? .
.
.
1. (.. )
.

242

III. Visual Basic for Applications

2. .
3. . ,
.
4.
.
5. VBA.


, .
Excel,
.
Excel . , .
, .
:
, , .
, . VBA.
( VBA).
Excel , .
: ,
. , , VBA ,
.

.
, .
. ,
, .
: ,
.
, VBA
.
:

, ,
, , .
1. .
2. .
3. .
4. ( ).
5. .

9. VBA

243


. , .
.
.
.
.
.

, . , . ,
, .


, ,
VBA. , . , . .
Excel .
Sub Macro1()
Sheets("3").Select
Sheets("3").Move Before:=Sheets(1)
End Sub

Move: , . , . , .
. Count , . Immediate VBE .
? ActiveWorkbook.Count

! , .
? ActiveWorkbook.Sheets.Count

. . 9.8
.

. 9.8. Immediate
VBE

244

III. Visual Basic for Applications

? . Immediate
.
? ActiveWorkbook.Sheets(1).Name

3 (
). , .
, For Each-Next
. ,
.
Sub Test()
For Each Sht In ActiveWorkbook.Sheets
MsgBox Sht.Name
Next Sht
End Sub

! ,
.
, .
, Sort Range. . .
, ,
VBA.

, . . , .
1. : 1,
2, 3, 4 5.
2. , .
3. Test.xls.
4. VBE Personal.xls Project.
5. Personal.xls Project, ,
. Excel ,
() , .
6. VBA ( InsertModule).
7. SortSheets (. 9.9).
8. .
. ,
.
9. Excel.
, .
<Ctrl+Shift+S>.

9. VBA

245

. 9.9. ,


.
. ,
, Dim
. , ReDim .
, SheetNames. ,
MsgBox, ,
.
Sub SortSheets()
Dim SheetNames() as String
Dim i as Integer
Dim SheetCount as Integer
SheetCount = ActiveWorkbook.Sheets.Count
ReDim SheetNames(1 To SheetCount)
For i = 1 To SheetCount
SheetNames(i) = ActiveWorkbook.Sheets(i).Name
MsgBox SheetNames(i)
Next i
End Sub

, Test.xls
<Ctrl+Shift+S>. .
. ,
, MsgBox (
).

246

III. Visual Basic for Applications

MsgBox, Print Debug, Immediate.


MsgBox
.
Debug.Print SheetNames(i)
, MsgBox.

SortSheets .
: SheetNames, .

SheetNames. SortSheets, ,

( ).
, .
: ,
.
, Internet.
.
( , ).
.
For-Next, . , ,
.
(.. n 1 ).

11 .

.
Sub BubbleSort(List() As String)
'
List
Dim First As Integer, Last As Integer
Dim i As Integer, j As Integer
Dim Temp As String
First = LBound(List)
Last = UBound(List)
For i = First To Last - 1
For j = i + 1 To Last
If List(i) > List(j) Then
Temp = List(j)
List(j) = List(i)
List(i) = Temp
End If
Next j
Next i
End Sub

9. VBA

247

: List.
, , .
First Last
LBound UBound, .
, , , SortSheets. BubbleSort,
SheetNames. .
Sub SortSheets()
Dim SheetNames() As String
Dim SheetCount as Integer
Dim i as Integer
SheetCount = ActiveWorkbook.Sheets.Count
ReDim SheetNames(1 To SheetCount)
For i = 1 To SheetCount
SheetNames(i) = ActiveWorkbook.Sheets(i).Name
Next i
Call BubbleSort(SheetNames)
End Sub
Sub BubbleSort(List() As String)
Dim First As Integer, Last As Integer
Dim i As Integer, j As Integer
Dim Temp As String
First = LBound(List)
Last = UBound(List)
For i = First To Last - 1
For j = i + 1 To Last
If List(i) > List(j) Then
Temp = List(j)
List(j) = List(i)
List(i) = Temp
End If
Next j
Next i
End Sub

SortSheets , . ,
Intermediate,
SortSheets .
For i = 1 To SheetCount
Debug.Print SheetNames(i)
Next i

.

SheetNames.
, , . , ?
Sheets("3").Move Before:=Sheets(1)

For-Next, , SheetNames.
For i = 1 To SheetCount
Sheets(SheetNames(i)).Move Before:=Sheets(i)
Next i

248

III. Visual Basic for Applications

, (i) 1.
SheetNames ( ) 1. , Move .
Sheets("1").Move Sheets(1)

.
Sheets("2").Move Sheets(2)

SortSheets .
Sub SortSheets()
SheetCount = ActiveWorkbook.Sheets.Count
ReDim SheetNames(1 To SheetCount)
For i = 1 To SheetCount
SheetNames(i) = ActiveWorkbook.Sheets(i).Name
Next i
Call BubbleSort(SheetNames)
For i = 1 To SheetCount
ActiveWorkbook.Sheets(SheetNames(i)).Move _
Before:=ActiveWorkbook.Sheets(i)
Next i
End Sub

, Test.xls.
. ,
, , , . SortSheets .
Sub SortSheets()
'
' .
Dim SheetNames() as String
Dim i as Integer
Dim SheetCount as Integer
'

,
SheetCount = ActiveWorkbook.Sheets.Count
ReDim SheetNames(1 To SheetCount)

'


For i = 1 To SheetCount
SheetNames(i) = ActiveWorkbook.Sheets(i).Name
Next I

'


Call BubbleSort(SheetNames)


For i = 1 To SheetCount
ActiveWorkbook.Sheets(SheetNames(i)).Move _
ActiveWorkbook.Sheets(i)
Next i
End Sub
'

, . ,
Test.xls . !

9. VBA

249


, , . ,
Test.xls, ,
. ,
. , ( , ).
.
,
.
. , SUMMARY ( )
Sheet1. BubbleSort (
U , h ).
, <Ctrl+Shift+S>
.
, Move .
Move . .
, ,
Excel.
.
; ,
,
.
<Ctrl+Break> VBA
.



SortSheets .
Application.ScreenUpdating = False

BubbleSort.
UCase, .
.
.

If UCase(List(i)) > UCase(List(j)) Then

.
Option Compare Text
VBA . , , .

250

III. Visual Basic for Applications

, ,
, .
, . On Error Resume Next, , Err. Err
, , . , .
.
On Error Resume Next
SheetCount = ActiveWorkbook.Sheets.Count
If Err <> 0 Then Exit Sub '

On Error Resume Next.


, ,
.
If ActiveWorkBook Is Nothing Then Exit Sub

.
; ,
. ProtectStructure WorkBook True, . .
'
If ActiveWorkbook.ProtectStructure Then
MsgBox ActiveWorkbook.Name & " .", _
vbCritical, " ."
Exit Sub
End If

. :
, (
Visible). .
(SheetHidden)
.

For i = 1 To SheetCount
SheetHidden(i) = Not ActiveWorkbook.Sheets(i).Visible
'
If SheetHidden(i) Then ActiveWorkbook.Sheets(i).Visible = True
Next i
'

, , ,
, .
'


For i = 1 To SheetCount
If SheetHidden(i) Then ActiveWorkbook.Sheets(i).Visible = False
Next i

,
.
, ,
(OldActive), .
<Ctrl+Break> ,
VBA .
,

9. VBA

251

. , Application EnableCancelKey, <Ctrl+Break>.


.
Application.EnableCancelKey = xlDisabled

, . , .
, , .

SortSheets
, 9.1.
9.1. SortSheets
Sub SortSheets()
'

Dim
Dim
Dim
Dim
Dim
Dim
Dim

SheetNames() As String
SheetHidden() As Boolean
i As Integer
SheetCount As Integer
VisibleWins As Integer
Item As Object
OldActive As Object

If ActiveWorkbook Is Nothing Then Exit Sub '


SheetCount = ActiveWorkbook.Sheets.Count
'


If ActiveWorkbook.ProtectStructure Then
MsgBox ActiveWorkbook.Name & " . ", _
vbCritical, " . "
Exit Sub
End If

'

Ctrl+Break
Application.EnableCancelKey = xlDisabled

'


SheetCount = ActiveWorkbook.Sheets.Count

'


ReDim SheetNames(1 To SheetCount)
ReDim SheetHidden(1 To SheetCount)

'


Set OldActive = ActiveSheet

'


For i = 1 To SheetCount
SheetNames(i) = ActiveWorkbook.Sheets(i).Name
Next i

'

For i = 1 To SheetCount
SheetHidden(i) = Not ActiveWorkbook.Sheets(i).Visible
unhide hidden sheets
If SheetHidden(i) Then ActiveWorkbook.Sheets(i).Visible = True
Next i

'


Call BubbleSort(SheetNames)

252

III. Visual Basic for Applications

'


Application.ScreenUpdating = False

'


For i = 1 To SheetCount
ActiveWorkbook.Sheets(SheetNames(i)).Move _
Before:=ActiveWorkbook.Sheets(i)
Next i

'


For i = 1 To SheetCount
If SheetHidden(i) Then ActiveWorkbook.Sheets(i).Visible = False
Next i


OldActive.Activate
End Sub
'


SortSheets ,
Excel. ( <Alt+F8>)
<Ctrl+Shift+S>.

. , .


, . :
, ,
, ( )
VBA.

: . ,
11 2,
2 11.
-, , ,
.

9. VBA

253

10



VBA : Sub
Function. Sub .
.



, , ...
, Excel
, ,

Windows API

11 .
.

:
,
. , Function ( ), Excel
VBA. , Function
.
Function .
VBA.
, .
Function ,
Excel VBA.


, Excel. ,
,
. Excel 300 , , . , VBA.

, Excel VBA,
.
.
VBA.
, , . .
, , , , .
,
. , , . , ,
.
. , , ,
.
, . , . ,
Excel. ,
.
;
.


, VBA.


, VBA. Reverse . .
Function Reverse(InString) As String
'
Dim i as Integer, StringLength as Integer
Reverse = ""
StringLength = Len(InString)
For i = StringLength To 1 Step 1
Reverse = Reverse & Mid(InString, i, 1)
Next i
End Function

, , , VBA. ,
.


, Reverse, Excel
.
.
=Reverse(A1)

256

III. Visual Basic for Applications

. 10.1.
, .
.

. 10.1.

,
. ,
.
.

. , (
) Reverse . .
=Reverse(Reverse(A1))

VBA
VBA, ,
Reverse, .
VBA MsgBox ,
, Reverse (. 10.2).
.
Sub ReverseIt()
Dim UserInput as String
UserInput = InputBox(" :")
MsgBox Reverse(UserInput), , UserInput
End Sub

, . 10.2, InputBox
VBA Excel. MsgBox
-.

. 10.2.
VBA

10.

257


, . ,
, .
, .
.
Function Reverse(InString) As String
'
Dim i as Integer, StringLength as Integer
Reverse = ""
StringLength = Len(InString)
For i = StringLength To 1 Step 1
Reverse = Reverse & Mid(InString, i, 1)
Next i
End Function

, Function,
Sub, (Reverse).
(InString), .
As String , . (Excel
Variant, .)
(), . Dim
(i StringLength), .
. ,
. , , .
VBA Len StringLength.
For-Next.
. , Step For-Next
, . VBA Mid, , . Reverse
, . , .
End Function.

,

,
VBA, , . , , . ,
.
, .
, . , , . , ,
. ,
. : , .

258

III. Visual Basic for Applications


Sub.
( Sub 9.)


.
[Public | Private][Static] Function ([_])[As ]
[]
[ = ]
[Exit Function]
[]
[ = ]
End Function

.
Public ( ) ,
VBA.
Private ( ) ,
.
Static ( ) , ,
, .
Function ( ) ,
.
( )
. ,
.
.
_ () ,
, .
. .
() , .
() VBA.
Exit Function () ,
.
End Function () , .
, VBA, :
, ,
, .
VBA ( ). Function,
( ) . , ,
As ( , ). VBA,
, , -

10.

259

,
. End Function.
, .
, ,
(,
J21). , , Excel. Excel .


9 (Public
Private). : ,
.
,
.
,
Public.
, Private,
. , ,
VBA, Private,
.
VBA ,
, , VBE ToolsReferences.


, .
.
.


,
. ,
SumArray , .
Total = SumArray(MyArray)

SumArray MyArray,
Total.
, Run Application.
Total = Application.Run ("SumArray", "MyArray")

Run . () . Run
( ), .

260

III. Visual Basic for Applications



, . ,
Excel .
, .
, Excel, .
.
. ,
CountNames,
Myfunc.xls, .
=Myfunc.xls!CountNames(A1:A1000)

,
.
.
VBE ToolsReferences. ,
.
,
, ( ).
. ,
, , . . 21.


Excel VBA .
.
Excel ( ) UpCase. ( , . . .)
Function UpCase(InString As String) As String
'
Dim StringLength As Integer
Dim i As Integer
Dim ASCIIVal As Integer
Dim CharVal As Integer
StringLength = Len(InString)
UpCase = InString
For i = 1 To StringLength
ASCIIVal = Asc(Mid(InString, i, 1))
CharVal = 0
If ASCIIVal >= 97 And ASCIIVal <= 122 Then
CharVal = 32
Mid(UpCase, i, 1) = Chr(ASCIIVal + CharVal)
End If
Next i
End Function

10.

261

, , , , 10000
26 . 13 .
Excel . , .
UpCase , ,
, VBA.

, , ,
. , VBE RunSub/UserForm ( <F5>), (
, ).
. ,
.
, .


.
( ), , .
.

( 1 60).
, .


#!, .
, (, ).
. .

,
. .


-.


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

262

III. Visual Basic for Applications

, . UserName Application. Excel


Windows.
Function User()
'
User = Application.UserName
End Function


(, ).
=User()

. ,
VBA. ,
.

,
, .
User
MsgBox , . (&)
User.
Sub ShowUser()
MsgBox " " & User()
End Sub


Excel () .
.
.
, ,
. VBA Rnd(), 0 1.
.
Function StaticRand()
' ,
'
StaticRand = Rnd()
End Function

0 1000,
=(StaticRand()*1000)

, , , ().

10.

263


, , , .
Excel. , ..
. . , .
Application.Volatile True
Volatile Application (True False). Volatile (.. ), , .
, NonStaticRand Volatile , Excel ().
Function NonStaticRand()
' ,
'
Application.Volatile True
NonStaticRand = Rnd()
End Function
False Volatile
, (
, ).
, , <Ctrl+Alt+F9>. , ,
StaticRand, .


,
.
.

0$9999

8,0%

$10000$19999

10,5%

$20000$39999

12,0%

$40000

14,0%

,
. , ,
.

, Excel. ,
, .
=((A1>=0;A1<=9999,99);A1*0,08;
((A1>=10000;A1<=19999,99);A1*0,105;
((A1>=20000;A1<=39999,99);A1*0,12;
F(A1>=40000;A1*0,14;0))))

264

III. Visual Basic for Applications

. -,
, . -, ,
- .
( VBA):
.
=(A1;;2)*A1

( ) , .
Function Commission(Sales)
Const Tier1 = 0.08
Const Tier2 = 0.105
Const Tier3 = 0.12
Const Tier4 = 0.14
'
Select Case Sales
Case 0 To 9999.99: Commission = Sales * Tier1
Case 10000 To 19999.99: Commission = Sales * Tier2
Case 20000 To 39999.99: Commission = Sales * Tier3
Case Is >= 40000: Commission = Sales * Tier4
End Select
End Function

VBA
VBA.
3000 ( 25000 12%).
=Commission(25000)

,
VBA. , VBA ,
VBA. ,
Commission
.
Sub CalcComm()
Dim Sales as Long
Sales = InputBox(" :")
MsgBox " " & Commission(Sales)
End Sub

CalcComm
.
.
, .
, ,
(. 10.3).

. 10.3.

10.

265

Sub CalcComm()
Dim Sales as Long
Dim Msg As String, Ans As String
'
Sales = Val(InputBox(" :", _
" "))
'
Msg = " : " & vbTab & Format (Sales, "$#,##0.00")
Msg = Msg & vbCrLf & ":" & vbTab
Msg = Msg & Format(Commission(Sales), "$#,##0.00")
Msg = Msg & vbCrLf & vbCrLf & " ?"
'
Ans = MsgBox(Msg, vbYesNo, " ")
If Ans = vbYes Then CalcComm
End Sub

VBA: vbTab ( ), vbCrLf (


). VBA Format
( , ).
Commission
; Excel , , .


, , , , : ,
, 1% , .
Commission ( )
, . ,
. Commission2.
Function Commission2(Sales, Years)
'
'
Const Tier1 = 0.08
Const Tier2 = 0.105
Const Tier3 = 0.12
Const Tier4 = 0.14
Select Case Sales
Case 0 To 9999.99: Commission2 = Sales * Tier1
Case 10000 To 19999.99: Commission2 = Sales * Tier2
Case 20000 To 39999.99: Commission2 = Sales * Tier3
Case Is >= 40000: Commission2 = Sales * Tier4
End Select
Commission2 = Commission2 + (Commission2 * Years / 100)
End Function

, ? (Years) Function
, .

(, 1, ,
, 1).
=Commission2(A1;B1)

266

III. Visual Basic for Applications


, () .
, ,
.
Function SumArray(List) As Double
Dim Item As Variant
SumArray = 0
For Each Item In List
If WorksheetFunction.IsNumber(Item) Then _
SumArray = SumArray + Item
Next Item
End Function

Excel IsNumber , ,
.
.
, .
MakeList 100- . MsgBox
SumArray.
Sub MakeList()
Dim Nums(1 To 100) As Double
Dim i as Integer
For i = 1 To 100
Nums(i) = Rnd * 1000
Next i
MsgBox SumArray(Nums)
End Sub

SumArray (
Variant), . ,
1:10.
=SumArray(A1:C10)

, , SumArray Excel . , SumArray


( 30- ).
, . SumArray
Excel .


Excel .
, . .
([;_])

, . , Excel 1. , ,
.
(A1;1)
(A1)

10.

267

, VBA, . ,
Optional.
.
.
Function User(Optional UpperCase As Variant)
If IsMissing(UpperCase) Then UpperCase = False
If UpperCase =True Then
User = Ucase(Application.UserName)
Else
User = Application.UserName
End If
End Function

False ,
- . True, ( VBA- Ucase).
VBA- IsMissing,
.
,
.
=User()
=User(False)
=User(True)

,
, Variant. IsMissing, .


.
.
True, .
False ( ), ,
, .
Function Draw(Rng As Variant, Optional Recalc As Boolean = False)
'
' , Recalc True
Application.Volatile Recalc
'
Draw = Rng(Int((Rng.Count) * Rnd + 1))
End Function

, Draw
Optional, .
,
.
=Draw(A1:A100)
=Draw(A1:A100;False)
=Draw(A1:A100;True)

,
..

268

III. Visual Basic for Applications

VBA,
VBA Array. Variant, (.. ).
Excel, Array VBA. <Ctrl+Shift+Enter>.
Excel , , .
3.

, , Array, , Variant.
, Variant , Variant.

MonthNames, , Array .
Function MonthNames()
MonthNames = Array("", "", "", "", _
"", "", "", "", "", "", _
"", "")
End Function

MonthNames .
,
MonthNames. , , VBA
. ( 12 ), <Ctrl+Shift+Enter>.
=MonthNames()

,
, <Ctrl+Shift+Enter>.
=(MonthNames())

Excel .
MonthNames.
Function MonthNames(Optional MIndex)
Dim AllNames As Variant
AllNames = Array("", "", "", "", _
"", "", "", "", "", "", _
"", "")
If IsMissing(MIndex) Then
MonthNames = AllNames
Else
Select Case MIndex
Case Is >= 1
'
(, 13=1)
MonthVal = ((MIndex 1) Mod 12)
MonthNames = AllNames(MonthVal)
Case Is <= 0 '
MonthNames = Application.Transpose(AllNames)
End Select
End If
End Function

10.

269

, VBA IsMissing.
, . IsMissing ,
Variant.
,
.
,
.
0,
. Excel
(Transpose).
1, ,
.

Mod . Mod
. , 13 0, 24 11 ..

,
. 10.4.
A1:L1 , .
A1:L1, <Ctrl+Shift+Enter>.
=MonthNames()

3:14 1 12. 3 , 11 , .
=MonthNames(A3)

D3:D14 , .
=MonthNames(-1)

, <Ctrl+Shift+Enter>.

, Array,
, Option Base . Option Base , 0.

. 10.4.

270

III. Visual Basic for Applications

,
,
. Reverse,
.
Function Reverse(InString) As String
'
Dim i as Integer, StringLength as Integer
Reverse = ""
StringLength = Len(InString)
For i = StringLength To 1 Step 1
Reverse = Reverse & Mid(InString, i, 1)
Next i
End Function

( ) . , , . , ,
(#/).
, ,
Excel.
Reverse = "#/"

, ,
, .
, CVErr, .
, VBA ,
.
Excel, VBA. .
xlErrDiv0 ( #/0!).
xlErrNA ( #/).
xlErrName ( #?).
xlErrNull ( #!).
xlErrNum ( #!).
xlErrRef ( #!).
xlErrValue ( #!).
#/ ,
.
Reverse = CVErr(xlErrNA)

Reverse. Excel
(IsText) , . , .
( ), #/.

10.

271

Function Reverse(InString) as Variant


' ,
' #N/A
Dim i as Integer, StringLength as Integer
If Application.WorksheetFunction.IsText(InString) Then
Reverse = ""
StringLength = Len(InString)
For i = StringLength To 1 Step 1
Reverse = Reverse & Mid(InString, i, 1)
Next i
Else
Reverse = CVErr(xlErrNA)
End If
End Function

, ,
. - ,
, Variant.


Excel . , .
(1;2;..)

, 29- . -.
(A1:A5;C1:C5;E1:E5;G1:G5)

. ,
: , , .
=(A1:A5;12;24*3)

,
. : ( ) ParamArray.

ParamArray . Variant
( Optional ).

,
( -).
.
Function SimpleSum(ParamArray arglist() As Variant) As Double
For Each arg In arglist
SimpleSum = SimpleSum + arg
Next arg
End Function

SimpleSum , Excel . , , , , , .

272

III. Visual Basic for Applications

Excel
MySum.
SimpleSum, ,
MySum Excel .
MySum Excel .
. 30- ( ), , , , ,
. .
=(B1;5;"6";;;(4);A1:A5)

, :
;
;
, ;
;
;
, ;
.

MySum ( 10.1) .

, MySum,
-.

10.1. MySum
Function MySum(ParamArray args() As Variant) As Variant
' Excel
'
Dim i As Variant
Dim TempRange As Range, cell As Range
Dim ECode As String
MySum = 0
'
For i = 0 To UBound(args)
'

If Not IsMissing(args(i)) Then
'

Select Case TypeName(args(i))
Case "Range"
'
/
Set TempRange = Intersect(args(i).Parent.UsedRange, args(i))
For Each cell In TempRange
If IsError(cell) Then
MySum = cell ' return the error
Exit Function
End If
If cell = True Or cell = False Then

10.

273

MySum = MySum + 0
Else
If IsNumeric(cell) Or IsDate(cell) _
Then MySum = MySum + cell
End If
Next cell
Case "Null" '
Case "Error" '
MySum = args(i)
Exit Function
Case "Boolean"
If args(i) = "True" Then MySum = MySum + 1
Case "Date"
MySum = MySum + args(i)
Case Else
MySum = MySum + args(i)
End Select
End If
Next i
End Function

MySum .
( IsMissing)
.
(Range, Error ..)
VBA TypeName.
.
- .
Variant, ,
.
(, #!/0), MySum
Excel .
Excel , 0, (.. ,
). , MySum
, (
VBA IsNumeric).
- Intersect , . , ,
.
,
MySum. , MySum ,
. 1000 ,
MySum 12 . MySum ,
, .
, ,
. , ,
, , Excel.

274

III. Visual Basic for Applications




. (#!).
, ,
.
MsgBox, . ,
- , .
,
,
( ).
, , .
, ( ), .
.
.
, ,
, DebugToggle Breakpoint
( <F9>).
Debug.Print,
Immediate VBA. ,
, .
Function VowelCount(r)
Count = 0
For i = 1 To Len(r)
Ch = UCase(Mid(r, i, 1))
If Ch Like "[AEIOU]" Then
Count = Count + 1
Debug.Print Ch, i
End If
Next i
VowelCount = Count
End Function

, Ch i, Immediate
, Debug.Print. . 10.5 , Mississippi.

. 10.5. Immediate

10.

275


Excel .
(. 10.6). ,
. ,
.

. 10.6.

, Private,
(
). VBA, , Private.


, . ,
, ( ).

Excel, Excel 2002,


. Excel 2002 , - . , , VBA.


, Excel
. , , ,
VBA.
Commission
.
Application.MacroOptions Macro:="Commission", Category:=1

276

( ,
).
.

III. Visual Basic for Applications

. 10.1 ,
VBA. , ( 10 13), ,
. , .

10.1.

10

11

12

13

14

15


(. 10.7).
: VBA.

,
. , .

. 10.7. Excel

10.

277


, .
1. VBE.
2. Excel, .
3. ,
.
4. .
5. ,
.
6. , . 10.8.
.

. 10.8.

7. , .


, . 5.

,
, 24.

, .
. ,
.

VBA

VBA. Commission.
Application.MacroOptions _
Macro:= "Commission", _
Description:= " "

( ,
).

278

III. Visual Basic for Applications




. : .
ZapSpaces,
Myfuncs.xls.
( Myfuncs.xls), .
=Myfuncs.xls!ZapSpaces(A1:C12)

Myfuncs.xls
Excel, ,
.

=ZapSpaces(A1:C12)

21.

Windows API
VBA ,
Excel VBA , DLL (Dynamic Link Library ), Windows . VBA ,
.
Windows API (Application Programming Interface
) ,
Windows. Windows VBA Windows API.
Windows, Windows,
DLL, , , .
Excel, , DLL. excel.exe, DLL, . Excel . ,
,
.
DLL . ,
Windows
. Windows DLL, . , ,
DLL, .
, DLL
VBA. Visual Basic Microsoft
DLL, Excel.

10.

279

Windows API
Windows API,
. VBA
(.. UserForm, ), API Private.
API ;
. VBA .
API .
API.
API.
API VBA.

Windows
API.
Declare Function GetWindowsDirectoryA Lib "kernel32" _
(ByVal lpBuffer As String, ByVal nSize As Long) As Long

, , ,
Windows ( VBA
). Windows
lpBuffer, nSize.
Declare
GetWindowsDirectoryA.
.
Sub ShowWindowsDir()
Dim WinPath As String
Dim WinDir As String
WinPath = Space(255)
WinDir = Left(WinPath, GetWindowsDirectoryA _
(WinPath, Len(WinPath)))
MsgBox WinDir, vbInformation, " Windows"
End Sub

ShowWindowsDir Windows. Windows


C:\Windows, . Windows NT , , C:WINNT.
(wrapper) API. ,
, API. API. VBA.
Function WindowsDir() As String
' Windows
Dim WinPath As String
WinPath = Space(255)
WindowsDir = Left(WinPath, GetWindowsDirectoryA _
(WinPath, Len(WinPath)))
End Function

.
MsgBox WindowsDir

280

III. Visual Basic for Applications

.
=WindowsDir()

API , ( ).
Windows, Excel VBA , . , , Windows API,
.
VBA Windows API.
.

<Shift>

. , VBA,
. ,
-, <Shift>. <Shift>, API GetKeyState. GetKeyState ,
. , nVirtKey, .
11 API-.

, ,
Button_Click <Shift>. ,
<Shift>
( ), GetKeyState. GetKeyState 0,
, <Shift> ; <Shift> .
Declare Function GetKeyState Lib "user32"
(ByVal nVirtKey As Long) As Integer

Sub Button_Click()
Const VK_SHIFT As Integer = &H10
If GetKeyState(VK_SHIFT) < 0 Then
MsgBox "Shift "
Else
MsgBox "Shift "
End If
End Sub

- , ( ): <Ctrl>, <Shift>, <Alt>.

Windows API
Windows API . API . ,
, . VBA-

10.

281

Excel API . Internet ,


.

282

-, , win32api.txt,
Windows API. VBA.
API
, .
,
Excel, ,
API. , ,
Excel 97 , API,
Excel 5 Excel 5 ( Excel 5 16- ). Excel 97
32- .
26.

III. Visual Basic for Applications

11


VBA

, ,
, . VBA. , ,
, , .
,
VBA. ,
Excel.
VBA
VBA
, VBA

VBA
Windows API
, , , . , VBA.
, , .
.
.
VBA.
, VBA.
, .

Windows API.

, , , ..


. , .
.
, .
, .


VBA.

-.


Excel
, , .
, , , .
,
VBA-.
Sub Macro1()
Range("A1").Select
Selection.Copy
Range("B1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub

, . VBA
.
, ,
Select.
Copy, , .
Sub CopyRange()
Range("A1").Copy Range("B1")
End Sub

, , .
, .
1 File.xls 2
File2.xls. , ,
.
Sub CopyRange2()
Workbooks("File1.xls").Sheets("1").Range("A1").Copy _
Workbooks("File2.xls").Sheets("2").Range("A1")
End Sub

284

III. Visual Basic for Applications

, .
Sub CopyRange3()
Set Rng1 = Workbooks("File1.xls"). _
Sheets("1").Range("A1")
Set Rng2 = Workbooks("File2.xls"). _
Sheets("2").Range("A1")
Rng1.Copy Rng2
End Sub

, .
, . ,
(
).
Sub CopyRange4()
Range("A1:C800").Copy Range("D1")
End Sub


VBA (. ). ,
Copy Cut. , .
18 (
A1:C6) , 1.
Sub MoveRange()
Range("A1:C6").Cut Range("H1")
End Sub


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

. 11.1.

11. VBA

285

,
1 2 ( 1).
CurrentRegion, Range,
( 1).
Sub CopyCurrentRegion2()
Range("A1").CurrentRegion.Copy _
Sheets("2").Range("A1")
End Sub

CurrentRegion :
, , . ,
. , CurrentRegion
,
.


, VBA,
, .

Excel , ( <Ctrl+Shift+ >), . Excel 2003 ,


.
, , ,
.

CurrentRegion ( ),
End Range. End ,
, . ,
, .
Range(ActiveCell, ActiveCell.End(xlDown)).Select

,
: xlUp (), xlToLeft () xlToRight
().

End. ,
End .

- ,
. ,
, ,
(. 11.2).
. SelectCurrentRegion <Ctrl+Shift+*>.
Sub SelectCurrentRegion()
ActiveCell.CurrentRegion.Select
End Sub

286

III. Visual Basic for Applications

. 11.2. , VBA

.
(,
). . ,
, SelectCurrentRegion
, Range .
, -, .
Sub FormatCurrentRegion()
Set WorkRange = ActiveCell.CurrentRegion
WorkRange.Font.Bold = True
End Sub


.
.
,
. , Activate
Worksheets.
.
,
.

11. VBA

287

VBA . ,
Range("Total"), Range("D45"). 45 . ,
(D46).
, (, <Ctrl+Shift+ > ),
. Excel .
, ,
, .
,
. ,
, .
Excel . , , <Ctrl> .
.


,
1 .
Sub GetValue1()
Range("A1").Value = InputBox(" ")
End Sub

. 11.3 .

. 11.3. InputBox
,

.
(Cancel) , , .
(Cancel) .
Sub GetValue2()
UserEntry = InputBox(" ")
If UserEntry <> "" Then Range("A1").Value = UserEntry
End Sub

, . , 1 12.
, . ,
. , (Cancel).
Sub GetValue3()
Dim MinVal As Integer, MaxVal As Integer
Dim UserEntry As String
Dim Msg As String
Dim IntEntry As Integer

288

III. Visual Basic for Applications

MinVal = 1
MaxVal = 12
Msg = " " & MinVal & " " & MaxVal
Do
UserEntry = InputBox(Msg)
If UserEntry = "" Then Exit Sub
If IsNumeric(UserEntry) Then
IntEntry = CInt(UserEntry)
If IntEntry >= MinVal And IntEntry <= MaxVal Then
Exit Do
End If
End If
Msg = " ."
Msg = Msg & vbNewLine
Msg = Msg & " " & _
MinVal & " " & MaxVal
Loop
ActiveSheet.Range("A1").Value = UserEntry
End Sub

. 11.4, ,
.

. 11.4.
, ,
VBA InputBox

InputBox , Val If .



. , (. 11.5).

. 11.5.

11. VBA

289

Sub GetData()
Dim NextRow As Long
Dim Entry1 As String, Entry2 As String
Do
NextRow = Range("A65536").End(xlUp).Row + 1
Entry1 = InputBox(" ")
If Entry1 = "" Then Exit Sub
Entry2 = InputBox(" ")
If Entry2 = "" Then Exit Sub
Cells(NextRow, 1) = Entry1
Cells(NextRow, 2) = Entry2
Loop
End Sub

, . (
Cancel) Exit Sub.

, .

,
NextRow. , : 65536 ( ), <End> . . Row
; ( ),
1.
, : ,
2.

,

, ,
, .
Excel InputBox.
, , ,
.
Sub GetUserRange()
Dim UserRange As Range
Output = 565
Prompt = " "
Title = " "

On Error Resume Next
Set UserRange = Application.InputBox( _
Prompt:=Prompt, _
Title:=Title, _
Default:=ActiveCell.Address, _
Type:=8) '
On Error GoTo 0
' ,
If UserRange Is Nothing Then
MsgBox " "
'

290

III. Visual Basic for Applications

Else
UserRange.Range("A1") = Output
End If
End Sub

. 11.6.

. 11.6.

Type 8. , On Error Resume


Next. , ,
. UserRange . .
, . On Error
Go To .
. Excel
.
, ScreenUpdating.
.


, , Count, , ( ). ,
,
.
MsgBox Selection.Count

data,
data CellCount.
CellCount = Range("data").Count

, .

.
Selection.Columns.Count


Rows.
data RowCount.
RowCount = Range("data").Rows.Count

11. VBA

291


Excel .
.
.
.
.
.
(
).
, VBA ,
- .
Range .
, ,
Areas, Areas.
.
,
, , .
NumAreas = Selection.Areas.Count

NumAreas ,
.
AboutRangeSelection AreaType, .
Function AreaType(RangeArea As Range) As String
'

Select Case True
Case RangeArea.Cells.Count = 1
AreaType = "Cell"
Case RangeArea.Count = Cells.Count
AreaType = "Worksheet"
Case RangeArea.Rows.Count = Cells.Rows.Count
AreaType = "Column"
Case RangeArea.Columns.Count = Cells.Columns.Count
AreaType = "Row"
Case Else
AreaType = "Block"
End Select
End Function

Range
, : , , ,
. Select Case
, True. , , Cell.
,
Worksheet.
, Column.
, Row. Case True, Block.

292

III. Visual Basic for Applications

, . , 65536 , Cells.Count, Excel 5 Excel 97 (


16384 ).
- (
AboutRangeSelection), AreaType
, (. 11.7).
Range.

. 11.7. AboutRangeSelection

, , Excel
. , , <Ctrl>, 1,
.
AboutRangeSelection.


, ,
, . 11.1 :
SelectiveColor1 , . .
11.1.
Sub SelectiveColor1()
'
,
If TypeName(Selection) <> "Range" Then Exit Sub
Const REDINDEX = 3
Application.ScreenUpdating = False
For Each cell In Selection
If cell.Value < 0 Then
cell.Interior.ColorIndex = REDINDEX
Else
cell.Interior.ColorIndex = xlNone
End If
Next cell
End Sub

11. VBA

293

SelectiveColor1 , .
, , ?
? ? , , ,
. (SelectiveColor2)
11.2.
11.2. SelectiveColor1
,
Sub SelectiveColor2()
'
,
Dim FormulaCells As Range
Dim ConstantCells As Range
Const REDINDEX = 3
'


On Error Resume Next
Application.ScreenUpdating = False

'


Set FormulaCells = Selection.SpecialCells _
(xlFormulas, xlNumbers)
Set ConstantCells = Selection.SpecialCells _
(xlConstants, xlNumbers)

'


If Not FormulaCells Is Nothing Then
For Each cell In FormulaCells
If cell.Value < 0 Then _
cell.Font.ColorIndex = REDINDEX
Next cell
End If


If Not ConstantCells Is Nothing Then
For Each cell In ConstantCells
If cell.Value < 0 Then
cell.Interior.ColorIndex = REDINDEX
Else
cell.Interior.ColorIndex = xlNone
End If
Next cell
End If
End Sub
'

,
. SpecialCells : , . For Each-Next.
, .

294

On Error , SpecialCells ,
.
, .

III. Visual Basic for Applications


.
, , ,
UsedRange Worksheet.
Sub DeleteEmptyRows()
Dim LastRow As Long, r As Long
LastRow = ActiveSheet.UsedRange.Rows.Count
LastRow = LastRow + ActiveSheet.UsedRange.Row - 1
Application.ScreenUpdating = False
For r = LastRow To 1 Step -1
If Application.CountA(Rows(r)) = 0 Then Rows(r).Delete
Next r
End Sub


LastRow. , , 1. , LastRow : 1.
Excel (COUNTA) ,
. 0,
. ,
For-Next. ,

. ,
.

,
InRange, , , Range.
, .
Function InRange(rng1, rng2) As Boolean
'
True, rng1 rng2
InRange = False
If rng1.Parent.Parent.Name = rng2.Parent.Parent.Name Then
If rng1.Parent.Name = rng2.Parent.Name Then
If Union(rng1, rng2).Address = rng2.Address Then
InRange = True
End If
End If
End If
End Function

, InRange , ,

. , Parent, - .
, rng1.
rng1.Parent.Name

rng1.
rng1.Parent.Parent.Name

11. VBA

295

VBA Intersection Range, Range.


. ,
, .


Excel , , . (ISTEXT), (ISLOGICAL)
(ISERROR). , VBA IsEmpty, IsDate
IsNumeric.
CellType, - (, , , , , ),
.
VBA.
Function CellType(Rng)
'

'

Application.Volatile
Set Rng = Rng.Range("A1")
Select Case True
Case IsEmpty(Rng)
CellType = ""
Case WorksheetFunction.IsText(Rng)
CellType = ""
Case WorksheetFunction.IsLogical(Rng)
CellType = " "
Case WorksheetFunction.IsErr(Rng)
CellType = ""
Case IsDate(Rng)
CellType = ""
Case InStr(1, Rng.Text, ":") <> 0
CellType = ""
Case IsNumeric(Rng)
CellType = ""
End Select
End Function

Set Rng. CellType


- , ,
(
TheCell).


, , . ,
Excel , .
WriteReadRange, 11.3, .
For-Next
.
Timer , .

296

III. Visual Basic for Applications

11.3.

Sub WriteReadRange()
Dim MyArray()
Dim Time1 As Date
Dim NumElements As Long, i As Long
Dim WriteTime As String, ReadTime As String
Dim Msg As String
NumElements = 60000
ReDim MyArray(1 To NumElements)
'


For i = 1 To NumElements
MyArray(i) = i
Next i

'


Time1 = Timer
For i = 1 To NumElements
Cells(i, 1) = MyArray(i)
Next i
WriteTime = Format(Timer - Time1, "00:00")

'


Time1 = Timer
For i = 1 To NumElements
MyArray(i) = Cells(i, 1)
Next i
ReadTime = Format(Timer - Time1, "00:00")


Msg = ": " & WriteTime
Msg = Msg & vbCrLf
Msg = Msg & ": " & ReadTime
MsgBox Msg, vbOKOnly, NumElements & " "
End Sub

'

60000 15
, 4 , .


For-Next.
.
11.4,
( ) . For-Next.
11.4.
Sub LoopFillRange()
'

Dim
Dim
Dim
Dim
'

CellsDown As Long, CellsAcross As Integer


CurrRow As Long, CurrCol As Integer
StartTime As Date
CurrVal As Long

11. VBA

297

CellsDown = Val(InputBox(" ?"))


CellsAcross = Val(InputBox(" ?"))
'


StartTime = Timer

'


CurrVal = 1
Application.ScreenUpdating = False
For CurrRow = 1 To CellsDown
For CurrCol = 1 To CellsAcross
ActiveCell.Offset(CurrRow - 1, _
CurrCol - 1).Value = CurrVal
CurrVal = CurrVal + 1
Next CurrCol
Next CurrRow


Application.ScreenUpdating = True
MsgBox Format(Timer - StartTime, "00.00") & " seconds"
End Sub
'

11.5
.
.
11.5.
Sub ArrayFillRange()
'

Dim
Dim
Dim
Dim
Dim
Dim

CellsDown As Long, CellsAcross As Integer


i As Long, j As Integer
StartTime As Date
TempArray() As Long
TheRange As Range
CurrVal As Long

'


CellsDown = Val(InputBox(" ?"))
CellsAcross = Val(InputBox(" "))

'


StartTime = Timer

'


ReDim TempArray(1 To CellsDown, 1 To CellsAcross)

'


Set TheRange = ActiveCell.Range(Cells(1, 1), _
Cells(CellsDown, CellsAcross))

'


CurrVal = 0
Application.ScreenUpdating = False
For i = 1 To CellsDown
For j = 1 To CellsAcross
TempArray(i, j) = CurrVal + 1
CurrVal = CurrVal + 1
Next j
Next i

'


TheRange.Value = TempArray

298

III. Visual Basic for Applications


Application.ScreenUpdating = True
MsgBox Format(Timer - StartTime, "00.00") & " "
End Sub
'

, 500256 (128000
) 202,34 .
0,77 250
! ?
Excel, .


,
(
).

.. .
, .
Excel (TRANSPOSE).
100- (A1:A100).
Range(A1:A100).Value = _
Application.WorksheetFunction.Transpose(MyArray)

Variant

Excel VBA. , ,
Variant. Variant.
Sub RangeToVariant()
Dim x As Variant
x = Range("A1:L600")
MsgBox UBound(x, 1)
MsgBox UBound(x, 2)
End Sub

600 (
), 12 ( ). ,
Variant .
Variant,
Variant
.
Sub RangeToVariant2()
Dim UserRange As Range
Dim x As Variant
Dim r As Long, c As Integer
Set UserRange = Range("A1:L600")
'


x = Range("A1:L50")

'


For r = 1 To UBound(x, 1)
For c = 1 To UBound(x, 2)
Multiply by 2

'

11. VBA

299

x(r, c) = x(r, c) * 2
Next c
Next r

Range("A1:L50") = x
End Sub
'


GoToMax 11.6 , . ; , .
Find.
11.6. ,
Sub GoToMax()
'

Dim WorkRange as Range
Dim MaxVal as Double
'
,
If TypeName(Selection) <> "Range" Then Exit Sub
'
'

, ;

If Selection.Count = 1 Then
Set Workrange = Cells
Else
Set Workrange = Selection
End If

'


MaxVal = Application.Max(Workrange)


On Error Resume Next
Workrange.Find(What:=MaxVal, _
After:=Workrange.Range("A1"), _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False _
).Select
If Err <> 0 Then MsgBox " : " _
& MaxVal
End Sub

'

, , Find
Excel .


FindFormat
, . , , .. . 11.8 .

300

III. Visual Basic for Applications

. 11.8.

FindFormat Excel 2002. ,


Excel.

SelectByFormat .
Sub SelectByFormat()
'

'

Excel 2002
If Val(Application.Version) < 10 Then
MsgBox " Excel 2002 "
Exit Sub
End If
Dim FirstCell As Range, FoundCell As Range
Dim AllCells As Range

'


With Application.FindFormat
.Clear
.Interior.ColorIndex = 6 '
.Font.Bold = True
End With

'


Set FirstCell = Cells.Find(What:="", SearchFormat:=True)

'

,
If FirstCell Is Nothing Then
MsgBox " "
Exit Sub
End If

'

AllCells
Set AllCells = FirstCell
Set FoundCell = FirstCell

'

, FirstCell
Do
Set FoundCell = Cells.FindNext(After:=FoundCell)
Set AllCells = Union(FoundCell, AllCells)
If FoundCell.Address = FirstCell.Address Then Exit Do
Loop

11. VBA

301


AllCells.Select
MsgBox " : " & AllCells.Count
End Sub
'

FindFormat.
: . , .
Find , .
What Find , , . , SearchFormat
True, ,
.
, ,
. AllCells ( ).
FindNext ,
, . ,
, .

, Excel.

VBA .

-.



Workbooks , .
Public Sub SaveAllWorkbooks()
Dim Book As Workbook
For Each Book In Workbooks
If Book.Path <> "" Then Book.Save
Next Book
End Sub

, Path. - Path , ,
( ).
, Path .

302

III. Visual Basic for Applications

Workbooks.

Sub CloseAllWorkbooks()
Dim Book As Workbook
For Each Book In Workbooks
If Book.Name <> ThisWorkbook.Name Then
Book.Close savechanges:=True
End If
Next Book
ThisWorkbook.Close savechanges:=True
End Sub

, If , . ,
, ,
, .


Excel , . VBA. ,
.
Sub LastSaved()
Dim SaveTime As String
On Error Resume Next
SaveTime = ActiveWorkbook. _
BuiltinDocumentProperties("Last Save Time").Value
If SaveTime = "" Then
MsgBox ActiveWorkbook.Name & " "
Else
MsgBox ": " & SaveTime, , ActiveWorkbook.Name
End If
End Sub

,
Last Save Time . On Error .
If-Then-Else SaveTime
. , ,
. . 11.9 .

. 11.9.

,
VBA, Excel.
.

11. VBA

303


, , ,
, , Excel .
, , . VBA,
,
.
, .
, .
.
Sub SynchSheets()
'

'

If TypeName(ActiveSheet) <> "Worksheet" Then Exit Sub
Dim UserSheet As Worksheet, sht As Worksheet
Dim TopRow As Long, LeftCol As Integer
Dim UserSel As String
Application.ScreenUpdating = False
'


Set UserSheet = ActiveSheet

'


TopRow = ActiveWindow.ScrollRow
LeftCol = ActiveWindow.ScrollColumn
UserSel = ActiveWindow.RangeSelection.Address

'


For Each sht In ActiveWorkbook.Worksheets
If sht.Visible Then '
sht.Activate
Range(UserSel).Select
ActiveWindow.ScrollRow = TopRow
ActiveWindow.ScrollColumn = LeftCol
End If
Next sht


UserSheet.Activate
Application.ScreenUpdating = True
End Sub
'

VBA


VBA,
.

304

, ,
-.

III. Visual Basic for Applications

Boolean
Boolean , :
True () False ().
Not, ,
WrapText .
Sub ToggleWrapText()
'
If TypeName(Selection) = "Range" Then
Selection.WrapText = Not ActiveCell.WrapText
End If
End Sub

, .
(,
, ), , Excel
. , ,
, .
Excel.
, TypeName ,
. , .
Not .
,
.
ActiveWindow.DisplayHeadings = Not _
ActiveWindow.DisplayHeadings

.
ActiveWindow.DisplayGridlines = Not _
ActiveWindow.DisplayGridlines


,
Excel , . VBA
.
Sub PageCount()
MsgBox (ActiveSheet.HPageBreaks.Count + 1) * _
(ActiveSheet.VPageBreaks.Count + 1)
End Sub

VBA
.
Sub ShowPageCount()
Dim PageCount As Integer
Dim sht As Worksheet
PageCount = 0
For Each sht In Worksheets
PageCount = PageCount + (sht.HPageBreaks.Count + 1) * _
(sht.VPageBreaks.Count + 1)
Next sht
MsgBox " = " & PageCount
End Sub

11. VBA

305


, Excel , VBA.
DateAndTime
(. 11.10). .

. 11.10. ,

, 11.7,
Format Date.
. .
11.7.
Sub DateAndTime()
TheDate = Format(Date, "Long Date")
TheTime = Format(Time, "Medium Time")
'


Select Case Time
Case Is < TimeValue("12:00"): Greeting = " , "
Case Is >= TimeValue("17:00"): Greeting = " , "
Case Else: Greeting = " , "
End Select

'


FullName = Application.UserName
SpaceInName = InStr(1, FullName, " ", 1)

'

,
If SpaceInName = 0 Then SpaceInName = Len(FullName)
FirstName = Left(FullName, SpaceInName)
Greeting = Greeting & FirstName


MsgBox TheDate & vbCrLf & TheTime, vbOKOnly, Greeting
End Sub

'

(Long Date Medium


Time)
. .
, //,
.
TheDate = Format(Date, "mm/dd/yy")

, , Select Case.
VBA , Excel. 0,5 (), .
0,7083 (5 ), .

306

III. Visual Basic for Applications

. VBA TimeValue,
.
,
.
VBA InStr.
, , . , Nobody,
, ,
. ( ,
, Excel User.)
: SpaceInName
, Left .
MsgBox ,
vbCrLf . vbOKOnly , 0; .
Greeting, .

,
, Excel .
.

. FontConrol
.
(, ),
CommandBar, .
CommandBar
22.

Sub ShowInstalledFonts()
Dim FontList As CommandBarControl
Dim TempBar As CommandBar
Dim i As Integer
Set FontList = Application.CommandBars("Formatting"). _
FindControl(ID:=1728)
'

,
If FontList Is Nothing Then
Set TempBar = Application.CommandBars.Add
Set FontList = TempBar.Controls.Add(ID:=1728)
End If

'


Range("A:A").ClearContents
For i = 0 To FontList.ListCount - 1
Cells(i + 1, 1) = FontList.List(i + 1)
Next i

,
On Error Resume Next
TempBar.Delete
End Sub
'

11. VBA

307


. For-Next.
Cells(i+1,1).Font.Name = FontList.List(i+1)
,
, .


, Excel ,
VBA . ,
, Excel,
.
, VBA .
.
. Excel; . . 65536 ( ).
(
9). ,
,
.
. ,
, , , .

. ,
.

- ,
.
.

. 11.11 . ( 100 100000 );


( Double).

. 11.11. ,

. 11.1 . 0,00 , 0,01 .

308

III. Visual Basic for Applications

11.1. ,


Excel

VBA

VBA

VBA

100
500
1000
5000
10000
50000
100000

0,05
0,06
0,11
0,55
1,16
6,98

0,00
0,11
0,44
8,89
31,69
788,62

0,05
0,05
0,11
0,77
1,75
10,21
20,60

0,00
0,00
0,00
0,05
0,06
0,22
0,44

, , :
.
, , ,
. ,
.


. 11.8 ,
, . ,
,
.
, .
11.8. ,
Sub BatchProcess()
Dim FS As FileSearch
Dim FilePath As String, FileSpec As String
Dim i As Integer
'


FilePath = ThisWorkbook.Path & "\"
FileSpec = "text??.txt"

'

FileSearch
Set FS = Application.FileSearch
With FS
.NewSearch
.LookIn = FilePath
.FileName = FileSpec
.Execute
,
If .FoundFiles.Count = 0 Then
MsgBox "No files were found"
Exit Sub
End If
End With

'

11. VBA

309


For i = 1 To FS.FoundFiles.Count
Call ProcessFiles(FS.FoundFiles(i))
Next i
End Sub


'

,
-: Text01.txt, Text02.txt Text03.txt. ,
. FileSearch,
Excel 2000 .

FileSearch,
For-Next. ProcessFiles, .
OpenText . , , .
Sub ProcessFiles(FileName As String)
'

Workbooks.OpenText FileName:=FileName, _
Origin:=xlWindows, _
StartRow:=1, _
DataType:=xlFixedWidth, _
FieldInfo:= _
Array(Array(0, 1), Array(3, 1), Array(12, 1))
'

Range("D1").Value = "A"
Range("D2").Value = "B"
Range("D3").Value = "C"
Range("E1:E3").Formula = "=COUNTIF(B:B,D1)"
Range("F1:F3").Formula = "=SUMIF(B:B,D1,C:C)"
End Sub

,
VBA

,
. ,
VBA. , Private
Excel .

, ,
-.

FileExists
( ) ,
.
Private Function FileExists(fname) As Boolean
' ,
FileExists = (Dir(fname) <> "")
End Function

310

III. Visual Basic for Applications

FileNameOnly
( )
. , .
Private Function FileNameOnly(pname) As String
'
/
Dim i As Integer, length As Integer, temp As String
length = Len(pname)
temp = ""
For i = length To 1 Step -1
If Mid(pname, i, 1) = Application.PathSeparator Then
FileNameOnly = temp
Exit Function
End If
temp = Mid(pname, i, 1) & temp
Next i
FileNameOnly = pname
End Function

FileNameOnly (
). ,
.
Private Function FileNameOnly2(pname) As String
FileNameOnly2 = Dir(pname)
End Function

PathExists
() , .
Private Function PathExists(pname) As Boolean
'
,
Dim x As String
On Error Resume Next
x = GetAttr(pname) And 0
If Err = 0 Then PathExists = True _
Else PathExists = False
End Function

RangeNameExists
( ) ,
.
Private Function RangeNameExists(nname) As Boolean
'
,
Dim n As Name
RangeNameExists = False
For Each n In ActiveWorkbook.Names
If UCase(n.Name) = UCase(nname) Then
RangeNameExists = True
Exit Function
End If
Next n
End Function

11. VBA

311

SheetExists
( ) ,
.
Private Function SheetExists(sname) As Boolean
'
,
Dim x As Object
On Error Resume Next
Set x = ActiveWorkbook.Sheets(sname)
If Err = 0 Then SheetExists = True _
Else SheetExists = False
End Function

WorkbookIsOpen
( ) ,
.
Private Function WorkbookIsOpen(wbname) As Boolean
'
,
Dim x As Workbook
On Error Resume Next
Set x = Workbooks(wbname)
If Err = 0 Then WorkbookIsOpen = True _
Else WorkbookIsOpen = False
End Function


,
, .
Private Function IsInCollection(Coln As Object, _
Item As String) As Boolean
Dim Obj As Object
On Error Resume Next
Set Obj = Coln(Item)
IsInCollection = Not Obj Is Nothing
End Function
: () (),
.
, . ,
True; False.
IsInCollection , : RangeNameExists, SheetExists WorkbookIsOpen. , Data,
IsInCollection .
MsgBox IsInCollection(ActiveWorkbook.Names, "Data")
, Budget, .
MsgBox IsInCollection(Workbooks, "budget.xls")
, 1,
MsgBox IsInCollection(ActiveWorkbook.Worksheets, "1")

312

III. Visual Basic for Applications


VBA
.
, Excel. VBA
(GetValue, ), .
XLM.
Private Function GetValue(path, file, sheet, ref)
'

Dim arg As String
'


If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = " "
Exit Function
End If

'


arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)

XLM
GetValue = ExecuteExcel4Macro(arg)
End Function

'

GetValue :
path (, "d:\files");
file (, "budget.xls");
sheet (, "1");
ref (, "C4").
, GetValue.
1 1 99Budget.xls
( XLFiles\Budget :).
Sub TestGetValue()
p = ":\XLFiles\Budget"
f = "99Budget.xls"
s = "1"
a = "A1"
MsgBox GetValue(p, f, s, a)
End Sub

. 1200
(100 12 )
.
Sub TestGetValue2()
p = "c:\XLFiles\Budget"
f = "99Budget.xls"
s = "Sheet1"
Application.ScreenUpdating = False
For r = 1 To 100
For c = 1 To 12
a = Cells(r, c).Address
Cells(r, c) = GetValue(p, f, s, a)
Next c

11. VBA

313

Next r
Application.ScreenUpdating = True
End Sub

GetValue , .
. .

Excel

, , ,
. ,
VBA (
(ThisWorkbook), ).

-.


, . (, , , , ).

,

Excel. (
), <Ctrl+Alt+F9>.

, ,
, .
Function ISBOLD(cell) As Boolean
' ,
ISBOLD = cell.Range("A1").Font.Bold
End Function

, () .
Function ISITALIC(cell) As Boolean
' ,
ISITALIC = cell.Range("A1").Font.Italic
End Function

,
(,
). , , ,
.
Function ALLBOLD(cell) As Boolean
' ,
'
If IsNull(cell.Font.Bold) Then
ALLBOLD = False
Else

314

III. Visual Basic for Applications

ALLBOLD = cell.Font.Bold
End If
End Function

FILLCOLOR, , , ( ).
, 4142.
Function FILLCOLOR(cell) As Integer
' ,
'
FILLCOLOR = cell.Range("A1").Interior.ColorIndex
End Function



Excel , BuiltinDocumentProperties
Workbook. .
Function LASTSAVED()
Application.Volatile
LASTSAVED = ThisWorkbook. _
BuiltinDocumentProperties("Last Save Time")
End Function

,

.
Function LASTPRINTED()
Application.Volatile
LASTPRINTED = ThisWorkbook. _
BuiltinDocumentProperties("Last Print Date")
End Function


( <Ctrl+Alt+F9>), .

, Excel .
, , ,
.

LASTSAVE LASTPRINTED
, .
, ( personal.xls),
, .
(ThisWorkbook), . .
Application.Caller,
Range. , . .

11. VBA

315

Function LastSaved2()
Application.Volatile
LastSaved2 = Application.Caller.Parent.Parent. _
BuitinDocumentProperties("Last Save Time")
End Function
Function LASTPRINTED2()
Application.Volatile
LastSaved2 = Application.Caller.Parent.Parent. _
BuitinDocumentProperties("Last Print Date")
End Function


, Excel :
.
Application. Excel , , ,
.. ,
Range.
Application
Workbook
Worksheet
Range
-
Range () Worksheet ( ), . Worksheet Workbook ( ),
, Workbook
Application (, .. Excel).
?
VBA SheetName, .
() , .
Parent Range. Parent
, , Range.
Function SheetName(ref) As String
SheetName = ref.Parent.Name
End Function

WorkbookName
. , Parent .
Parent Worksheet, Parent
Workbook.
Function WorkbookName(ref) As String
WorkbookName = ref.Parent.Parent.Name
End Function

AppName, ,
, Parent . Application . ,
Microsoft Excel.
Function AppName(ref) As String
AppName = ref.Parent.Parent.Parent.Name
End Function

316

III. Visual Basic for Applications


COUNTBETWEEN
( ), ,
.
Function COUNTBETWEEN(InRange, num1, num2) As Long
'
num1 num2
With Application.WorksheetFunction
COUNTBETWEEN = .CountIf(InRange, ">=" & num1) - _
.CountIf(InRange, ">" & num2)
End With
End Function

, Excel (COUNTIF).
, COUNTBETWEEN ,
.
, COUNTBETWEEN.
1:100, 10
20.
=COUNTBETWEEN(A1:A100;10;20)

VBA, .
=((A1:A100; ">=10"))-(A1:A100; ">=20"))


COUNTVISIBLE, , ()
. ,
.
Function COUNTVISIBLE(rng)
'

Dim CellCount As Long
Dim cell As Range
Application.Volatile
CellCount = 0
Set rng = Intersect(rng.Parent.UsedRange, rng)
For Each cell In rng
If Not IsEmpty(cell) Then
If Not cell.EntireRow.Hidden And _
Not cell.EntireColumn.Hidden Then _
CellCount = CellCount + 1
End If
Next cell
COUNTVISIBLE = CellCount
End Function

,
. , ,
. , , ,
CellCount 1.
COUNTVISIBLE . .

Excel . ( 2 3)
.

11. VBA

317

Excel 2003 100 ..


. ( ) .
. : , .



: LASTINCOLUMN
, LASTINROW, .
.
( LASTINCOLUMN) ( LASTINROW).
, . ,
.
=LASTINCOLUMN(B5)

7.
=LASTINROW(C7:D9)

LASTINCOLUMN
LASTINCOLUMN .
Function LASTINCOLUMN(rng As Range)
Application.Volatile
Set LastCell = rng.Parent.Cells(Rows.Count, rng.Column) _
.End(xlUp)
LASTINCOLUMN = LastCell.Value
If IsEmpty(LastCell) Then LASTINCOLUMN = ""
If rng.Parent.Cells(Rows.Count, rng.Column) <> "" Then _
LASTINCOLUMN = rng.Parent.Cells(Rows.Count, rng.Column)
End Function

, ,
.
Application.Volatile ,
.
Rows.Count . , 65536,
( Excel
).
rng.Column rng.
rng.Parent , rng .
End ( xlUp)
<End> .
IsEmpty , . ,
.
0.
If .
, .

318

III. Visual Basic for Applications

LASTINROW
LASTINROW .
LASTINCOLUMN.
Function LASTINROW(rng As Range)
Application.Volatile
Set LastCell = rng.Parent.Cells(rng.Row, Columns.Count) _
.End(xlToLeft)
LASTINROW = LastCell.Value
If IsEmpty(LastCell) Then LASTINROW = ""
If rng.Parent.Cells(rng.Row, Columns.Count) <> "" Then _
LASTINROW = rng.Parent.Cells(rng.Row, Columns.Count)
End Function

?
ISLIKE ( ). ,
.
ISLIKE . , ,
VBA Like.
Function ISLIKE(text As String, pattern As String) As Boolean
' , ,
If text Like pattern Then ISLIKE = True _
Else ISLIKE = False
End Function

ISLIKE :
text , ;
pattern , .
()

(09)

[_]

[!_]

,
_

, *
. , ,
g.
=ISLIKE("guitar"; "g*")

, ? . "Unit12", .
=ISLIKE("Unit1"; "Unit?")

,
.
=ISLIKE("a"; "[aeiou]")

11. VBA

319

, 1 : a, e, i, o, u, A, E, I, O, U. UPPER .
=ISLIKE(UPPER(A1); UPPER("[aeiou]"))

, 1
, 1 (..
100 199).
=ISLIKE(A1; "1##")

n6
ExtractElement (
VBA), .
, ,
ExtractElement .
123-456-789-0133-8844

, , 0133, ..
. (-) .
=ExtractElement("123-456-789-0133-8844",4,"-")

ExtractElement :
Txt , .
;
n , ;
Separator , .

- ,
, . n
, .

VBA ExtractElement.
Function ExtractElement(Txt, n, Separator) As String
' n- ,
' -.
Dim AllElements As Variant
AllElements = Split(Txt, Separator)
EXTRACTELEMENT = AllElements(n-1)
End Function

VBA- Split, , .
( ), n-1.
, Split Excel 2000.
, .
Function ExtractElement(Txt, n, Separator) As String
' n- ,
' -.
Dim Txt1 As String, TempElement As String

320

III. Visual Basic for Applications

Dim ElementCount As Integer, i As Integer


'

Txt1 = Txt
,
If Separator = Chr(32) Then Txt1 = Application.Trim(Txt1)

'


If Right(Txt1, Len(Txt1)) <> Separator Then _
Txt1 = Txt1 & Separator

'

ElementCount = 0
TempElement = ""


For i = 1 To Len(Txt1)
If Mid(Txt1, i, 1) = Separator Then
ElementCount = ElementCount + 1
If ElementCount = n Then
'
n- ,
ExtractElement = TempElement
Exit Function
Else
TempElement = ""
End If
Else
TempElement = TempElement & Mid(Txt1, i, 1)
End If
Next i
ExtractElement=""
End Function
'


, ,
, . ,
VBA StatFunction.
: (rng) (op). op ,
Excel: (AVERAGE), (COUNT), (MAX), (MEDIAN), (MIN),
(MODE), (STDEV), (SUM) (VAR).
,
.
=STATFUNCTION(B1:B24;A24)

24,
: (AVERAGE), (COUNT), (MAX) ..
.
Function STATFUNCTION(rng,
Select Case UCase(op)
Case "SUM"
STATFUNCTION =
Case "AVERAGE"
STATFUNCTION =
Case "MEDIAN"
STATFUNCTION =
Case "MODE"
STATFUNCTION =
Case "COUNT"
STATFUNCTION =

op)
WorksheetFunction.Sum(rng)
WorksheetFunction.Average(rng)
WorksheetFunction.Median(rng)
WorksheetFunction.Mode(rng)
WorksheetFunction.Count(rng)

11. VBA

321

Case "MAX"
STATFUNCTION
Case "MIN"
STATFUNCTION
Case "VAR"
STATFUNCTION
Case "STDEV"
STATFUNCTION
Case Else
STATFUNCTION
End Select
End Function

= WorksheetFunction.Max(rng)
= WorksheetFunction.Min(rng)
= WorksheetFunction.Var(rng)
= WorksheetFunction.StDev(rng)
= CVErr(xlErrNA)

SHEETOFFSET
, , Excel
. , ,
.
, .

, ,
.
, , VBA ( SHEETOFFSET), .
, 1
.
=SHEETOFFSET(-1;A1)

,
. .
,
.
VBA SHEETOFFSET.
Function SHEETOFFSET(Offset As Long, Optional Cell As Variant)
Dim WksIndex As Long, WksNum As Long
Dim wks As Worksheet
Application.Volatile
If IsMissing(Cell) Then Set Cell = Application.Caller
WksNum = 1
For Each wks In Application.Caller.Parent.Parent.Worksheets
If Application.Caller.Parent.Name = wks.Name Then
SHEETOFFSET = Worksheets(WksNum + Offset).Range(Cell(1).Address)
Exit Function
Else
WksNum = WksNum + 1
End If
Next wks
End Function


1
, .
=(1:4!B1)

1 1,
4 .

322

III. Visual Basic for Applications

, 4 (5)? , ,
.
=MA(1:5!B1)

MAXALLSHEETS, , ( )

. , 1 .
=MAXALLSHEETS(B1)

.
Function MAXALLSHEETS(cell)
Dim MaxVal As Double
Dim Addr As String
Dim Wksht As Object
Application.Volatile
Addr = cell.Range("A1").Address
MaxVal = -9.9E+307
For Each Wksht In cell.Parent.Parent.Worksheets
If Wksht.Name = cell.Parent.Name And _
Addr = Application.Caller.Address Then
'
Else
If IsNumeric(Wksht.Range(Addr)) Then
If Wksht.Range(Addr) > MaxVal Then _
MaxVal = Wksht.Range(Addr).Value
End If
End If
Next Wksht
If MaxVal = -9.9E+307 Then MaxVal = 0
MAXALLSHEETS = MaxVal
End Function

For Each .
cell.Parent.Parent.Worksheets

,
. , For Each .
If , ,
, . , .

,
, ,
..


RANDOMINTEGERS, ,
.
.

<Ctrl+Shift+Enter>. ,
. 40 ,
1 40.

11. VBA

323

RANDOMINTEGERS.
Function RANDOMINTEGERS()
Dim FuncRange As Range
Dim V() As Variant, ValArray() As Variant
Dim CellCount As Double
Dim i As Integer, j As Integer
Dim r As Integer, c As Integer
Dim Temp1 As Variant, Temp2 As Variant
Dim RCount As Integer, CCount As Integer
Randomize
'

Range
Set FuncRange = Application.Caller

'

, FuncRange
CellCount = FuncRange.Count
If CellCount > 1000 Then
RANDOMINTEGERS = CVErr(xlErrNA)
Exit Function
End If

'


RCount = FuncRange.Rows.Count
CCount = FuncRange.Columns.Count
ReDim V(1 To RCount, 1 To CCount)
ReDim ValArray(1 To 2, 1 To CellCount)

'
'



For i = 1 To CellCount
ValArray(1, i) = Rnd
ValArray(2, i) = i
Next i

'

ValArray
For i = 1 To CellCount
For j = i + 1 To CellCount
If ValArray(1, i) > ValArray(1, j) Then
Temp1 = ValArray(1, j)
Temp2 = ValArray(2, j)
ValArray(1, j) = ValArray(1, i)
ValArray(2, j) = ValArray(2, i)
ValArray(1, i) = Temp1
ValArray(2, i) = Temp2
End If
Next j
Next i

V
i = 0
For r = 1 To RCount
For c = 1 To CCount
i = i + 1
V(r, c) = ValArray(2, i)
Next c
Next r
RANDOMINTEGERS = V
End Function
'

324

III. Visual Basic for Applications



RANGERANDOMIZE, ,
, .
Function RANGERANDOMIZE(rng)
Dim V() As Variant, ValArray() As Variant
Dim CellCount As Double
Dim i As Integer, j As Integer
Dim r As Integer, c As Integer
Dim Temp1 As Variant, Temp2 As Variant
Dim RCount As Integer, CCount As Integer
Randomize
'

,
CellCount = rng.Count
If CellCount > 1000 Then
RANGERANDOMIZE = CVErr(xlErrNA)
Exit Function
End If

'


RCount = rng.Rows.Count
CCount = rng.Columns.Count
ReDim V(1 To RCount, 1 To CCount)
ReDim ValArray(1 To 2, 1 To CellCount)

'
'


rng
For i = 1 To CellCount
ValArray(1, i) = Rnd
ValArray(2, i) = rng(i)
Next i

'

ValArray
For i = 1 To CellCount
For j = i + 1 To CellCount
If ValArray(1, i) > ValArray(1, j) Then
Temp1 = ValArray(1, j)
Temp2 = ValArray(2, j)
ValArray(1, j) = ValArray(1, i)
ValArray(2, j) = ValArray(2, i)
ValArray(1, i) = Temp1
ValArray(2, i) = Temp2
End If
Next j
Next i

V
i = 0
For r = 1 To RCount
For c = 1 To CCount
i = i + 1
V(r, c) = ValArray(2, i)
Next c
Next r
RANGERANDOMIZE = V
End Function
'

11. VBA

325

RANGERANDOMIZE RANDOMINTEGERS.
. 11.12 RANGERANDOMIZE. B2:B11
.
{=RANGERANDOMIZE(A2:A11)}

A2:A11, .

. 11.12. RANGERANDOMIZE

Windows API
VBA ,
(Dynamic Link Libraries DDL).
Windows API.

API Excel. 32- API 16- Excel 5, . , 16- 32-


Excel 95 .
32- Excel.

25.


Windows .
;
.
GetExecutable Windows API
, . ,
.txt , Readme.txt
Windows. GetExecutable (
).

326

Windows API VBA.

III. Visual Basic for Applications

Private Declare Function FindExecutableA Lib "shell32.dll"_


(ByVal lpFile As String, ByVal lpDirectory As String,_
ByVal lpResult As String) As Long
Function GetExecutable(strFile As String) As String
Dim strPath As String
Dim intLen As Integer
strPath = Space(255)
intLen = FindExecutableA(strFile, "\", strPath)
GetExecutable = Trim(strPath)
End Function

. 11.13 GetExecutable
c:\windows\readme.txt.
NOTEPAD.EXE.

. 11.13. ,


, , Windows API
. .
.
Private Declare Function GetProfileStringA Lib "kernel32" _
(ByVal lpAppName As String, ByVal lpKeyName As String, _
ByVal lpDefault As String, ByVal lpReturnedString As _
String, ByVal nSize As Long) As Long
Sub DefaultPrinterInfo()
Dim strLPT As String * 255
Dim Result As String
Call GetProfileStringA _
("Windows", "Device", "", strLPT, 254)
Result = Application.Trim(strLPT)
ResultLength = Len(Result)
Comma1 = Application.Find(",", Result, 1)
Comma2 = Application.Find(",", Result, Comma1 + 1)
'


Printer = Left(Result, Comma1 - 1)

'


Driver = Mid(Result, Comma1 + 1, Comma2 - Comma1 - 1)

'


Port = Right(Result, ResultLength - Comma2)

'


Msg = ":" & Chr(9) & Printer & Chr(13)
Msg = Msg & ":" & Driver & Chr(13)
Msg = Msg & ":" & Chr(9) & Port


MsgBox Msg, vbInformation, " "
End Sub
'

11. VBA

327

ActivePrinter Application
( ).
, .
.

. 11.14 ,
.

. 11.14.
Windows API


Windows API
.
, , , ,
, .
' 32- API-
Declare Function GetSystemMetrics Lib "user32" _
(ByVal nIndex As Long) As Long
Public Const SM_CXSCREEN = 0
Public Const SM_CYSCREEN = 1
Sub DisplayVideoInfo()
vidWidth = GetSystemMetrics(SM_CXSCREEN)
vidHeight = GetSystemMetrics(SM_CYSCREEN)
Msg = " : "
Msg = Msg & vidWidth & " X " & vidHeight
MsgBox Msg
End Sub

. 11.15 , 1024768.

. 11.15.
Windows API


Excel . VBA Beep. API
WAV MIDI.
. ,
, CanPlaySounds.
Sub CanPlaySound()
If Not Application.CanPlaySounds Then
MsgBox ", "
End If
End Sub

328

III. Visual Basic for Applications

WAV
API
dogbark.wav (,
, ).
Private Declare Function PlaySound Lib "winmm.dll" _
Alias "PlaySoundA" (ByVal lpszName As String, _
ByVal hModule As Long, ByVal dwFlags As Long) As Long
Const SND_SYNC = &H0
Const SND_ASYNC = &H1
Const SND_FILENAME = &H20000
Sub PlayWAV()
WAVFile = "dogbark.wav"
WAVFile = ThisWorkbook.Path & "\" & WAVFile
Call PlaySound(WAVFile, 0&, SND_ASYNC Or SND_FILENAME)
End Sub

WAV . ,
, . ,
Call PlaySound(WAVFile, 0&, SND_SYNC Or SND_FILENAME)

MIDI
MIDI,
API. MIDI PlayMIDI. StopMIDI MIDI. xfiles.mid.
Private Declare Function mciExecute Lib "winmm.dll" _
(ByVal lpstrCommand As String) As Long
Sub PlayMIDI()
MIDIFile = "xfiles.mid"
MIDIFile = ThisWorkbook.Path & "\" & MIDIFile
mciExecute ("play " & MIDIFile)
End Sub
Sub StopMIDI()
MIDIFile = "xfiles.mid"
MIDIFile = ThisWorkbook.Path & "\" & MIDIFile
mciExecute ("stop " & MIDIFile)
End Sub


Alarm, ,
. Windows API ,
.
Declare Function PlaySound Lib "winmm.dll" _
Alias "PlaySoundA" (ByVal lpszName As String, _
ByVal hModule As Long, ByVal dwFlags As Long) As Long
Function ALARM(Cell, Condition)
Dim WAVFile As String
Const SND_ASYNC = &H1
Const SND_FILENAME = &H20000

11. VBA

329

If Evaluate(Cell.Value & Condition) Then


WAVFile = ThisWorkbook.Path & "\sound.wav"
Call PlaySound(WAVFile, 0&, SND_ASYNC Or SND_FILENAME)
ALARM = True
Else
ALARM = False
End If
End Function

Alarm : (
). , Alarm WAV, 13 1000.
=ALARM(B13; ">=1000")

VBA Evaluate ,
. ( ), , .


Windows ( 4). VBA .
Windows API.
Private Declare Function RegOpenKeyA Lib "ADVAPI32.DLL" _
(ByVal hKey As Long, ByVal sSubKey As String, _
ByRef hkeyResult As Long) As Long
Private Declare Function RegCloseKey Lib "ADVAPI32.DLL" _
(ByVal hKey As Long) As Long
Private Declare Function RegSetValueExA Lib "ADVAPI32.DLL" _
(ByVal hKey As Long, ByVal sValueName As String, _
ByVal dwReserved As Long, ByVal dwType As Long, _
ByVal sValue As String, ByVal dwSize As Long) As Long
Private Declare Function RegCreateKeyA Lib "ADVAPI32.DLL" _
(ByVal hKey As Long, ByVal sSubKey As String, _
ByRef hkeyResult As Long) As Long

Private Declare Function RegQueryValueExA Lib "ADVAPI32.DLL" _


(ByVal hKey As Long, ByVal sValueName As String, _
ByVal dwReserved As Long, ByRef lValueType As Long, _
ByVal sValue As String, ByRef lResultLen As Long) As Long

330

-, :
GetRegistry WriteRegistry.
-. , .

III. Visual Basic for Applications


GetRegistry . .
RootKey. , , . .
HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
HKEY_CURRENT_CONFIG
HKEY_DYN_DATA
Path. , .
RegEntry. , .
, GetRegistry ( ,
).
RootKey = "hkey_current_user"
Path = "Control Panel\Colors"
RegEntry = "ActiveTitle"
MsgBox GetRegistry(RootKey, Path, RegEntry), _
vbInformation, Path & "\RegEntry"

, RGB.


WriteRegistry .
, ;
. WriteRegistry
( ).
RootKey. , , . .
HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
HKEY_CURRENT_CONFIG
HKEY_DYN_DATA
Path. . , .
RegEntry. , .
, .
RegVal. , .

11. VBA

331

, ,
Excel. Excel.
Sub Auto_Open()
RootKey = "hkey_current_user"
Path = "software\microsoft\office\10.0\excel\LastStarted"
RegEntry = "DateTime"
RegVal = Now()
If WriteRegistry(RootKey, Path, RegEntry, RegVal) Then
msg = RegVal & " "
Else msg = " "
End If
MsgBox msg
End Sub

,
Excel.


,
GetSetting SaveSetting.
, . .
HKEY_CURRENT_USER\Software\VB and VBA Program Settings
,
, Excel.

332

III. Visual Basic for Applications

IV

...

12.
13.
14.
15.




UserForm

12



...
, , Windows. Windows . , . ,
Excel,
UserForm. .





, Excel
,
UserForm, Excel, .
.

...
.
:
;
;
;
;
;
.
.


, . , ,
,
. InputBox:
VBA, Excel.

InputBox VBA
.
InputBox([,][,_][,xpos][,ypos][,, ])

, ( ).
( ).
_ , ( ).
xpos, ypos
( ).
,
( ).

InputBox . ,
.
, , 1024 ( ). ,
,
.
. , .
, . 12.1, VBA
InputBox, ( ).
.

. 12.1.
VBA InputBox
Sub GetName()
Dim UserName As String
Dim FirstSpace As Integer
Do Until UserName <> ""
UserName = InputBox(" : ", _
" ?")
Loop
FirstSpace = InStr(UserName, " ")
If FirstSpace <> 0 Then
UserName = Left(UserName, FirstSpace - 1)
End If
MsgBox ", " & UserName
End Sub

336

IV.

-.

: InputBox Do Until. , .
(Cancel) , UserName
, .

( InStr). , Left ,
. , .
, InputBox . ,
InputBox,
, VBA Val.
InputBox Excel.

InputBox Excel
Excel InputBox ( VBA InputBox) :
;
, ;
.
InputBox .
object.InputBox(,,_,,,,,)

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

,
( ). . 12.1.

12.1. , Excel InputBox

0
1
2
4
8
16
64

()
( )

( #/)

12.

337

Excel InputBox . . ,
, ,
3 (.. 1+2 +). 8,
. ,
.
EraseRange, , InputBox.
, (. 12.2).
, .
InputBox 8 Range ( Set). (
Clear).
. (Cancel),
On Error .

Sub EraseRange()
Dim UserRange As Range
DefaultRange = Selection.Address
On Error GoTo Canceled
Set UserRange = Application.InputBox _
(Prompt:=" :", _
Title:=" ", _
Default:=DefaultRange, _
Type:=8)
UserRange.Clear
UserRange.Select
Canceled:
End Sub

-.

Excel InputBox Excel. GetRange , , Excel


(. 12.3).

. 12.2. InputBox

338

IV.

. 12.3. Excel InputBox

VBA MsgBox
VBA MsgBox . (
OK ). MsgBox
.
MsgBox.
MsgBox([,][,][,, ])

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

12.2. , MsgBox

vbOKonly
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
vbCritical
vbQuestion
vbExclamation
vbInformation
vbDefaultButton1
vbDefaultButton2
vbDefaultButton3
vbDefaultButton4
vbSystemModal

0
1
2
3
4
5
16
32
48
64
0
256
512
768
4098

OK
OK
,
,











,
( )

12.

339

MsgBox (
), .
MsgBox , ,
.
.
Sub MsgBoxDemo()
MsgBox " OK "
End Sub

,
MsgBox . (. 12.3), MsgBox
.
Sub GetAnswer()
Ans = MsgBox("?", vbYesNo)
Select Case Ans
Case vbYes
'
...[ Ans Yes]...
Case vbNo
'
...[ Ans No]...
End Select
End Sub

12.3. , MsgBox

vbOK
vbCancel
vbAbort
vbRetry
vbIgnore
vbYes
vbNo

1
2
3
4
5
6
7

OK

MsgBox. . ,
.
Sub GetAnswer2()
If MsgBox("?", vbYesNo) <> vbYes Then Exit Sub
'
...[ , ]...
End Sub

, .
(. 12.4).
Config.
Private Function ContinueProcedure() As Boolean
Dim Config As Integer
Dim Ans As Integer
Config = vbYesNo + vbQuestion + vbDefaultButton2
Ans = MsgBox(" . ?", Config)
If Ans = vbYes Then ContinueProcedure = True _
Else ContinueProcedure = False
End Function

340

IV.

ContinueProcedure . ,
ContinueProcedure ( ). (..
), . .
If Not ContinueProcedure Then Exit Sub

. 12.4.
MsgBox
,

,
vbCrLf ( vbNewLine) . .
Sub MultiLine()
Dim Msg As String
Msg = " " & vbCrLf
Msg = Msg & " " & vbCrLf
Msg = Msg & " "
MsgBox Msg
End Sub

vbTab. 208 (. 12.5).


vbTab. vbCrLf. MsgBox ,
1023 .
, .
Sub ShowRange()
Dim Msg As String
Dim r As Integer, c As Integer
Msg = ""
For r = 1 To 20
For c = 1 To 8
Msg = Msg & Cells(r, c) & vbTab
Next c
Msg = Msg & vbCrLf
Next r
MsgBox Msg
End Sub

. 12.5.

12.

341

15 VBA,
MsgBox.

Excel GetOpenFilename
,
InputBox, . GetOpenFilename
Application, ,
( ).

( ),
. ,
, .
, . ( ).
object.GetOpenFilename(_, _, , _,
_)

_ ,
( ).

_
, ( ).
( ).
, .
_ Macintosh.
_ .
, . .
_
. ,
, , . .
, .
" (*.*),*.*"

(*.*). , . *.*
.
Filt .
_
GetOpenFilename. (
). Filt, VBA.
.

342

IV.

Filt = " (*.txt),*.txt," & _


" (*.prn),*.prn," & _
" (*.csv),*.csv," & _
"ASCII (*.asc),*.asc," & _
" (*.*),*.*"

_ _ . ,
. _ ,
. .
.
.
Sub GetImportFileName()
Dim Filt As String
Dim FilterIndex As Integer
Dim FileName As Variant
Dim Title As String
'


Filt = " (*.txt),*.txt," & _
" (*.prn),*.prn," & _
" (*.csv),*.csv," & _
"ASCII (*.asc),*.asc," & _
" (*.*),*.*"

'

*.*
FilterIndex = 5

'


Title = " "

'


FileName = Application.GetOpenFilename _
(FileFilter:=Filt, _
FilterIndex:=FilterIndex, _
Title:=Title)

'


If FileName = False Then
MsgBox " "
Exit Sub
End If


MsgBox " " & FileName
End Sub

'

. 12.6 , .
. ,
, <Shift> <Ctrl>, . ,
FileName.
, .
.

12.

343

. 12.6. GetOpenFilename
Sub GetImportFileName2()
Dim Filt As String
Dim FilterIndex As Integer
Dim FileName As Variant
Dim Title As String
Dim i As Integer
Dim Msg As String
'

Filt = " (*.txt),*.txt," & _
" (*.prn),*.prn," & _
" (*.csv),*.csv," & _
"ASCII (*.asc),*.asc," & _
" (*.*),*.*"
'
*.*
FilterIndex = 5
'


Title = " "

'

Get the file name


FileName = Application.GetOpenFilename _
(FileFilter:=Filt, _
FilterIndex:=FilterIndex, _
Title:=Title, _
MultiSelect:=True)

'


If Not IsArray(FileName) Then
MsgBox " "
Exit Sub
End If


For i = LBound(FileName) To UBound(FileName)
Msg = Msg & FileName(i) & vbCrLf
Next i
MsgBox " :" & vbCrLf & Msg
End Sub

'

344

IV.

, FileName ( ). ,
FileName , .

Excel GetSaveAsFilename
GetOpenFilename.
( ) . , .
.
object.GetSaveAsFilename(_, _, _, ,
_)

_ (
).
_
( ).
_ ,
( ).
(
).
_ Macintosh.


, GetOpenFilename ( ).
,
Excel.
.
, Excel 97 .
, Excel 2002 .

Windows API

GetDirectory,
, . 12.7. , .
, . Excel 97
.
GetDirectory ,
. ,
.

- , .

12.

345

. 12.7.
Windows API

API,
. BROWSEINFO.
' 32- API
Declare Function SHGetPathFromIDList Lib "shell32.dll" _
Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal _
pszPath As String) As Long
Declare Function SHBrowseForFolder Lib "shell32.dll" _
Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) _
As Long
Public Type BROWSEINFO
hOwner As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type

API GetDirectory.
Function GetDirectory(Optional Msg) As String
Dim bInfo As BROWSEINFO
Dim path As String
Dim r As Long, x As Long, pos As Integer
'

=
bInfo.pidlRoot = 0&

'


If IsMissing(Msg) Then
bInfo.lpszTitle = " "
Else
bInfo.lpszTitle = Msg
End If

'


bInfo.ulFlags = &H1

'


x = SHBrowseForFolder(bInfo)

346

IV.


path = Space$(512)
r = SHGetPathFromIDList(ByVal x, ByVal path)
If r Then
pos = InStr(path, Chr$(0))
GetDirectory = Left(path, pos - 1)
Else
GetDirectory = ""
End If
End Function
'


GetDirectory VBA.
. OK, MsgBox
.
, .
Sub GetAFolder1()
'
Excel 97
Dim Msg As String
Dim UserFile As String
Msg = " "
UserFile = GetDirectory(Msg)
If UserFile = "" Then
MsgBox ""
Else
MsgBox UserFile
End If
End Sub

,
.

FileDialog
, , Excel 2002
, , FileDialog.

FileDialog Excel 2002. ,


Excel.

,
. ( ) MsgBox.
Sub GetAFolder2()
'
Excel 2002
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = " "
.Show
If .SelectedItems.Count = 0 Then
MsgBox ""
Else
MsgBox .SelectedItems(1)
End If
End With
End Sub

12.

347

FileDialog .
InitialFileName.
Excel.


Excel
VBA Excel. VBA
,
( ).
, VBA ,
A1:C3 OK.
( , ).
Application.Goto Reference:=Range("A1:C3")

Excel, .
.
Dialogs Application.
.

Dialogs
Dialogs Application 258 ,
Excel.
, ,
. , Excel
xlDialogFormulaGoto.
Show .
, (. 12.8).
Application.Dialogs(xlDialogFormulaGoto).Show

. 12.8.
VBA

,
, .
(
<F5>).
, , ,
. . Result True,

348

IV.

OK, False,
<Esc>.
Result = Application.Dialogs(xlDialogFormulaGoto).Show

, Range
.
, .
,
, Excel
VBA ,
. , , .
,
VBA .
. VBA, .
Application.Dialogs(xlDialogSelectSpecial).Show

. ,
. VBA
.
(. 12.9).
Application.Dialogs(xlDialogAlignment).Show

,
: xlDialogFormatNumber, xlDialogBorder,
xlDialogCellProtection, xlDialogPatterns xlDialogFontProperties.
.

. 12.9.

12.

349




Object Browser.
Dialogs Object Browser.
1. VBA, <F2>
Object Browser.
2. Object Browser Excel.
3. xlDialog .
4. .


. , xlDialogFontProperties,
, .



,
() . ,
(
xlDialogCellProtection) : locked hidden. ,
.
Application.Dialogs(xlDialogCellProtection).Show True, True

VBE. , Built-In Dialog Box Argument List. ,


.

( xlDialogFormulaGoTo)
: reference corner. reference
. Corner , ,
. ,
.
Application.Dialogs(xlDialogFormulaGoto). _
Show Range("Z100"), True

, Dialogs
, .

350

IV.


(
CommandBar). ,
.
.
CommandBar 2223.

.
Application.CommandBars("Worksheet Menu Bar"). _
Controls("").Controls("...").Execute

, . , ( ).
Dialogs, .


Excel CommandBar. , Excel. ,
Excel, FindControl,
Id .
22.

Dialogs.
, . . , .
Application.CommandBars("Worksheet Menu Bar"). _
Controls("").Controls("...").Execute

, Execute
, .
.
, (
).
Selection.Font.Bold = Not Selection.Font.Bold

12.

351

13


...
Excel
. Excel 97, . ,
.
Excel 97
Excel 5/95. ,
UserForm , ,
.
, .
.
.
VBA.
.
,
.
Toolbox.
.
Excel
.
Excel.
.

Excel

UserForm, Visual Basic.
, .
1. UserForm VBAProject .
2. , UserForm.
VBA ( UserForm).

3. UserForm.
4. .
5. .
UserForm (, ).

UserForm
UserForm, VBE (
<Alt+F11>, InsertUserForm).
UserForm , UserForm1, UserForm2 ..

, UserForm. Properties Name


( <F4>, Properties ).
. 13.1 Properties UserForm.


. UserForm .

. 13.1. Properties

354

IV.



UserForm,
Toolbox ( VBE , ). Toolbox ,
ViewToolbox. Toolbox . 13.2.

. 13.2.
Toolbox

Toolbox,
.
( ).
, ,
.
,
. , CommandButton UserForm, CommandButton1.
CommandButton, CommandButton2.

,
VBA-. (, ProductListBox),
( ListBox1). , Properties VBE.
.

,
Toolbox.

UserForm ActiveX.
Toolbox .

CheckBox
CheckBox
: , , ..
CheckBox , True, False.

13.

355

ComboBox
ComboBox ListBox.
, ComboBox , . ,
,
ComboBox.

CommandButton

CommandButton. CommandButton, OK .

Frame
Frame
. , .
Frame ,
OptionButton.

Image
Image , .
, Image
.
. , .

,
.
,
.

Label
Label .

ListBox
ListBox ,
( ). ListBox
. , , . .
, ListBox VBA.

MultiPage
MultiPage
, .
MultiPage .
,
New Page .

356

IV.

OptionButton
OptionButton
. , . OptionButton , OptionButton
.

OptionButton,
GroupName.
OptionButton .
OptionButton Frame,
.

RefEdit
RefEdit ,
.

ScrollBar
ScrollBar
SpinButton. ,
ScrollBar .
ScrollBar
.

SpinButton
SpinButton
. , . SpinButton TextBox Label,
SpinButton.

TabStrip
TabStrip MultiPage,
. TabStrip, MultiPage,
. ,
MultiPage .

TextBox
TextBox
.

ToggleButton
ToggleButton : .
. True
() False ().
, OptionButton
CheckBox .

13.

357



, ,
, .
.

.
<Shift> .
.

UserForm , .
, .
, , VBE ToolsOptions.
Options General
Form Grid Settings.
Format VBE , . ,
. , . . 13.3
OptionButton
.



.
( Excel, VBE). , . , , .
, , , LinkedCell.
, .
, .
,
.
,
.
. ,
Excel 5 Excel 95.
. ActiveX.
, . Excel 97
, Excel 5 Excel 95.
,
.
, ActiveX.

358

IV.


Excel .
,
. ActiveX, .

, .
,
(, CommandButton1_Click) . .
Excel , .
,
( ).
,
, -.


, , . , .


, . .
.
Properties.
,
. VBA.

13.

359

. 13.3. FormatAlign

Properties
VBE Properties ( UserForm).
,
Properties (. 13.4).

. 13.4.
(OptionButton)
Properties

360

IV.

Properties . Alphabetic
.
Categorized , .
, .

,
. , . Properties , .
, .
, TextAlign :
1 - fmTextAlignLeft, 2 - fmTextAlignCenter 3 - fmTextAlignRight.
(, Font Picture)
.
.
Picture Image ,
. . , Picture Image
<Ctrl+V> .

, Properties , .
UserForm , . ,
,
. , Font UserForm, , ,
.


,
, . ,
Name ,
(Height, Width, Left Right).
VBA,
. ,
OptionButton, ,
OptionButton1. .
OptionButton1.Value = True

OptionButton
(, obLandscape), .
obLandscape.Value = True

, , . ob , OptionButton.

13.

361

.
, OptionButton
.
OptionButton Left Properties.
Left.


.
Properties <F1>. . 13.5 , .

. 13.5.


. <Tab> <Shift+Tab>
. ,
,
: .

()
,
<Tab>
<Shift+Tab>. , ,
. TextBox, . OptionButton, .
, ,
.
, ViewTab Order.
, Tab
Order . , Excel
Tab Order, . 13.6. Tab Order , -

362

IV.

. , Move Up
Move Down.
( <Shift> <Ctrl>).

. 13.6.
Tab Order
()

,
Properties.
TabIndex, 0.
TabIndex TabIndex . . , TabIndex , . ,
TabStop False.

, Frame MultiPage, .
. OptionButton
Frame, ViewTab Order.


. ,
<Alt> . Accelerator
Properties .

Accelerator, Caption. Label.


Label, TextBox.



UserForm. , VBA.
RunRun Sub/UserForm.
<F5>.
Run Sub/UserForm Standard.
. , .

13.

363



VBA,
.


VBA,
, Show UserForm.
UserForm , VBA. UserForm UserForm1, .
Sub ShowDialog()
UserForm1.Show
End Sub

VBA,
UserForm.
,
.
CommandButton, .
Unload, Hide UserForm.
.
.
Excel, . ( Excel, ).
.
UserForm1.Show 0

Excel 2000 .

, Add UserForms,
Show .
MyForm, .
MyForm = "UserForm"
UserForms.Add(MyForm).Show


VBA.
, VBA Load. . , Show,
. UserForm1, .
Load UserForm1

364

IV.

, , Show. , Load .


UserForm1, Unload.
Unload UserForm1

.
Unload Me

Me .
VBA Unload ,
UserForm . , UserForm
CommandButton, OK.
.
UserForm .

, , Unload, .
UserForm , , , . ,
, ,
. , ,
( UserForm),
Public,
VBA. , .

, ( ).
QueryClose UserForm, Terminate UserForm.

UserForm Hide.
, , . ,
.
UserForm1.Hide

.
Me.Hide

- ,
, Hide , DoEvents. ,
UserForm , CommandButton1.
.
Private Sub CommandButton1_Click()
Me.Hide
DoEvents
For r = 1 To 10000

13.

365

Cells(r, 1) = r
Next r
Unload Me
End Sub

15 , ,
:
, .


,
ListBox,
CommandButton .. , ,
. ,
CommandButton Click CommandButton.
,
. .

UserForm. , VBA.

VBA , (.. ). ,
ListBox ,
Label .
.



, , .
VBA
.
, : . TextBox, ,
OptionButton (, ). , , .


. 13.7 .
, . .
1. <Alt+F11> VBE.
2. Project , InsertUserForm,
.

366

IV.

3. Caption UserForm
UserForm1. Properties, Caption ( Properties
, <F4>).

. 13.7.

4. Label ,
.

Accelerator

Caption

TabIndex

5. TextBox
.

Name

TextName

TabIndex

6. Frame .

Caption

TabIndex

7. OptionButton
Frame , .

Accelerator

Caption

Name

OptionMale

TabIndex

13.

367

8. Frame
OptionButton , .

Accelerator

Caption

Name

OptionFemale

TabIndex

9. Frame
OptionButton .

Accelerator

Caption

Name

OptionUnknown

TabIndex

Value

True

10. CommandButton Frame .

Caption

OK

Default

True

Name

OKButton

TabIndex

11. CommandButton Frame , .

Caption

Default

True

Name

CancelButton

TabIndex

368

,
, .
, <Ctrl>
, .
.

IV.



CommandButton. ,
UserForm. .
1. Excel ( <Alt+F11>).
2.
. Excel .
Toolbox VBE.
3. ,
. ,
.
4. .
CommandButtonEdit .
, .
5. .
6. VBE.
CommandButton
(), .
7. CommandButton1_Click (. 13.8).
Show UserForm1 UserForm.

. 13.8. CommandButton1_
Click
,

, .

. ,
, . ,
Excel , ,
.
, .

Excel ,
(. 13.9).

13.

369

,
OK. : , UserForm .

. 13.9. Click CommandButton


,
, . .
1. <Alt+F11>. VBE.
2. , ,
, . , UserForm, CancelButton_Click. , , , .
3. , ( Click
CancelButton).
Private Sub CancelButton_Click()
Unload UserForm1
End Sub

4. .
UserForm .
5. <Shift+F7>,
UserForm1 ( View Object
Project Explorer).

370

IV.

6. OK ( Click OKButton).
Private Sub OKButton_Click()
'

Sheets("1").Activate
'
'
'


NextRow = _
Application.WorksheetFunction.CountA(Range("A:A")) + 1

Cells(NextRow, 1) = TextName.Text

If OptionMale Then Cells(NextRow, 2) = ""
If OptionFemale Then Cells(NextRow, 2) = ""
If OptionUnknown Then Cells(NextRow, 2) = ""


TextName.Text = ""
OptionUnknown = True
TextName.SetFocus
End Sub
'

7. Excel , . .
8. .
. 13.10 .
OKButton_Click : ,
1. Excel (COUNT) .
TextBox A. If
OptionButton, B (, , ). ,
( ). , OK
. ( )
.

. 13.10.

13.

371


. , , ( , ). OKButton_Click
. , ( ) TextBox. TextBox , , . , . Exit Sub
.
'


If TextName.Text = "" Then
MsgBox " "
TextName.SetFocus
Exit Sub
End If

!

( ). ,
.
.
.

UserForm

UserForm ( UserForm)
, . Excel.
, CommandButton
Click CommandButton. ,
.
. ,
SpinButton SpinUp Change.
,
Show, Excel Initialize Activate UserForm.
, Excel Sheet (), Chart ()
ThisWorkbook (). 18.


, , .
1. .

372

IV.

2. ,
UserForm. VBE , .
3.
,
(. 13.11).

. 13.11.
Option Button

4. , VBE .

, . ,
.
,
. , ,
. !
, ,
.

UserForm

UserForm.
Initialize UserForm.
, UserForm .
Activate UserForm.
Deactivate
UserForm.

UserForm.

QueryClose UserForm.
Terminate UserForm.

13.

373

. Show Initialize Activate


( ). Load Initialize. Unload, QueryClose Terminate ( ). Hide
.
- ,
. UserForm , , ,
.

SpinButton

,
, SpinButton.

- , , SpinButton UserForm
( ).

SpinButton UserForm. , .

. 13.1 , SpinButton.

13.1. SpinButton

AfterUpdate

,

,


Value
, SpinButton

UserForm
;


, ,

,
,
,

BeforeDragOver
BeforeDropOrPaste
BeforeUpdate
Change
Enter

Error

Exit

KeyDown
KeyPress
KeyUp
SpinDown

, ( )
SpinButton

SpinUp

, ( )
SpinButton

374

IV.

SpinButton (
) .


SpinButton,
.
1. Enter ( , ).
2. Change.
3. SpinUp.


<Tab> ,
SpinButton.
.
, .
1. Enter.
2. KeyDown.
3. Change.
4. SpinUp.

, ?
SpinButton VBA, . , Value SpinButton 0, Change. , Value .
SpinButton1.Value = 0

, ,
EnableEvents Application False. , ,
Excel: Workbook, Worksheet Chart.


SpinButton TextBox
SpinButton Value,
. , SpinButton ,
.
SpinButton
TextBox,
SpinButton ,
TextBox. , SpinButton
, TextBox.
. 13.12 . Min SpinButton
1, Max 100. ,
SpinButton 1 100.

13.

375

. 13.12. SpinButton,
TextBox

-.

, SpinButton TextBox,
. ,
Value SpinButton
Text TextBox.

Change SpinButton. , , SpinButton
, .
Private Sub SpinButton1_Change()
TextBox1.Text = SpinButton1.Value
End Sub

Value
SpinButton Text TextBox.
, (SpinButton1 TextBox1).
TextBox,
Change, .
Private Sub TextBox1_Change()
NewVal = Val(TextBox1.Text)
If NewVal >= SpinButton1.Min And _
NewVal <= SpinButton1.Max Then _
SpinButton1.Value = NewVal
End Sub

VBA Val,
TextBox (
TextBox , Val 0). , .
, Value SpinButton
, TextBox.
, OK ( OKButton) SpinButton . Click CommandButton .
Private Sub OKButton_Click()
'

If CStr(SpinButton1.Value) = TextBox1.Text Then
ActiveCell = SpinButton1.Value
Unload Me
Else
MsgBox " .", vbCritical
TextBox1.SetFocus
TextBox1.SelStart = 0
TextBox1.SelLength = Len(TextBox1.Text)
End If
End Sub

376

IV.

: ,
TextBox, SpinButton.
. ,
TextBox 3r,
SpinButton , ,
, . ,
Value SpinButton
CStr. , , .
SpinButton TextBox,
. TextBox ,
( SelStart SelLength). , .

Tag
UserForm Tag.
. Tag
, .
, TextBox .
. . Tag ,
. Tag , , Required.
Tag.
, , , TextBox UserForm1 ,
.
Function EmptyCount()
Dim ctl As Control
EmptyCount= 0
For Each ctl In UserForm1.Controls
If TypeName(ctl) = "TextBox" Then
If ctl.Tag = "Required" Then
If ctl.Text = "" Then
EmptyCount = EmptyCount + 1
End If
End If
End If
Next ctl
End Function

Tag.

13.

377



, UserForm, VBA
UserForm. , VBA .

, UserForm. , VBA.
, UserForm1.
Sub GetData()
UserForm1.Show
End Sub

, UserForm1
(TextBox1). .
.
Sub GetData()
UserForm1.TextBox1.Value = ""
UserForm1.Show
End Sub


Initialize UserForm.
UserForm_Initialize, .
Private Sub UserForm_Initialize()
TextBox1.Value = ""
End Sub

,
UserForm.
:
Auto List Member, . UserForm, Me.
, UserForm ,
( ) .


.
,
UserForm1.
MsgBox UserForm1.Controls.Count
. , CommandButton.
TypeName.
For Each Controls. CommandButton,
UserForm1.

378

IV.

Sub CountButtons()
Dim cbCount As Integer
Dim ctl as Control
cbCount = 0
For Each ctl In UserForm1.Controls
If TypeName(ctl) = "CommandButton" Then _
cbCount = cbCount + 1
Next ctl
MsgBox cbCount
End Sub

Toolbox
UserForm VBE, Toolbox
, .
Toolbox.


, Customize Control .
,
.


Toolbox . New Page, Toolbox.
, , . Rename .



. , ,
CommandButton, OK. : Width (), Height (), Caption
(), Default ( ) Name (). CommandButton Toolbox.
. , .
Toolbox,
. , CommandButton, OK .
, .
Toolbox.
Toolbox .
,
. , Frame
OptionButton (-

13.

379

).
Frame Toolbox,
Frame.

Toolbox. , Toolbox Excel.


Toolbox, Export Page.
- .PAG
.
Toolbox.
Import Page. .PAG.
Toolbox . 13.13.

. 13.13. Toolbox,

ActiveX

ActiveX, Microsoft .
ActiveX , Toolbox Additional
Controls. , . 13.14.
Additional Controls ActiveX,
. , . OK
.

. 13.14. Additional
Controls
ActiveX

380

IV.

ActiveX, , Excel. . , .
, .

Excel
Windows .
Excel Excel
, .

Excel. , , . Excel, . Excel
.
, Excel,
VBA. ,
Excel . .


,
. ,
CommandButton,
OK . , .
,
. :
.
,
, .
, . FileExport
File ( <Ctrl+E>).
.
FileImport File, .



, , .
,
.
?
?

13.

381

? , MultiPage.
?
?
?
VBA ,
OK ?
?
?

? , , VGA (
).
( )?
ScrollBar SpinButton
?
ListBox?

382

IV.

14


...
,
UserForm.





, ListBox
MultiPage

. ,
, -.

15

UserForm
.
: CommandButton ListBox.

CommandButton
. 14.1 UserForm,
CommandButton . , , , . CommandButton . ,
CommandButton1.
Private Sub CommandButton1_Click()
Call Macro1
Unload Me
End Sub

Macro1
UserForm. .

. 14.1.
CommandButton,

ListBox
. 14.2 , ListBox. Initialize. , , AddItem
ListBox.
Private Sub UserForm_Initialize()
With ListBox1
.AddItem "Macro1"
.AddItem "Macro2"
.AddItem "Macro3"
.AddItem "Macro4"
.AddItem "Macro5"
.AddItem "Macro6"
End With
End Sub

. 14.2.
ListBox

,
.
Private Sub ExecuteButton_Click()
Select Case ListBox1.ListIndex
Case -1
MsgBox " "
Exit Sub
Case 0: Call Macro1
Case 1: Call Macro2
Case 2: Call Macro3
Case 3: Call Macro4
Case 4: Call Macro5
Case 5: Call Macro6
End Select
Unload Me
End Sub

ListIndex
ListBox, , ( ListIndex
-1, ). .

384

IV.

Excel . 2223.


Excel
. ,
. , .
.
RefEdit. ,
Excel, .
, ,
(
Excel).

, RefEdit . ,
<Shift+> .

. 14.3 RefEdit.
. OptionButton.

. 14.3. RefEdit

, RefEdit.
RefEdit , . Range.
.
Set UserRange = Range(RefEdit1.Text)

RefEdit
. UserForm_
Initialize .
RefEdit1.Text = ActiveWindow.RangeSelection.Address

RefEdit .

.

14.

385

, .
, ,
.
. , , , RefEdit , .
On Error Resume Next
Set UserRange = Range(RefEdit1.Text)
If Err <> 0 Then
MsgBox " "
RefEdit1.SetFocus
Exit Sub
End If
On Error GoTo 0

, RefEdit.
.
, ,
.
2!$A$1:$C:4

,
.
.

Set OneCell = Range(RefEdit1.Text).Range("A1")

12, VBA InputBox,


.



. .
, Excel, .
Excel . ,
.
.
1.

2.

VBE UserForm .
, UserForm UserForm1.

3.


UserForm1. ,
Image, .
. 14.4 .

386

IV.

. 14.4.

4.

ThisWorkbook
().
Private Sub Workbook_Open()
UserForm1.Show
End Sub

5.

UserForm1
( ).
Private Sub UserForm_Activate()
Application.OnTime Now + _
TimeValue("00:00:05"), "KillTheForm"
End Sub

6.

VBA.
Private Sub KillTheForm()
Unload UserForm1
End Sub

Workbook_Open.
UserForm.
Activate, UserForm_Activate.
OnTime Application KillTheForm . Activate. KillTheForm
UserForm .
7.
CommandButton CancelButton, Cancel
True UserForm.
Private Sub CancelButton_Click()
KillTheForm
End Sub

, ,
.
<Esc>. ,
.

14.

387

, ,
. ,
, ,
, .
VBA- , ,
. Workbook_Open.
Private Sub Workbook_Open()
UserForm1.Show vbModeles
'
End Sub



,
( ) UserForm
. , . , , UserForm
CommandButton.
, ,
, .
QueryClose.
,
UserForm, (.. QueryClose).
Private Sub UserForm_QueryClose _
(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
MsgBox " OK "
Cancel = True
End If
End Sub

UserForm_QueryClose . CloseMode
,
QueryClose. CloseMode vbFormControlMenu
( ), ,
. ; Cancel True, .

, <Ctrl+Break> . <Ctrl+Break>
UserForm , . ,
UserForm.
Application.EnableCancelKey = xlDisabled

, , . ,
.

388

IV.


, . , Excel ( ) , .
. Width Height UserForm.
. 14.5 , . . 14.6
. ,
.

, . UserForm_Initialize
( ).

. 14.5.

. 14.6.

. , .
, .
Private Sub OptionsButton_Click()
If OptionsButton.Caption = " >>" Then
Me.Height = 164
OptionsButton.Caption = "<< "
Else
Me.Height = 128
OptionsButton.Caption = " >>"
End If
End Sub

Caption CommandButton
Height UserForm Caption.

,
, ,
, .
<Alt+L> ( ), . ,
, , .

14.

389




.
, .

Excel 2000, UserForm . , Excel. Show


UserForm
. , .
UserForm1.Show vbModeless

, , ,
ScrollBar . . 14.7
( 100% 400%) ScrollBar, . ScrollBar
.

. 14.7. ScrollBar

.
Private Sub UserForm_Initialize()
LabelZoom.Caption = ActiveWindow.Zoom
'

With ScrollBarZoom
.Min = 10
.Max = 400
.SmallChange = 1
.LargeChange = 10
.Value = ActiveWindow.Zoom
End With

390

IV.

'


With ScrollBarColumns
.Min = 1
.Max = 256
.Value = ActiveWindow.ScrollColumn
.LargeChange = 25
.SmallChange = 1
End With


With ScrollBarRows
.Min = 1
.Max = ActiveSheet.Rows.Count
.Value = ActiveWindow.ScrollRow
.LargeChange = 25
.SmallChange = 1
End With
End Sub
'


ScrollBar. , .
ScrollBarZoom
ScrollBarZoom_Change ( ).
Zoom ActiveWindow Value
ScrollBar. , ,
.
Private Sub ScrollBarZoom_Change()
With ActiveWindow
.Zoom = ScrollBarZoom.Value
LabelZoom = .Zoom & "%"
End With
End Sub

. ScrollRow ScrollColumns ActiveWindow


Value ScrollBar.
Private Sub ScrollBarColumns_Change()
ActiveWindow.ScrollColumn = ScrollBarColumns.Value
End Sub
Private Sub ScrollBarRows_Change()
ActiveWindow.ScrollRow = ScrollBarRows.Value
End Sub

Change , Scroll. ,
.

ListBox
ListBox ,
. ,
ListBox.

, ,
ComboBox.

14.

391

ListBox
, ListBox.
.
ListBox
( RowSource) VBA
( AddItem).
ListBox
.
MultiSelect.
ListBox
, ListBox
ControlSource.
ListBox
( ListIndex -1).
,
.
ListBox ( ColumnCount) (
ColumnHeads).
ListBox, , UserForm .
ListBox , , , . ListStyle.


ListBox .

ListBox
, ListBox, ListBox . ListBox
, . , VBA
.
.
UserForm UserForm1.
UserForm1 ListBox,
ListBox1.
1, A1:A12
, ListBox.

392

IV.

LISTBOX

ListBox
, . RowSource ,
ListBox. . 14.8 Properties
ListBox. RowSource 1!A1:A12.
UserForm , ListBox
. ListBox , , RowSource.

, RowSource .
ListBox
. , . :
[1.xls]1!A1:A12.

LISTBOX

ListBox , .
RowSource, , .
, AddItem
ListBox.

. 14.8. RowSource

14.

393

RowSource ,
Properties. , RowSource ListBox ,
UserForm.
Categories Budget.
UserForm1.ListBox1.RowSource = "Budget!Categories"
UserForm1.Show

ListBox ,
VBA ListBox
.
ListBox AddItem.
Sub ShowUserForm2()
'
ListBox
With UserForm2.ListBox1
.RowSource=""
.AddItem ""
.AddItem ""
.AddItem ""
.AddItem ""
.AddItem ""
.AddItem ""
.AddItem ""
.AddItem ""
.AddItem ""
.AddItem ""
.AddItem ""
.AddItem ""
End With
UserForm2.Show
End Sub

RowSource
(, , , Properties
RowSource ListBox ). ListBox RowSource,
("Permission denied").

, AddItem
ListBox, . ListBox A1:A12 1.
For Row = 1 To 12
UserForm1.ListBox1.AddItem Sheets("1").Cells(Row, 1)
Next Row

, . ,
dData, 50 .
50 ListBox, ListBox1.
ListBox1.List = dData

394

IV.

LISTBOX

ListBox () . , , .
(. 14.9). ListBox , .

. 14.9. Collection
ListBox

Collection.
Collection .
object.Add item, key, before, after

key ( ) , .
, ,
. ,
.
.
Collection NoDupes. , , Data, , .
, NoDupes
. ,
( ) key. On Error Resume Next , VBA , .
, , .
NoDupes ListBox. UserForm
, .

14.

395

Sub RemoveDuplicates1()
Dim AllCells As Range, Cell As Range
Dim NoDupes As New Collection
On Error Resume Next
For Each Cell In Range("Data")
NoDupes.Add Cell.Value, CStr(Cell.Value)
Next Cell
On Error GoTo 0
'

ListBox
For Each Item In NoDupes
UserForm1.ListBox1.AddItem Item
Next Item

'


UserForm1.Label1.Caption = _
" : " & NoDupes.Count

UserForm
UserForm1.Show
End Sub


'


-.


UserForm ListBox, . : , .

ListBox
MultiSelect 0.

, ,
Value ListBox. , ,
ListBox1 .
MsgBox ListBox1.Value

, .
( ), ListIndex
ListBox. , ListBox.
MsgBox " #" & ListBox1.ListIndex

, ListIndex -1.

396

ListBox 0, 1.
, ListIndex 0.

ListCount-1.

IV.


, MultiSelect ListBox 0; ,
ListBox.
ListBox (..
MultiSelect 1 2),
ListIndex Value ListBox
. Selected, , 0. , True,
ListBox.

MsgBox ListBox1.Selected(0)

- ,
ListBox. , .

, .
ListBox. , Msg.
.
Private Sub OKButton_Click()
Msg = ""
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then _
Msg = Msg & ListBox1.List(i) & vbCrLf
Next i
MsgBox " : " & vbCrLf & Msg
Unload Me
End Sub

. 14.10
ListBox.

. 14.10. ,
ListBox

14.

397

ListBox
ListBox,
,
OptionButton .
. 14.11 UserForm.
ListBox . , Click OptionButton, RowSource ListBox . .
Private Sub obMonths_Click()
ListBox1.RowSource = "1!"
End Sub

OptionButton, obMonths, RowSource ListBox,


1.

ListBox
. .
, (
, ).
. 14.12 ListBox.
,
ListBox, ListBox. . . ,
, , , .

. 14.11. ListBox , OptionButton


398

IV.

. 14.12.

. ,
.
Private Sub AddButton_Click()
If ListBox1.ListIndex = -1 Then Exit Sub
If Not cbDuplicates Then
'

For i = 0 To ListBox2.ListCount - 1
If ListBox1.Value = ListBox2.List(i) Then
Beep
Exit Sub
End If
Next i
End If
ListBox2.AddItem ListBox1.Value
End Sub

.
Private Sub DeleteButton_Click()
If ListBox2.ListIndex = -1 Then Exit Sub
ListBox2.RemoveItem ListBox2.ListIndex
End Sub

,
. ListIndex ListBox -1,
, . .

ListBox
,
ListBox. VB
UserForm.
. 14.13 ,
ListBox CommandButton.
ListBox.
.

. 14.13.


ListBox

14.

399

CommandButton .
Private Sub MoveUpButton_Click()
If ListBox1.ListIndex <= 0 Then Exit Sub
NumItems = ListBox1.ListCount
Dim TempList()
ReDim TempList(0 To NumItems - 1)
'

For i = 0 To NumItems - 1
TempList(i) = ListBox1.List(i)
Next i
'

ItemNum = ListBox1.ListIndex
'

TempItem = TempList(ItemNum)
TempList(ItemNum) = TempList(ItemNum - 1)
TempList(ItemNum - 1) = TempItem
ListBox1.List = TempList
'

ListBox1.ListIndex = ItemNum - 1
End Sub
Private Sub MoveDownButton_Click()
If ListBox1.ListIndex = ListBox1.ListCount - 1 Then Exit Sub
NumItems = ListBox1.ListCount
Dim TempList()
ReDim TempList(0 To NumItems - 1)
'

For i = 0 To NumItems - 1
TempList(i) = ListBox1.List(i)
Next i
'

ItemNum = ListBox1.ListIndex
'

TempItem = TempList(ItemNum)
TempList(ItemNum) = TempList(ItemNum + 1)
TempList(ItemNum + 1) = TempItem
ListBox1.List = TempList
'

ListBox1.ListIndex = ItemNum + 1
End Sub

, , , ,
. , ,
.
DblClick
CommandButton. ,
Click, .
Private Sub MoveUpButton_DblClick _
(ByVal Cancel As MSForms.ReturnBoolean)
Call MoveUpButton_Click
End Sub
Private Sub MoveDownButton_DblClick _
(ByVal Cancel As MSForms.ReturnBoolean)
Call MoveDownButton_Click
End Sub

400

IV.

ListBox,

, ListBox , . ListBox,
.
. 14.14 ListBox ,
.

. 14.14. ListBox
,

ListBox ,
, , .
1. , ColumnCount ListBox ,
.
2. , RowSource
ListBox.
3. ,
. 14.14, ColumnHeads True.
,
RowSource. VBA ,
, RowSource.
4. , ColumnWidths , (1/72 ) .
, ColumnWidths
ListBox.
100;40;30

5. BoundColumn.
,
Value ListBox.

14.

401

ListBox
, ,
List ListBox.
1, 2 (. 14.15).
, ColumnCount 2.
Private Sub UserForm_Initialize()
'
ListBox
Dim Data(1 To 12, 1 To 2)
For i = 1 To 12
Data(i, 1) = Format(DateSerial(2001, i, 1), "mmmm")
Next i
For i = 1 To 12
Data(i, 2) = Day(DateSerial(2001, i + 1, 1) - 1)
Next i
ListBox1.ColumnCount = 2
ListBox1.List = Data
End Sub

. 14.15.
ListBox

ColumnHeads,
VBA.

ListBox

, , . ListBox,
(. 14.16).
ListBox.
, ,
. OK ,
ListBox. ,
.
<Ctrl>. ,
, , .
, MultiSelect
ListBox 1 - fmMultiSelectMulti.
, ListStyle
ListBox 1 - fmListStyleOption.

402

IV.

. 14.16. ListBox

UserForm Initialize.
rng, . RowSource ColumnCount
ListBox, ColumnWidths,
ListBox
.
Private Sub UserForm_Initialize()
ColCnt = ActiveSheet.UsedRange.Columns.Count
Set rng = ActiveSheet.UsedRange
With ListBox1
.ColumnCount = ColCnt
.RowSource = rng.Address
cw = ""
For c = 1 To .ColumnCount
cw = cw & rng.Columns(c).Width & ";"
Next c
.ColumnWidths = cw
.ListIndex = 0
End With
End Sub

( SelectAllButton SelectNoneButton)
, .
Private Sub SelectAllButton_Click()
For r = 0 To ListBox1.ListCount - 1
ListBox1.Selected(r) = True
Next r
End Sub
Private Sub SelectNoneButton_Click()
For r = 0 To ListBox1.ListCount - 1
ListBox1.Selected(r) = False
Next r
End Sub

OKButton_Click.
Range, RowRange. , ListBox.
, Selected
ListBox. , Union
RowRange.

14.

403

Private Sub OKButton_Click()


Dim RowRange As Range
RowCnt = 0
For r = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(r) Then
RowCnt = RowCnt + 1
If RowCnt = 1 Then
Set RowRange = ActiveSheet.Rows(r + 1)
Else
Set RowRange = _
Union(RowRange, ActiveSheet.Rows(r + 1))
End If
End If
Next r
If Not RowRange Is Nothing Then RowRange.Select
Unload Me
End Sub

ListBox

, , , .
ListBox
. .
.
( , Excel 5/95).
.
.
. 14.17 .

. 14.17.

UserForm_Initialize ( ) ,
. ListBox.
Private Sub UserForm_Initialize()
Dim SheetData() As String
Set OriginalSheet = ActiveSheet
ShtCnt = ActiveWorkbook.Sheets.Count
ReDim SheetData(1 To ShtCnt, 1 To 4)
ShtNum = 1
For Each Sht In ActiveWorkbook.Sheets
If Sht.Name = ActiveSheet.Name Then _
ListPos = ShtNum - 1
SheetData(ShtNum, 1) = Sht.Name

404

IV.

Select Case TypeName(Sht)


Case "Worksheet"
SheetData(ShtNum, 2) = ""
SheetData(ShtNum, 3) = _
Application.CountA(Sht.Cells)
Case "Chart"
SheetData(ShtNum, 2) = ""
SheetData(ShtNum, 3) = "N/A"
Case "DialogSheet"
SheetData(ShtNum, 2) = ""
SheetData(ShtNum, 3) = "N/A"
End Select
If Sht.Visible Then
SheetData(ShtNum, 4) = ""
Else
SheetData(ShtNum, 4) = ""
End If
ShtNum = ShtNum + 1
Next Sht
With ListBox1
.ColumnWidths = "100 pt;50 pt;40 pt;50 pt"
.List = SheetData
.ListIndex = ListPos
End With
End Sub

ListBox1_Click.
Private Sub ListBox1_Click()
If cbPreview Then _
Sheets(ListBox1.Value).Activate
End Sub

CheckBox ( cbPreview)
, ListBox.
OK ( OKButton)
OKButton_Click, .
Private Sub OKButton_Click()
Dim UserSheet As Object
Set UserSheet = Sheets(ListBox1.Value)
If UserSheet.Visible Then
UserSheet.Activate
Else
If MsgBox(" ?", _
vbQuestion + vbYesNoCancel) = vbYes Then
UserSheet.Visible = True
UserSheet.Activate
Else
OriginalSheet.Activate
End If
End If
Unload Me
End Sub

OKButton_Click ,
. , . ,
, .
, . (
OriginalSheet).

14.

405

ListBox , OK. ListBox1_DblClick, , OKButton_Click.


Private Sub ListBox1_DblClick(ByVal Cancel As _
MSForms.ReturnBoolean)
Call OKButton_Click
End Sub

MultiPage
MultiPage UserForm,
. .
MultiPage ,
.
TabOrientation, .

Toolbox , TabStrip.
MultiPage ,
TabStrip.

MultiPage . ,
MultiPage.
( ), , Value MultiPage. 0
. 1 ..
MultiPage .
,
New Page .
MultiPage ,
. Properties , .
MultiPage,
.
, .
, <Tab>
. MultiPage Properties.
MultiPage ,
MultiRow True, .
, . Style 1. Style 2,
MultiPage , .
TabOrientation
MultiPage.

406

IV.

. TransitionEffect. ,
, .
TransitionPeriod .

, MultiPage.

14.

407

15


UserForm
...
, 13.
.
.
, MsgBox VBA.
UserForm.

.
.
UserForm.
UserForm ( ).
UserForm.
.
;
.


Excel . ,
, , .
Excel 97 . . .
, UserForm
( ).
, UserForm.
UserForm MultiPage , .

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


, , Excel. , , .
.
Excel, .
Application.StatusBar = ", ..."
. ,
Pct, , ,
.
Application.StatusBar = "... " & Pct & "% "
, .
.
Application.StatusBar = False

, ,
. ,
.

UserForm
, .

-.

USERFORM
UserForm,
.
1. UserForm
Caption .
2. Frame FrameProgress.

410

IV.

3. Frame Label LabelProgress. ( BackColor). .


4. Label ,
.
5.
UserForm , . 15.1.

: , SpecialEffect
Frame, . 15.1.

. 15.1.
UserForm


, UserForm.
Initialize. ,
, . , Activate , UserForm
, .
UserForm.
Main, UserForm
. Main, VBA, , ,
.
Private Sub UserForm_Activate()
Call Main
End Sub

Main. . Label
Frame.
.
, .
Sub Main()
'

Cells.Clear
Counter = 1
RowMax = 200
ColMax = 25
For r = 1 To RowMax
For c = 1 To ColMax
Cells(r, c) = Int(Rnd * 1000)
Counter = Counter + 1

15. UserForm

411

Next c
PctDone = Counter / (RowMax * ColMax)
Call UpdateProgress(PctDone)
Next r
Unload UserForm1
End Sub

Main (, ).
UpdateProgress. :
0 100, .
Sub UpdateProgress(Pct)
With UserForm1
.FrameProgress.Caption = Format(Pct, "0%")
.LabelProgress.Width = Pct * (.FrameProgress.Width - 10)
.Repaint
End With
End Sub


, ,
UserForm. VBA.
Sub ShowDialog()
UserForm1.LabelProgress.Width = 0
UserForm1.Show
End Sub


ShowDialog Label
0. Show UserForm1,
UserForm ( ). UserForm , Activate, Main. Main Label.
, Repaint UserForm.
Label
.
UserForm .
, ,
. PctDone.


MultiPage
UserForm.
UserForm,
, , . , .
.
UserForm (
MultiPage) .
.

412

IV.

- , .

USERFORM
, UserForm .
MultiPage.
MultiPage .
,
. ,
VBA Value MultiPage .

, .
MultiPage
UserForm. UserForm
MultiPage.
MultiPage
, , . 15.2.
, .
1. Frame FrameProgress.
2. Label Frame LabelProgress. Label
.
3. Label,
( ).

. 15.2. MultiPage,

4. MultiPage ( , ) Style 2 - fmTabStyleNone ( ). MultiPage


Properties.
, MultiPage,
.

15. UserForm

413

UPDATEPROGRESS
UserForm.
Sub UpdateProgress(Pct)
With UserForm1
.FrameProgress.Caption = Format(Pct, "0%")
.LabelProgress.Width = Pct * (.FrameProgress.Width - 10)
.Repaint
End With
End Sub

.
.


,
OK.
Click OKButton_Click.
.
MultiPage1.Value = 1


MultiPage ( , ).
, .
PctDone. ,
. ,
.
Call UpdateProgress(PctDone)


, ,
UserForm.
MultiPage .


MultiPage

, , , . , MultiPage.
UserForm.
, , ,
UserForm .
, UserForm , .

414

- ,
.

IV.

. 15.3 UserForm VBE.


Height UserForm 170. ,
UserForm, Height 120
( , ,
, ). OK,
VBA Height 170. .
Me.Height = 170

. 15.3.
UserForm
,

.
Excel .
,
.
.
, . ,
, , .
VBA- UserForm.
UserForm
MultiPage.
. 15.4 .
UserForm,
MultiPage.
MultiPage.

,
- .
, .

-.

15. UserForm

415

MultiPage
UserForm. MultiPage. .
MultiPage
, (
). -
, MultiPage . MultiPage .
Style MultiPage 2 - fmTabStyleNone. UserForm
() (
MultiPage).

. 15.4. , , MultiPage


MultiPage. . MultiPage, .


,
.
MultiPage, MultiPage. , .
: .
: .
.

416

IV.

: .
.
: .


, ,
.
. ,
, . .

CommandButton ()
CancelButton, BackButton, NextButton FinishButton.



Click.
CancelButton. MsgBox (. 15.5), , . ,
UserForm , . .
Private Sub CancelButton_Click()
Msg = " ?"
Ans = MsgBox(Msg, vbQuestion + vbYesNo, APPNAME)
If Ans = vbYes Then Unload Me
End Sub

. 15.5.

.
Private Sub BackButton_Click()
MultiPage1.Value = MultiPage1.Value - 1
UpdateControls
End Sub
Private Sub NextButton_Click()
MultiPage1.Value = MultiPage1.Value + 1
UpdateControls
End Sub

. Value MultiPage, , UpdateControls ( ).


UpdateControls, 15.1, BackButton NextButton.

15. UserForm

417

15.1. ,
Sub UpdateControls()
Select Case MultiPage1.Value
Case 0
BackButton.Enabled = False
NextButton.Enabled = True
Case MultiPage1.Pages.Count - 1
BackButton.Enabled = True
NextButton.Enabled = False
Case Else
BackButton.Enabled = True
NextButton.Enabled = True
End Select
'


Me.Caption = APPNAME & " " _
& MultiPage1.Value + 1 & " " _
& MultiPage1.Pages.Count


If tbName.Text = "" Then
FinishButton.Enabled = False
Else
FinishButton.Enabled = True
End If
End Sub
'

UserForm, ( APPNAME
Module1).
MultiPage ( TextBox,
tbName). , . TextBox ,
FinishButton .
, .


, . -
, . (
) Microsoft.
OptionButton
, .
,
Change MultiPage.
MultiPage (
), MultiPage1_Change.
( ), CheckBox ,
. .

CheckBox, ( ),
Frame ( ). For Next

418

IV.

Frame ,
. Frame. ,
, ,
, TextBox,
(, ,
). MultiPage1_Change 15.2.
15.2. ,
Private Sub MultiPage1_Change()
'
?
If MultiPage1.Value = 3 Then
'
CheckBox
Dim ProdCB(1 To 3) As MSForms.CheckBox
Set ProdCB(1) = cbExcel
Set ProdCB(2) = cbWord
Set ProdCB(3) = cbAccess
'

Frame
Dim ProdFrame(1 To 3) As MSForms.Frame
Set ProdFrame(1) = FrameExcel
Set ProdFrame(2) = FrameWord
Set ProdFrame(3) = FrameAccess
TopPos = 22
FSpace = 8
AtLeastOne = False

'


For i = 1 To 3
If ProdCB(i) Then
ProdFrame(i).Visible = True
ProdFrame(i).Top = TopPos
TopPos = TopPos + ProdFrame(i).Height + FSpace
AtLeastOne = True
Else
ProdFrame(i).Visible = False
End If
Next i

?
If AtLeastOne Then
lblHeadings.Visible = True
Image4.Visible = True
lblFinishMsg.Visible = False
Else
lblHeadings.Visible = False
Image4.Visible = False
lblFinishMsg.Visible = True
If tbName = "" Then
lblFinishMsg.Caption = _
" 1."
Else
lblFinishMsg.Caption = _
" ."
End If
End If
End If
End Sub
'

15. UserForm

419


, :
UserForm
. , 15.3, .
(r).
.
15.3.
Private Sub FinishButton_Click()
r = Application.WorksheetFunction. _
CountA(Range("A:A")) + 1
'


Cells(r, 1) = tbName.Text

'


Select Case True
Case obMale: Cells(r, 2) = ""
Case obFemale: Cells(r, 2) = ""
Case obNoAnswer: Cells(r, 2) = ""
End Select

'


Cells(r, 3) = cbExcel
Cells(r, 4) = cbWord
Cells(r, 5) = cbAccess

'


If obExcel1 Then Cells(r, 6) = ""
If obExcel2 Then Cells(r, 6) = 0
If obExcel3 Then Cells(r, 6) = 1
If obExcel4 Then Cells(r, 6) = 2
If obWord1 Then Cells(r, 7) = ""
If obWord2 Then Cells(r, 7) = 0
If obWord3 Then Cells(r, 7) = 1
If obWord4 Then Cells(r, 7) = 2
If obAccess1 Then Cells(r, 8) = ""
If obAccess2 Then Cells(r, 8) = 0
If obAccess3 Then Cells(r, 8) = 1
If obAccess4 Then Cells(r, 8) = 2


Unload Me
End Sub
'

,
Style MultiPage.
2 - fmTabStyleNone.

MsgBox
VBA MsgBox ,
. , , ,
, ,
.

420

IV.

, VBA MsgBox. ,
. , MsgBox
( , ), : ,
MsgBox, .

, UserForm. ,

. . ,
, , ..
, MsgBox,
MyMsgBox. ,
MyMsgBox .
( ,
).
(
).
( ,
).
MyMsgBox .
MyMsgBox([, ] [, ])

MsgBox, ,
( ).
MyMsgBox ,
MsgBox: vbOKOnly, vbQuestion, vbDefaultButton1 ..

MsgBox
, .

MyMsgBox

MyMsgBox UserForm,
MyMsgBoxForm. . . Initialize
(UserForm_Initialize).

Public
Public
Public
Public

MyMsgBox
,
-.
Prompt1 As String
Buttons1 As Integer
Title1 As String
UserClick As Integer

15. UserForm

421

Function MyMsgBox(ByVal Prompt As String, _


Optional ByVal Buttons As Integer, _
Optional ByVal Title As String) As Integer
Prompt1 = Prompt
Buttons1 = Buttons
Title1 = Title
MyMsgBoxForm.Show
MyMsgBox = UserClick
End Function

. 15.6 MyMsgBox ( ).

. 15.6.
MsgBox ( )

, .
Prompt = " ?"
Buttons = vbQuestion + vbYesNo
Title = " "
Ans = MyMsgBox(Prompt, Buttons, Title)


. (Prompt1, Buttons1 Title1) , . (UserClick) , . UserForm_Initialize .
(Public)
.
UserForm (. 15.7)
Image ( ),
CommandButton, TextBox.

. 15.7. UserForm,
MyMsgBox

422

IV.

UserForm_Initialize
.
, (
).
, (
).
, .
.
CommandButton.
.
(
API, ).
.
UserForm.

CommandButton. , .
UserClick.
() .
.
vbYesNoCancel + VbQuestion + VbDefaultButton3

(, ),

. 547 (3+32+512).
.
: . , 547
1000100011. 4 6 , 8 10 , 1
2 , .

MyMsgBox
,
MyMsgBoxMod MyMsgBoxForm.
.


, , , ..
, ,
. .
, ,
.

15. UserForm

423

Excel 2000 Excel, . ,


Excel.

UserForm, .
UserForm1.Show vbModeless

vbModeless , 0.
, .
UserForm1.Show 0

. 15.8 , . , .

-.


, .
:
SheetSelectionChange SheetActivate. ThisWorkbook.

18, .

. 15.8. ,

424

IV.

.
Private Sub Workbook_SheetSelectionChange _
(ByVal Sh As Object, ByVal Target As Range)
Call UpdateBox
End Sub
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Call UpdateBox
End Sub

UpdateBox, .
Sub UpdateBox()
With UserForm1
'

If TypeName(ActiveSheet) <> "Worksheet" Then
.lblFormula.Caption = "N/A"
.lblNumFormat.Caption = "N/A"
.lblLocked.Caption = "N/A"
Exit Sub
End If
.Caption = ": " & ActiveCell.Address(False, False)

If ActiveCell.HasFormula Then
.lblFormula.Caption = ActiveCell.Formula
Else
.lblFormula.Caption = "()"
End If
'

.lblNumFormat.Caption = ActiveCell.NumberFormat
'

.lblLocked.Caption = ActiveCell.Locked
End With
End Sub
'

UpdateBox UserForm,
. Label (lblFormula, lblNumFormat lblLocked).
, , .
UserForm ,
,
. Excel 97
UserForm .
, .
, Label N/A.

( ThisWorkbook).

Selection_Change

Label
.
. 15.9
( -).
. , Excel, , Info (

15. UserForm

425

Excel ). ,
, .
UserForm ( ),

UserForm.

: SheetSelectionChange SheetActivate. , ,
, . ,
. , , ,
. .
, ,
. Precedents
Dependents.

UserForm
Label. , VBA
Label, UserForm
.
29.

. 15.9. UserForm



CommandButton UserForm
Click. ,
CommandButton,
.
Private Sub CommandButton1_Click()
'
End Sub

426

IV.

Private Sub CommandButton2_Click()


'
End Sub

, ,
CommandButton. Click CommandButton.

, , . (CommandButton1 CommandButton2)
ButtonClick.
ButtonClick, .
Private Sub CommandButton1_Click()
Call ButtonClick(1)
End Sub
Private Sub CommandButton2_Click()
Call ButtonClick(2)
End Sub

UserForm
CommandButton,
. , , , .
, .
.

-.

.
1.
CommandButton ( -
16 CommandButton). ,
UserForm1.
2. (
InsertClass Module), BtnClass .
ButtonGroup_Click.
Public WithEvents ButtonGroup As MsForms.CommandButton
Private Sub ButtonGroup_Click()
Msg = " " & ButtonGroup.Name & vbCrLf _
& vbCrLf
Msg = Msg & ": " & ButtonGroup.Caption _
& vbCrLf
Msg = Msg & " : " & ButtonGroup.Left _
& vbCrLf
Msg = Msg & " : " & ButtonGroup.Top
MsgBox Msg, vbInformation, ButtonGroup.Name
End Sub

15. UserForm

427

3. VBA . UserForm.
Sub ShowDialog()
UserForm1.Show
End Sub

4. UserForm 15.4. Initialize


UserForm. ,
OKButton. ,
OKButton ButtonGroup_Click.
15.4. Button
Dim Buttons() As New BtnClass
Private Sub UserForm_Initialize()
Dim ButtonCount As Integer
Dim ctl As Control
Button
ButtonCount = 0
For Each ctl In UserForm1.Controls
If TypeName(ctl) = "CommandButton" Then
If ctl.Name <> "OKButton" Then ' OKButton
ButtonCount = ButtonCount + 1
ReDim Preserve Buttons(1 To ButtonCount)
Set Buttons(ButtonCount).ButtonGroup = ctl
End If
End If
Next ctl
End Sub
'

ShowDialog,
UserForm. CommandButton ( OK) ButtonGroup_Click.
. 15.10 ,
.

. 15.10. ButtonGroup_Click

428

IV.


. Public WithEvents. , CommandButton OptionButton, .
Public WithEvents ButtonGroup As MsForms.OptionButton

, . UserForm,
( 56 ).
(GetAColor),
UserForm .

-.

GetAColor.
Public ColorValue As Variant
Dim Buttons(1 To 56) As New ColorButtonClass
Function GetAColor() As Variant
'
UserForm
'
False,
Dim ctl As Control
Dim ButtonCount As Integer
ButtonCount = 0
For Each ctl In UserForm1.Controls
'
56 '
'
Tag "ColorButton"
If ctl.Tag = "ColorButton" Then
ButtonCount = ButtonCount + 1
Set Buttons(ButtonCount).ColorButton = ctl
'

Buttons(ButtonCount).ColorButton.BackColor = _
ActiveWorkbook.Colors(ButtonCount)
End If
Next ctl
UserForm1.Show
GetAColor = ColorValue
End Function

UserForm 56 CommandButton, , .
GetAColor .
UserColor = GetAColor()

UserForm,
UserColor. , .

15. UserForm

429

. 15.11 UserForm ( ),
56 CommandButton. BackColor

.
.

. 15.11.
,

, -,
.
(UserForm1), 56 CommandButton, .
(ColorButtonClass), ColorButton.
VBA (Module1), GetAColor.
, GetAColor.
GetAColor UserForm
. , , . , GetAColor False. , ,
.
, , ,
.
, -,
.



Excel 5 Excel 95
( ): . ,
UserForm
. , ,
Picture Image, , ,
. UserForm , Microsoft
.

430

IV.

Excel 97
. ,
.


UserForm.

1:
, Microsoft UserForm, , !
. 15.12 UserForm,
Image. ,
UserForm .
,
Picture Image.

. 15.12.
UserForm


UserForm, .
1. .
2. UserForm Image.
3. VBA,
GIF. Picture
Image .
VBA LoadPicture.
4. . , UserForm
, . ,
.

GIF
GIF ( temp.gif) (
Data).
Set CurrentChart = Sheets("Data").ChartObjects(1).Chart
Fname = ThisWorkbook.Path & "\temp.gif"
CurrentChart.Export FileName:=Fname, FilterName:="GIF"

15. UserForm

431

, . , , .

PICTURE IMAGE
Image UserForm Image1,
( Fname)
Image.
Image1.Picture = LoadPicture(Fname)

,
.
.

2:
OWC ChartSpace
13, UserForm
, Toolbox.
Microsoft Office XP Office Web Components
(OWC), UserForm.
. 15.13 UserForm,
ChartSpace.

Excel UserForm. ,
ChartSpace.

CHARTSPACE
Toolbox. ,
Additional Controls.
Microsoft Office Chart 10.0 ( Excel 2000, Microsoft Office Chart 9.0). OK,
Toolbox.

CHARTSPACE
USERFORM
ChartSpace UserForm , .
. .
.

432

IV.

. 15.13. UserForm
ChartSpace


, UserForm,
, .
A2:A13,
B2:B13. , ChartSpace ChartSpace1.
Sub CreateChart()
Dim Chart1 As ChChart 'WCChart
Dim Series1 As ChSeries 'WCSeries
Dim r As Integer
Dim XValues(1 To 12)
Dim DataValues(1 To 12)
'

ChartSpace
Set Chart1 = ChartSpace1.Charts.Add

'


With Chart1
.HasTitle = True
.Title.Caption = Range("B1")
End With
For r = 2 To 13
XValues(r - 1) = Cells(r, 1)
DataValues(r - 1) = Cells(r, 2)
Next r

'


Set Series1 = Chart1.SeriesCollection.Add


With Series1
.Type = chChartTypeColumnClustered
.SetData chDimCategories, chDataLiteral, XValues
.SetData chDimValues, chDataLiteral, DataValues
End With
End Sub
'

15. UserForm

433

. Excel 2000,
, -.
, WCChart ( chChart), ,
WCSeries ( chSeries).
: (XValues),
(DataValues).
Set Chart,
ChartSpace. Chart Chart1.
, B1.
For Next .
Set , Series
Series1. With-End With ( ) .
OWC . OWC.

Object Browser.

, OWC
Excel. 18 VBA Excel.

. 15.14 .
, .
, GIF.

-.
Excel 2002 .

Office Web Components


Office Web Components Web-.
Spreadsheet, Chart Pivot Table. ,
OWC, OWC .
OWC Microsoft Office 2000-2003. . , ,
Microsoft Office 2000 OWC (,
). , , Small Business Microsoft Office 2000 OWC.
, OWC Excel . , OWC.

434

IV.



UserForm ?
?
. 15.15 UserForm,
Microsoft Office Spreadsheet 10.0.
, . Spreadsheet
Excel:
18278 262144 . 300
, Excel.

. 15.14. UserForm
ChartSpace
( Office
Web Components)

. 15.15. UserForm Spreadsheet

SPREADSHEET
Spreadsheet
Toolbox. , Additional Control.
Microsoft Office Spreadsheet 11.0 ( Excel 2002,
Microsoft Office Spreadsheet 10.0).
OK, Toolbox.

SPREADSHEET
USERFORM
Spreadsheet UserForm , .
UserForm,
, . .


Spreadsheet,
.
. 15.16.

15. UserForm

435

B, ( ) .

.
Spreadsheet . EditBox VBA.

. 15.16.
UserForm
Spreadsheet

UserForm ,
. ,
Spreadsheet Toolbox.
1. UserForm Spreadsheet. ,
(Spreadsheet1).
2. ,
, .
, .
3. Spreadsheet
.
.
4. (. 15.17).
5. 2 3. ,
, .
6. A , . 15.16. A, .
7. B1:B3.
B5.
=(B2/12;B3;-B1)

. 15.17.

Spreadsheet

436

IV.

8. B1:B3
. ,
( , ).
9. .
A1:B5.
10. , .
11. .
12. , CommandButton. ( CancelButton) .
(PasteButton) , Excel.
VBA. . , ( , Excel). , ,
UserForm. (
),
( , ).
,
, .
.
Private Sub UserForm_Initialize()
Spreadsheet1.ActiveSheet.Protect
End Sub

PasteButton UserForm .
Private Sub PasteButton_Click()
ActiveCell.Value = Spreadsheet1.Range("B5")
Unload Me
End Sub

B5 (
Spreadsheet) Excel.
UserForm .
, .
Private Sub CancelButton_Click()
Unload Me
End Sub

- Spreadsheet UserForm. ,
, .

15. UserForm

437


UserForm
, . Excel (. 15.18). .

. 15.18. Excel

,
. -
.


.
. Excel
32 .
, .
Excel
.
, , , . Excel
.

. Excel
.
.
Excel .
.
Excel .
,
. Excel .
, Excel , (*, ? #).

438

IV.

VBA,
. Excel
VBA .


( ), , .


,
.
1. dataform.xla - .
2. Excel .
3.
dataform.xla , .



: JWalk
Enhanced Data Form. , .

15. UserForm

439

...

16.
17.
18.
19.
20.
21.

Excel VBA


Excel

16

Excel
VBA
...
Excel.
, .
Excel
VBA

Excel
Excel
, Excel
.

Excel
(, ,
). , (,
). Excel ( ) ,
Excel, .
Excel, Office,
. .
, , ,
.
,
. . , ,
,
. .
, . . , VBA , .
Sub ToggleGridDisplay()
ActiveWindow.DisplayGridlines = _
Not ActiveWindow.DisplayGridlines
End Sub

,
. ,
.
.

, IV,
( ).

VBA
- Excel 5 VBA,
Excel XLM
Excel , .
VBA Excel, VBA. , , .
Power Utility Pak Excel.
VBA .
VBA ,
.
VBA.
,
.
VBA Excel ,
Excel, , .
Excel . , , .
,

.


Excel ,
, . , ?
.
- Excel. ,
,
.
.
, . , , ,
.

444

V.

. , .
, Excel.
,
( ,
Excel).
. , , .
.
VBA. , , .
. , , .

:
Excel, Power Utility Pak. Text Tools . , .
( ,
).
, .
, .
( )

. 16.1 Text Tools .

-.
, Power Utility
Pak.
. .

. 16.1.

16. Excel VBA

445


Excel , . ,
. ..
, , , . , Excel
. , Excel
, .
, ....

Text Tools
,
. , .
,
Excel. , ,
, Excel.
.
( ) , .
,
, .
,
.

, .
, .
. ,
, , .
.
.


Text Tools,
. . RunTextTools,
Excel (, ),
.
, . . .
. -

446

V.

.
.
.

Text Tools
Text Tools .
. .
.
VBA. . . , , .
UserForm. .
.
.


,
.
.
UserForm ,
. . 16.2 VBE.
,
, . , . .
.
.
Proc1. , .
Proc2.
.
.

. 16.2. UserForm

16. Excel VBA

447

. .
. CommandButton,
. .
. .
. CommandButton , .
. Label Frame.
. .
. 16.3 .
.

. 16.3.

448

, ,
.
Excel, OK , .
Text Tools OK,
. .

. , ,
.

V.

ThisWorkbook
Workbook_Open.
.
APPNAME, Module1.
Private Sub Workbook_Open()
Dim ToolsMenu As CommandBarPopup
Dim NewMenuItem As CommandBarButton
Set ToolsMenu = Application.CommandBars(1).FindControl(Type:=10, ID:=30007)
Set NewMenuItem = ToolsMenu.Controls.Add(Type:=1, Temporary:=True)
With NewMenuItem
.Caption = APPNAME
.OnAction = "RunTextTools"
End With
End Sub

Workbook_BeforeClose.

Private Sub Workbook_BeforeClose(Cancel As Boolean)


On Error Resume Next
Application.CommandBars(1).FindControl(Type:=10, _
ID:=30007).Controls(APPNAME).Delete
On Error GoTo 0
End Sub

. 16.4 .
23.

. 16.4.

16. Excel VBA

449

Module1
Module1 , , .


, Module1.
Public
Public
Public
Public
Public

Const APPNAME As String = " "


Const PROGRESSTHRESHHOLD = 2000
UserChoices(1 To 8) As Variant
UndoRange As Range
UserSelection As Range

, ,
.
.
PROGRESSTHRESHHOLD , .
2000 .
UserChoices . .
, Range.
, .

RUNTEXTTOOLS
RunTextTools.
Sub RunTextTools()
Dim InvalidContext As Boolean
If ActiveSheet Is Nothing Then InvalidContext = True
If TypeName(ActiveSheet) <> "Worksheet" Then InvalidContext = True
If InvalidContext Then
MsgBox " .", vbCritical, APPNAME
Else
UserForm1.Show 0
End If
End Sub

, . , ,
.
, InvalidContext True. If-Then-Else
. , Show 0, .

, .
.

UNDOTEXTTOOLS
Excel ( ). .

450

V.

UserForm1
,
UserForm1. .
, , text
tools.xla - .

USERFORM_INITIALIZE
.
, (
). ,
.

COMBOBOXOPERATION
.
.

APPLYBUTTON_CLICK
.
, CreateWorkRange. . ApplyButton_Click
SaveForUndo, .
Select Case,
, :
ChangeCase, AddText, RemoveText, RemoveSpaces RemoveCharacters. . , ChangeCase ToggleCase SentenceCase.

CLOSEBUTTON_CLICK
.
.

HELPBUTTON_CLICK
.
.

Text Tools
, . , , .
, ApplyButton_Click
CreateWorkRange. Range, . , A
A1:A12. ,
CreateWorkRange
(.. A1:A12). ,
( ) .

16. Excel VBA

451

CreateWorkRange .
Rng. Range, .
TextOnly. . True . .
CreateWorkRange.
Private Function CreateWorkRange(Rng, TextOnly)
'
Range
Set CreateWorkRange = Nothing
'

,
If Rng.Count = 1 And Rng.HasFormula Then
Set CreateWorkRange = Nothing
Exit Function
End If

,
If Rng.Count = 1 Or Rng.MergeCells = True Then
If TextOnly Then
If Not IsNumeric(Rng(1).Value) Then
Set CreateWorkRange = Rng
Exit Function
Else
Set CreateWorkRange = Nothing
Exit Function
End If
Else
If Not IsEmpty(Rng(1)) Then
Set CreateWorkRange = Rng
Exit Function
End If
End If
End If
On Error Resume Next
Set Rng = Intersect(Rng, Rng.Parent.UsedRange)
If TextOnly = True Then
Set CreateWorkRange = Rng.SpecialCells(xlConstants, xlTextValues)
If Err <> 0 Then
Set CreateWorkRange = Nothing
On Error GoTo 0
Exit Function
End If
Else
Set CreateWorkRange = Rng.SpecialCells(xlConstants, xlTextValues + _
xlNumbers)
If Err <> 0 Then
Set CreateWorkRange = Nothing
On Error GoTo 0
Exit Function
End If
End If
End Function

'

452

CreateWorkRange SpecialCell.
,
Excel
. , <F5> .

V.

. . ,
, . , .
CreateWorkRange , , .

Text Tools
Text Tools : . ,
.
,
. SaveSettings, . GetSettings, .
.
HKEY_CURRENT_USER\Software\VB and VBA Program Settings\Text Tools Utility\Settings

. 16.5 ( regedit.exe).


, Excel,
, Text Tools, . , .
.
, .

. 16.5.

16. Excel VBA

453

Text Tools Module1


.
Public UndoRange As Range
Public UserSelection As Range

ApplyButtonClick
SaveForUndo. .
Set UserSelection = Selection
Set UndoRange = WorkRange
ThisWorkbook.Sheets(1).UsedRange.Clear

WorkRange Range, . .
.
For Each RngArea In WorkRange.Areas
ThisWorkbook.Sheets(1).Range(RngArea.Address).Formula = RngArea.Formula
Next RngArea

WorkRange, (
, ).

OnUndo. .
, .
Applocation.OnUndo " ", "UndoTextTools"

Excel .
UndoTextTools, .

Private Sub UndoTextTools()


'

Dim a As Range
Application.ScreenUpdating = False
With UserSelection
.Parent.Parent.Activate
.Parent.Activate
.Select
End With
For Each a In UndoRange.Areas
a.Formula = ThisWorkbook.Sheets(1).Range(a.Address).Formula
Next a
Application.ScreenUpdating = True
On Error GoTo 0
Exit Sub
ErrHandler:
Application.ScreenUpdating = True
MsgBox " ", vbInformation, APPNAME
On Error GoTo 0
End Sub

454

- ,
VBA.

V.

VBA
.
, Excel, . Excel 97 .
VBA ,
. : . , ,
.
VBA .
- ,
. , . .
, .
Application OnUndo, ,
, ,
. ,
.
, UndoMyMacro.
Application.OnUndo " ", "UndoMyMacro"



Text Tools. ,
. .
,
Excel. ,
, , Excel.
, Text Tools
, OK .
,
Excel .
. .
(
)
, . .
, ,
.
.

,
. .
, .
.

16. Excel VBA

455

. ,
, , .
.
.
, .
. .

Text Tools

,
.
, . , ,
, , . , ,
.

456

Text Tools , . 21
.

V.

17

...
Excel.
Excel 5. Excel (

). . ,
( ).
VBA.
VBA, .
VBA .
,
, . , . Excel
VBA, .

Excel 2000. ,
. , . , Excel 2000 .


VBA
.
. 17.1 . : , , .
.


. 17.2 , .
. .
.
.

.
,
Sum ().

. 17.1.

. 17.2. ,
, . 17.1

.
, .
Sub Macro1()
'

Range("A1").Select
ActiveWorkbook.PivotCaches.Add _
(SourceType:=xlDatabase, _
SourceData:="1!R1C1:R13C4"). _
CreatePivotTable _
TableDestination:="", _
TableName:="1", _
DefaultVersion:=xlPivotTableVersion10
ActiveSheet.PivotTableWizard _
TableDestination:=ActiveSheet.Cells(3, 1)
ActiveSheet.Cells(3, 1).Select
With ActiveSheet.PivotTables("1"). _
PivotFields("")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("1"). _
PivotFields("")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("1"). _
PivotFields("")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("1"). _
AddDataField ActiveSheet.PivotTables("1"). _
PivotFields(""), " ", xlSum
End Sub

458

V.


. , , . :
.
, ,
, . ,
.


VBA, ,
. ,
, .
PivotCaches PivotCache Workbook.
PivotTables PivotTable Worksheet.
PivotFields PivotTable.
PivotItems .
CreatePivotTable PivotCache,
, -.
PivotTableWizard Worksheet,
( . ).


, , . ,
. 17.1 , , , .
17.1. VBA
Sub CreatePivotTable()
'

Dim PTCache As PivotCache
Dim PT As PivotTable
Set PTCache = ActiveWorkbook.PivotCaches.Add _
(SourceType:=xlDatabase, _
SourceData:=Range("A1").CurrentRegion.Address)
Set PT = PTCache.CreatePivotTable _
(TableDestination:="", _
TableName:="1")
With PT
.PivotFields("").Orientation = xlPageField
.PivotFields("").Orientation = xlColumnField
.PivotFields("").Orientation = xlRowField
.PivotFields("").Orientation = xlDataField
End With
End Sub

17.

459

CreatePivotTable ( ), : PivotCache PT.


ActiveSheet.PivotCaches ActiveSheet.
PivotTables. PivotCache Add.
PivotTable, CreatePivotTable
PivotCaches.
( , , ).
, , PivotCache (
"1!R1C1:R13C4"). CreatePivotTable
, A1. ,
, .


PivotFields. , , .
, PivotFields(1)
PivotFields("").

, , .
, , . .
,
.


VBA, .

. 17.3 . 15840
. ;
. , .
( ) .

-.


. 17.4 ,
. ,
, , (1, 2,
3 4), .

460

V.

. 17.3.

. 17.4. , , . 17.3


, 17.2, ,
.
17.2.
Sub CreatePivotTable()
Dim PTcache As PivotCache
Dim PT As PivotTable
On Error Resume Next
Sheets("1").DrawingObjects("TextBoxWait").Visible = True
On Error GoTo 0

17.

461

Application.ScreenUpdating = False
'

,
On Error Resume Next
Application.DisplayAlerts = False
Sheets("").Delete
On Error GoTo 0

'

PivotCache
Set PTcache = ActiveWorkbook.PivotCaches.Add( _
SourceType:=xlDatabase, _
SourceData:=Range("A1").CurrentRegion.Address)

'


Worksheets.Add
ActiveSheet.Name = ""

'

-
Set PT = PTcache.CreatePivotTable( _
TableDestination:=Sheets("").Range("A1"), _
TableName:="BudgetPivot")

'

With PT

.PivotFields("").Orientation = xlRowField
.PivotFields("").Orientation = xlColumnField
.PivotFields("").Orientation = xlPageField
.PivotFields("").Orientation = xlDataField
.PivotFields("").Orientation = xlDataField

'


.CalculatedFields.Add "", "=-"
.PivotFields("").Orientation = xlDataField

'


.PivotFields("").CalculatedItems.Add "1", "= + + "
.PivotFields("").CalculatedItems.Add "2", "= + + "
.PivotFields("").CalculatedItems.Add "3", "= + + "
.PivotFields("").CalculatedItems.Add "4", "= + + "

'


.PivotFields("").PivotItems("1").Position
.PivotFields("").PivotItems("2").Position
.PivotFields("").PivotItems("3").Position
.PivotFields("").PivotItems("4").Position

'

=
=
=
=

4
8
12
16


.PivotFields(" ").Caption = " ($)"
.PivotFields(" ").Caption = " ($)"
.PivotFields(" ").Caption = " ($)"

End With
Application.ScreenUpdating = True
On Error Resume Next
Sheets("1").DrawingObjects("TextBoxWait").Visible = False
End Sub


CreatePivotTable ( 17.2) PivotSheet, .
PivotCache, , .
.

462

V.

.
.
.
.
.
Add CalculatedFields
,
.
.
. , (, 1
). , ,
. , ($).

. ,
.




. , Excel .
VBA, ,
Access.

, , .

, , 17.3.
, budget.mdb ,
.
17.3.

Sub CreatePivotTableFromDB()
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim DBFile As String
Dim ConString As String
Dim QueryString As String
'

,
On Error Resume Next
Application.DisplayAlerts = False
Sheets("").Delete
On Error GoTo 0
Application.DisplayAlerts = True

17.

463

'

PivotCache
Set PTCache = ActiveWorkbook.PivotCaches.Add _
(SourceType:=xlExternal)

'


DBFile = ThisWorkbook.Path & "\budget.mdb"
ConString = "ODBC;DSN=MS Access Database;DBQ=" & DBFile
QueryString = "SELECT * FROM BUDGET"
With PTCache
.Connection = ConString
.CommandText = QueryString
End With

'


Worksheets.Add
ActiveSheet.Name = ""

'


Set PT = PTCache.CreatePivotTable( _
TableDestination:=Sheets("").Range("A1"), _
TableName:="BudgetPivot")


With PT
.PivotFields("").Orientation = xlRowField
.PivotFields("").Orientation = xlColumnField
.PivotFields("").Orientation = xlPageField
.PivotFields("").Orientation = xlDataField
.PivotFields("").Orientation = xlDataField
End With
End Sub
'

, SourceType Add PivotCaches


xlExternal. ( ) SourceType xlDatabase.
PivotCache
.
. .
ODBC, Microsoft Access budget.mdb.
. SQL, ,
.
Budget.
PivotCache
Connection CommandText. ,
CreatePivotTable .

464

SQL .
.
, SQL.

V.


,
, .
(. 17.5) 100 .
,
.
. 17.6 ,
.
.

. 17.5.

. 17.6. , VBA

17.

465

VBA, , 17.4.
17.4.

Sub MakePivotTables()
'
14
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim SummarySheet As Worksheet
Dim ItemName As String
Dim Row As Integer, i As Integer
Application.ScreenUpdating = False
'

,
On Error Resume Next
Application.DisplayAlerts = False
Sheets("").Delete
On Error GoTo 0

'


Set SummarySheet = Worksheets.Add
ActiveSheet.Name = ""

'

PivotCache
Set PTCache = ActiveWorkbook.PivotCaches.Add( _
SourceType:=xlDatabase, _
SourceData:=Sheets("").Range("A1"). _
CurrentRegion.Address)

'

Row = 1
For i = 1 To 14
ItemName = Sheets("").Cells(1, i + 2)

Set PT = PTCache.CreatePivotTable _
(TableDestination:=SummarySheet.Cells(Row, 1), _
TableName:=ItemName)
Row = Row + 11

With PT.PivotFields(ItemName)
.Orientation = xlDataField
.Name = "-"
End With

'

With PT.PivotFields(ItemName)
.Orientation = xlDataField
.Name = ""
.Calculation = xlPercentOfTotal
End With
PT.AddFields RowFields:=Array(ItemName, "")
PT.PivotFields("").Orientation = xlColumnField
PT.PivotFields("").Orientation = xlColumnField
Next i
'


SummarySheet.Activate
With Columns("A:A")
.Replace "1", " "
.Replace "2", " "
.Replace "3", " "
.Replace "4", ""
.Replace "5", " "
End With

466

V.


Columns("A:G").EntireColumn.AutoFit
End Sub
'

,
PivotCache. Row
.
(, 1 ). , .


Excel . , ,
. ,
. ,
, ,
OptionButtons CheckBox (. 17.7).
(1,
2, 3 4), . VBA, OptionButton1, 17.5.
. OptionButton.

. 17.7.

17.5.
Private Sub OptionButton2_Click()
'

Application.ScreenUpdating = False
With ActiveSheet.PivotTables(1).PivotFields("")
.PivotItems("1").Visible = True
.PivotItems("2").Visible = True
.PivotItems("3").Visible = True
.PivotItems("4").Visible = True
.PivotItems("").Visible = False
.PivotItems("").Visible = False
.PivotItems("").Visible = False
.PivotItems("").Visible = False

17.

467

.PivotItems("").Visible = False
.PivotItems("").Visible = False
.PivotItems("").Visible = False
.PivotItems("").Visible = False
.PivotItems("").Visible = False
.PivotItems("").Visible = False
.PivotItems("").Visible = False
.PivotItems("").Visible = False
End With
End Sub

CheckBox .
.
Private Sub CheckBox1_Click()
'

Application.ScreenUpdating = False
ActiveSheet.PivotTables(1).ColumnGrand = CheckBox1.Value
End Sub
Private Sub CheckBox2_Click()
'

Application.ScreenUpdating = False
ActiveSheet.PivotTables(1).RowGrand = CheckBox2.Value
End Sub

. ,
VBA,
, .
.

468

V.

18


...
Excel .
, .
.
Excel.
.
Chart.

Chart.

VBA.
.
.
Excel 100 ,
.


.
, . ,
VBA .
VBA,
.
. Excel.


Excel .
.
.
. .

, Excel 5/95. (.
),
.

. VBA. , VBA
.

<F11>. Excel , .

.
,
Chart. VBA ActiveChart
Chart ( ). ,
( Workbook, ActiveWorkbook).
. ,
Name Chart.
MsgBox ActiveChart.Name

, .

,
VBA.


,
, ,
. , Excel, .
Chart , , .
, , . ,
Chart .
, ,
. Application (Excel).
Application Workbook, Worksheet.
Worksheet ChartObject, Chart.
Chart ChartTitle, ChartTitle
Text, , .
.
Application
Workbook
Worksheet
ChartObject
Chart
ChartTitle

VBA , , . ,
, VBA.

470

V.

WorkSheets("1").ChartObjects(1).Chart.ChartTitle. _
.Text = " "

,
Workbook.
1. Chart Chart, ChartTitle ChartTitle. Text.
,
Worksheet ChartObject. , .
Application
Workbook
Chart
ChartTitle

Text ChartTitle.
WorkSheets("1").ChartTitle. _
Text = " "

, Chart
ChartObject. , ,
ChartObject,

Workbook.
,
.
MsgBox TypeName(Sheets("1").ChartObjects(1).Chart)
Msgbox TypeName(Sheets("1"))

ChartObjects, (
Charts).
Charts Sheets .


,
Chart .
,
, ,
VBA.
Excel ,
, Chart
ActiveChart. Excel ( ) , () VBA. , ,
. , , , (, ).

18.

471



( . 18.1). A1:F2. ( ) .

. 18.1.
Excel

, .
Sub Macro1()
'

Range("A1:F2").Select
Charts.Add
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData _
Source:=Sheets("1").Range("A1:F2"), _
PlotBy:=xlRows
ActiveChart.Location _
Where:=xlLocationAsObject, _
Name:="1"
ActiveChart.HasLegend = False
ActiveChart.ApplyDataLabels _
Type:=xlDataLabelsShowValue, LegendKey:=False
ActiveChart.HasDataTable = False
ActiveChart.Axes(xlCategory).Select
Selection.TickLabels.Orientation = xlHorizontal
ActiveChart.ChartTitle.Select
Selection.Font.Bold = True
Selection.AutoScaleFont = True
With Selection.Font
.Name = "Arial"
.Size = 12
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
.Background = xlAutomatic
End With
ActiveChart.PlotArea.Select

472

V.

Selection.Top = 18
Selection.Height = 162
ActiveChart.ChartArea.Select
ActiveChart.Axes(xlValue).Select
With ActiveChart.Axes(xlValue)
.MinimumScaleIsAuto = True
.MaximumScale = 0.6
.MinorUnitIsAuto = True
.MajorUnitIsAuto = True
.Crosses = xlAutomatic
.ReversePlotOrder = False
.ScaleType = xlLinear
End With
End Sub


, ,
, . , .
. ,
, .
ScreenUpdating False .
Sub CleanedMacro()
Application.ScreenUpdating = False
Charts.Add
ActiveChart.Location _
Where:=xlLocationAsObject, Name:="1"
With ActiveChart
.SetSourceData Range("A1:F2")
.HasTitle = True
.ChartType = xlColumnClustered
.HasLegend = False
.ApplyDataLabels Type:=xlDataLabelsShowValue
.Axes(xlCategory).TickLabels.Orientation = xlHorizontal
.ChartTitle.Font.Bold = True
.ChartTitle.Font.Size = 12
.PlotArea.Top = 18
.PlotArea.Height = 162
.Axes(xlValue).MaximumScale = 0.6
.Deselect
End With
Application.ScreenUpdating = True
End Sub

Add Charts
. Location .
, ( ), -. , .

18.

473


VBA
,
.


, . VBA
Activate.
.
ActiveSheet.ChartObjects("1").Activate

,
.
Sheets("1").Activate

,
ActiveChart. ,
. ,
.
MsgBox ActiveChart.Name

VBA, . , , ( 1 ). , .
Sub ModifyChart1()
ActiveSheet.ChartObjects("1").Activate
ActiveChart.Type = xlArea
ActiveChart.Deselect
End Sub
Sub ModifyChart2()
ActiveSheet.ChartObjects("1").Chart.Type = xlArea
End Sub

, , .
, .
. Chart ( ChartObject)
, ChartObject .
,
VBA. ,
ChartObject 1 , .
Sub ConvertChart1()
Sheets("1").ChartObjects(1).Chart. _
Location xlLocationAsNewSheet, ""
End Sub

474

V.

, : 1.
Sub ConvertChart2()
Charts("") _
.Location xlLocationAsObject, "1"
End Sub

Location
.

, ChartObject, , . ,
.
, , ,
(. 18.2). , (
). ,
. , .

. 18.2.

VBA ChartObject
.

ActiveSheet.ChartObjects(1).Activate
ActiveChart.ShowWindow = True

,
.


, ,
.
ActiveWindow.Visible = False

18.

475

, ,
.
Deselect, .
ActiveChart.Deselect

-.
, Deselect .
Visible ActiveWindow False , .



( ). , ,
.
: VBA , ?
. TypeName Selection .
TypeName(Selection) = "Chart"

True, . , True.
, ,
, Chart. , Series, ChartTitle, Legend, PlotArea ..
ChartIsSelected, , True,
.
False.
Private Function ChartIsSelected() As Boolean
ChartIsSelected = Not ActiveChart Is Nothing
End Function

ActiveChart Nothing.
, .

ChartObject
ChartObject , Delete ChartObjects.
ActiveSheet.ChartObjects.Delete

,
.
ActiveWorkbook.Charts.Delete

Excel , . 18.3. ,
. ,
.
Application.DisplayAlerts = False
ActiveWorkbook.Charts.Delete
Application.DisplayAlerts = True

476

V.

. 18.3. ,



.
Sub ChartMods1()
With ActiveChart
.Type = xlArea
.ChartArea.Font.Name = "Arial"
.ChartArea.Font.FontStyle = "Regular"
.ChartArea.Font.Size = 9
.PlotArea.Interior.ColorIndex = xlNone
.Axes(xlValue).TickLabels.Font.Bold = True
.Axes(xlCategory).TickLabels.Font.Bold = True
.HasLegend = True
.Legend.Position = xlBottom
End With
End Sub

, . ,
HasLegend True. ,
Position
Legend, .

ChartMods. ,
ChartObject 1 1. , .
Sub ChartMods2()
With Sheets("1").ChartObjects("1").Chart
.Type = xlArea
.ChartArea.Font.Name = "Arial"
.ChartArea.Font.FontStyle = "Regular"
.ChartArea.Font.Size = 9
.PlotArea.Interior.ColorIndex = xlNone
.Axes(xlValue).TickLabels.Font.Bold = True
.Axes(xlCategory).TickLabels.Font.Bold = True
.HasLegend = True
.Legend.Position = xlBottom
End With
End Sub

18.

477


.

. For Next
ChartObjects. ChartType
Chart.
xlArea. VBA,
, .
Sub ChangeChartType()
Dim chtobj as ChartObject
For Each chtobj In ActiveSheet.ChartObjects
chtobj.Chart.ChartType = xlArea
Next chtobj
End Sub

, ,
.
Sub ChangeChartType2()
Dim cht as Chart
For Each cht In ActiveWorkbook.Charts
cht.ChartType = xlArea
Next cht
End Sub


. ChartObject For Next.
Sub LegendMod()
Dim chtobj as ChartObject
For Each chtobj In ActiveSheet.ChartObjects
With chtobj.Chart.Legend.Font
.Name = "Arial"
.FontStyle = "Bold"
.Size = 12
End With
Next chtobj
End Sub


ChartObject
ChartObject . , VBA.
ChartObject 1, ChartObject
1. , ChartObject , .
Sub ResizeAndArrangeChartObjects()
Dim W As Double, H As Double
Dim TopPos As Double
Dim chtobj As ChartObject
W = ActiveSheet.ChartObjects("1").Width
H = ActiveSheet.ChartObjects("1").Height
TopPos = 0

478

V.

For Each chtobj In ActiveSheet.ChartObjects


With chtobj
.Width = W
.Height = H
.Left = 0
.Top = TopPos
End With
TopPos = TopPos + H
Next chtobj
End Sub


Excel 2000 (
PivotChart). , ( PivotTable). PivotChart (PivotTable).
, .
. .
(. ).
,
.

Microsoft Excel, Excel, VBA.


PivotLayout Chart.

. , , VBA.

18.

479

TopPos . ( ) H ( ChartObject).


-.

.
,
VBA , .


. ,
, (SERIES). .

,
VBA.
.
=(;1!$A$1:$A$6;1!$B$1:$B$6;1)


, ,
.
. : , , .
.
.
=(; _; ;, )
, ( ).
,
;
_ ,
( ). , Excel , 1.
, .
, ( , ).

480

V.

.
=(!$B$1;;!$B$2:$B$7;1)
. , , . B2:B3 B5:B7.
=(;;(1!$B$2:$B$3;1!$B$5:$B$7);1)
. Excel
, .
=(1!$B$1;;budget.xls!MyData;1)

(, ),
,
. .
=(;!;!;1)

, ,
VBA .
. ,
.
Range("B1:B12").Name = ""


.
Resize Range . , Data
, .

With Range("Data")
.Resize(.Rows.Count + 1, 1).Name = "Data"
End With

Excel 2003 ,
.
, , .

,
, ,
VBA , .


. 18.4 ,
.
.

18.

481

. 18.4.


Worksheet. SelectionChange ,
, .
( 1) .
Private Sub Worksheet_SelectionChange(ByVal Target _
As Excel.Range)
Call UpdateChart
End Sub

, , ,
Worksheet_SelectionChange.
UpdateChart.
Sub UpdateChart()
Dim TheChartObj As ChartObject
Dim TheChart As Chart
Dim UserRow As Long
Dim CatTitles As Range
Dim SrcRange As Range
Dim SourceData As Range
If Sheets("1").CheckBox1 Then
Set TheChartObj = ActiveSheet.ChartObjects(1)
Set TheChart = TheChartObj.Chart
UserRow = ActiveCell.Row
If UserRow < 3 Or IsEmpty(Cells(UserRow, 1)) Then
TheChartObj.Visible = False
Else
Set CatTitles = Range("A2:F2")
Set SrcRange = Range(Cells(UserRow, 1), Cells(UserRow, 6))
Set SourceData = Union(CatTitles, SrcRange)
TheChart.SetSourceData _
Source:=SourceData, PlotBy:=xlRows
TheChartObj.Visible = True
End If
End If
End Sub

482

V.


. , .
UserRow .
If , (
3). , , ChartObject .
Range ( CatTitle), ,
Range ( SrcRange), . Range VBA Union
Range SourceData. , SourceData SetSourceData Chart.


ComboBox
ComboBox
.
(. 18.5).

ComboBox, ,
(
). , Excel ActiveX.

-.

DropDown1_Change ComboBox.
ComboBox,
.
Sub DropDown1_Change()
ListIndex = Charts(1).DropDowns(1).Value
Call UpdateChart(ListIndex)
End Sub

. 18.5. ComboBox

18.

483

UpdateChart , , .
UpdateChart ( UpdateChart ).
Sub UpdateChart(Item)
'

Dim TheChart As Chart
Dim DataSheet As Worksheet
Dim CatTitles As Range, SrcRange As Range
Dim SourceData As Range
Set TheChart = Sheets("1")
Set DataSheet = Sheets("1")
With DataSheet
Set CatTitles = .Range("A2:F2")
Set SrcRange = .Range(.Cells(Item + 2, 1), _
.Cells(Item + 2, 6))
End With
Set SourceData = Union(CatTitles, SrcRange)
With TheChart
.SetSourceData Source:=SourceData, PlotBy:=xlRows
.ChartTitle.Left = TheChart.ChartArea.Left
.Deselect
End With
End Sub


. Series
Chart. SeriesCollection
Series Chart.
, . Series . Series
, .
Formula. Series. ,
. Formula .
Values. .
,
.
XValues. X . XValues
, .
, ,
, , Values Series. XValues
, X ( ). , .
XValues
Value (.. ).

484

V.

, (SERIES)
. ,
(SERIES) .
(SERIES) , , , , . .
, , ,
. ,
(SERIES) 25 , .
,
( Series)
.
SERIESNAME_FROM_SERIES. , (SERIES) (Range, Empty
String). ,
.
XVALUES_FROM_SERIES. ,
(SERIES) (Range, Empty String).
, .
VALUES_FROM_SERIES. , (SERIES) (Range Array).
.
BUBBLESIZE_FROM_SERIES. XVALUES_FROM_SERIES.
,
(SERIES) (Range, Array Empty).
, .

, SERIES ( ).
PlotOrder Series.

, .
,
-.

.
Sub ShowValuesRange()
Dim Ser As Series
Dim x As Variant
Set Ser = ActiveChart.SeriesCollection(1)
x = VALUES_FROM_SERIES(Ser)
If x(1) = "Range" Then
MsgBox Range(x(2)).Address
End If
End Sub

x Variant, , VALUES_FROM_SERIES. . Range, , .

18.

485

. 18.6 .
. , ().
ContractAllSeries. SeriesCollection
XVALUES_FROM_SERIES VALUES_FROM_SERIES .
Resize .
Sub ContractAllSeries()
Dim s As Series
Dim Result As Variant
Dim DRange As Range
For Each s In ActiveSheet.ChartObjects(1).Chart.SeriesCollection
Result = XVALUES_FROM_SERIES(s)
If Result(1) = "Range" Then
Set DRange = Range(Result(2))
If DRange.Rows.Count > 1 Then
Set DRange = DRange.Resize(DRange.Rows.Count - 1)
s.XValues = DRange
End If
End If
Result = VALUES_FROM_SERIES(s)
If Result(1) = "Range" Then
Set DRange = Range(Result(2))
If DRange.Rows.Count > 1 Then
Set DRange = DRange.Resize(DRange.Rows.Count - 1)
s.Values = DRange
End If
End If
Next s
End Sub

ExpandAllSeries .
.

. 18.6.

486

V.



Excel. , ,
. 18.7. . ,
Excel, ( ). , , ,
.

. 18.7.

18.2 ,
. Points Text
, .
18.2.
Sub DataLabelsFromRange()
Dim DLRange As Range
Dim Cht As Chart
Dim i As Integer, Pts As Integer
'


Set Cht = ActiveSheet.ChartObjects(1).Chart

'


On Error Resume Next
Set DLRange = Application.InputBox _
(prompt:=" ", Type:=8)
If DLRange Is Nothing Then Exit Sub
On Error GoTo 0

'


Cht.SeriesCollection(1).ApplyDataLabels _
Type:=xlDataLabelsShowValue, _
AutoText:=True, _
LegendKey:=False

18.

487


Pts = Cht.SeriesCollection(1).Points.Count
For i = 1 To Pts
Cht.SeriesCollection(1). _
Points(i).DataLabel.Text = DLRange(i)
Next i
End Sub


'

-.

. 18.8 DataLabelsFromRange
A2:A9.

. 18.8. ,
( VBA)

. ,
.
Series. Power Utility Pak
.



15 .
GIF,
Image, UserForm.
, , .
:
(. 18.9).

488

V.

. 18.9.

UserForm . Image CommandButton ( ).


, , ,
.
Sub ShowChart()
Dim UserRow As Long
UserRow = ActiveCell.Row
If UserRow < 2 Or IsEmpty(Cells(UserRow, 1)) Then
MsgBox " "
Exit Sub
End If
CreateChart (UserRow)
UserForm1.Show
End Sub

,
, .
, ShowChart CreateChart .
.
CreateChart, 18.3, , .
,
.
18.3.
Sub CreateChart(r)
Dim TempChart As Chart
Dim CatTitles As Range
Dim SrcRange As Range, SourceData As Range
Application.ScreenUpdating = False

18.

489

Set CatTitles = ActiveSheet.Range("A2:F2")


Set SrcRange = ActiveSheet.Range(Cells(r, 1), Cells(r, 6))
Set SourceData = Union(CatTitles, SrcRange)
'


Set TempChart = Charts.Add

'


With TempChart
.ChartType = xlColumnClustered
.SetSourceData Source:=SourceData, PlotBy:=xlRows
.HasLegend = False
.ApplyDataLabels Type:=xlDataLabelsShowValue, LegendKey:=False
.ChartTitle.Font.Size = 14
.ChartTitle.Font.Bold = True
.Axes(xlValue).MaximumScale = 0.6
.Axes(xlCategory).TickLabels.Font.Size = 10
.Axes(xlCategory).TickLabels.Orientation = xlHorizontal
.Location Where:=xlLocationAsObject, Name:="1"
End With


With ActiveSheet.ChartObjects(1)
.Width = 300
.Height = 150
End With
End Sub
'

CreateChart
ChartObject .
ChartObject , ScreenUpdating
Application .
ShowChart UserForm.
UserForm_Initialize.
GIF, ChartObject
GIF Image.
Private Sub UserForm_Initialize()
Dim CurrentChart As Chart
Dim Fname As String
Set CurrentChart = ActiveSheet.ChartObjects(1).Chart
'

GIF
Fname = ThisWorkbook.Path & Application.PathSeparator & "temp.gif"
CurrentChart.Export FileName:=Fname, FilterName:="GIF"
ActiveSheet.ChartObjects(1).Delete


Image1.Picture = LoadPicture(Fname)
Application.ScreenUpdating = True
Kill ThisWorkbook.Path & Application.PathSeparator & "temp.gif"
End Sub


'

490

-.

V.

Excel , .
, , Activate. Calculate , . VBA, .
19 .

. 18.1 ,
Excel 97 .

18.1. ,

Activate

BeforeDoubleClick

BeforeRightClick

Calculate

Deactivate

DragOver

DragPlot

MouseDown

MouseMove

MouseUp

Resize

Select

SeriesChange

Chart
, , VBA Chart.
, Chart . Chart Object
Procedure, (. 18.10).

, , , .
, ,
, .
.

18.

491

. 18.10.

, , :
; ;
. , .
Chart_Activate , .
Chart_Deactivate , .
Chart_Select , .
Chart_Activate.
Private Sub Chart_Activate()
Dim msg As String
msg = ", " & Application.UserName & vbCrLf & vbCrLf
msg = msg & " "
msg = msg & " 6 3 " & vbCrLf & vbCrLf
msg = msg & " "
MsgBox msg, vbInformation, ActiveWorkbook.Name
End Sub

(. 18.11).

. 18.11.
Chart_Activate

492

V.

Chart_Deactivate, ,
, , .
Private Sub Chart_Activate()
Dim msg As String
msg = "! "
msg = msg & " "
msg = msg & " 6 3 " & vbCrLf & vbCrLf
msg = msg & " "
MsgBox msg, vbInformation, ActiveWorkbook.Name
End Sub

Chart_Select, , ,
.
Private Sub Chart_Select(ByVal ElementID As Long, _
ByVal Arg1 As Long, ByVal Arg2 As Long)
Dim Id As String
Select Case ElementID
Case xlChartArea: Id = " "
Case xlChartTitle: Id = " "
Case xlPlotArea: Id = " "
Case xlLegend: Id = ""
Case xlFloor: Id = ""
Case xlWalls: Id = ""
Case xlCorners: Id = ""
Case xlDataTable: Id = " "
Case xlSeries: Id = ""
Case xlDataLabel: Id = " "
Case xlTrendline: Id = ""
Case xlErrorBars: Id = ""
Case xlXErrorBars: Id = " "
Case xlYErrorBars: Id = " "
Case xlLegendEntry: Id = " "
Case xlLegendKey: Id = " "
Case xlAxis: Id = ""
Case xlMajorGridlines: Id = " "
Case xlMinorGridlines: Id = " "
Case xlAxisTitle: Id = " "
Case xlShape: Id = ""
Case xlNothing: Id = ""
Case Else: Id = " "
End Select
MsgBox ": " & Id
End Sub

,
. Select ElementID
, . Arg1 Arg2 ( ).
Select Case .

Chart. , . Case Else.


, Chart , ,
. , ,
.

18.

493


VBE Project InsertClass Module.
. ,
Properties.

CHART
, . Chart
WithEvents.
WithEvents, .
.
Public WithEvents myChartClass As Chart


, ,
.
Class1 ( ).
,
VBA ( ).
Dim MyChart As New MyChartClass

, . .
Set myChart.myChartClass = ActiveSheet.ChartObjects(1).Chart

myChartClass
. ,

.

,
. , .
Public WithEvents myChartClass As Chart

WithEvents Object .
Object,
Procedure (. 18.12).
,
.
, Chart ( hartObject).
Private Sub clsChart_Activate()
MsgBox clsChart.Parent.Name & " "
End Sub

494

V.

. 18.12. Procedure Chart

- ,
, .

Chart

, , ,
. . 18.13 ,
. .
, .

. 18.13. ,

18.

495

. . , . B1:B4
,
. . , .
, EmbChartClass,
VBA Module1.
: EnableChartEvents, DisableChartEvents ( Module1).
, ,
ReturntoMain, .
Module1 .
Dim SummaryChart As New EmbChartClass
Sub EnableChartEvents()
'

Range("A1").Select
Set SummaryChart.myChartClass = _
Worksheets(1).ChartObjects(1).Chart
End Sub
Sub DisableChartEvents()
'

Set SummaryChart.myChartClass = Nothing
Range("A1").Select
End Sub
Sub ReturnToMain()
'

Sheets("").Activate
End Sub

SummaryChart EmbChartClass
( ). , SummaryChart, ,
, . 18.4
EmbChartClass.
MouseDown,
myChartClass_MouseDown.
GetChartElement ,
. GetChartElement , X Y (
myChartClass_MouseDown).
18.4.
Public WithEvents myChartClass As Chart
Private Sub myChartClass_MouseDown(ByVal Button As Long, _
ByVal Shift As Long, ByVal X As Long, ByVal Y As Long)
Dim IDnum As Long
Dim a As Long, b As Long
'
'


IDNum, a b

496

V.

myChartClass.GetChartElement X, Y, IDnum, a, b
?
If IDnum = xlSeries Then
Select Case b
Case 1
Sheets("").Activate
Case 2
Sheets("").Activate
Case 3
Sheets("").Activate
End Select
End If
Range("A1").Select
End Sub


'

-.


, .
.
.



.
( ), .
,
.
Sub PrintEmbeddedCharts()
For Each chtObj In ActiveSheet.ChartObjects
chtObj.Chart.Print
Next chtObj
End Sub


, Excel , .
. (
). , , ,
.
.
.
. <Shift> (
,
<Shift>). .

18.

497

. , . <F9>,
. .

xl8galry.xls . , Excel . , 20 . ,
.


( ). , .

Sub ConvertChartToPicture()
Dim TheChart As Chart
If ActiveChart Is Nothing Then
MsgBox "Activate a chart.", vbInformation
Exit Sub
End If
Set TheChart = ActiveChart
Application.ScreenUpdating = False
TheChart.CopyPicture Appearance:=xlPrinter, _
Size:=xlScreen, Format:=xlPicture
If TypeName(ActiveSheet) = "Chart" Then
ActiveChart.Paste
Else
ActiveSheet.Paste
Selection.Left = TheChart.Parent.Left
Selection.Top = TheChart.Parent.Top
End If
Application.ScreenUpdating = True
End Sub

(. 18.14),
. . ,
SERIES () , .

Sub CreateADeadChart()
Charts.Add
ActiveChart.Location _
Where:=xlLocationAsObject, Name:="Sheet1"
With ActiveChart
.SeriesCollection.NewSeries
.SeriesCollection(1).XValues = Array("Jan", "Feb", "Mar")
.SeriesCollection(1).Values = Array(125, 165, 189)
.SeriesCollection(1).Name = "Sales"
.ChartType = xlColumnClustered
.HasLegend = False
.Deselect
End With
End Sub

498

-.

V.

. 18.14.

SERIES () ,
.


. ,
.
( ) . Chart .

.
.

. . 18.15
, MouseOver. .

. 18.15.

18.

499

Chart.
Private Sub Chart_MouseMove(ByVal Button As Long, ByVal Shift As Long, _
ByVal X As Long, ByVal Y As Long)
Dim ElementId As Long
Dim arg1 As Long, arg2 As Long
Dim NewText As String
On Error Resume Next
ActiveChart.GetChartElement X, Y, ElementId, arg1, arg2
If ElementId = xlSeries Then
NewText = Sheets("1").Range("Comments").Offset(arg2, arg1)
Else
NewText = ""
ActiveChart.Shapes(1).Visible = False
End If
If NewText <> ActiveChart.Shapes(1).TextFrame.Characters.Text Then
ActiveChart.Shapes(1).TextFrame.Characters.Text = NewText
ActiveChart.Shapes(1).Visible = True
End If
End Sub

. X Y, .
Button Shift .
GetChartElement.
ElementId xlSeries, . NewText (. 18.16). ,
.

-.


Excel ( ). , . ,
. 18.17.

. 18.16. 7:9
,

500

V.

. 18.17. VBA

X ( A) ,
A1.
A1. B , SIN
A.
.
A1, X Y.

- ,
, .

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

-.

. X
Y , A B.
Scrollbar , . B1, B2 B3.
ActiveX. ,
, .

18.

501

. 18.18. ,

( ).
.
1 250 .
Sub Random_Click()
Randomize
Range("B1") = Int(Rnd * 250)
Range("B2") = Int(Rnd * 250)
Range("B3") = Int(Rnd * 250)
End Sub


. 18.19 , ,
. , , ,
. ,
.

. 18.19.

502

V.

-.

, , , . 18.20. ,
, .

. 18.20.

,
,

, -,
.
ChartObject ClockChart
DigitalClock .

.
(StartClock StopClock).
CheckBox () ( cbClockType)
,
.
cbClockType_Click, Visible
ClockChart. ,
.
Series.
, , , 12 .
UpdateClock .
.
UpdateClock OnTime Application.
.
UpdateClock OnTime,
. ,
UpdateClock .
UpdateClock
.
,
. VBA Values XValues Series .

18.

503

,

, . , Excel .



. 18.21 , 365
. , . ,
, .
Excel .
, . Excel ,
. .
, . . . , , . , . 18.22, , , .

. 18.11.

. 18.22.

504

V.

-.

. 18.23.

. 18.23.

, .
, .
. , .
.

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

. ,
<F11>.

, . . 18.24
, .

-.

18.

505

. 18.24.


:
,
?
, , . 18.25.
.
.
, .
, , .

. 18.25.

506

V.

Excel 2003 .
( ) .
.

, .
,
. .
,
, .
,
, . ,
,
.


,
. . 18.25 , . .
=(1!$B$1;dailysales.xls!;dailysales.xls!;1)

.
1.
2:11.
2:11.
, . , .


.
.
, .
.
1. .
.
2. . .
=(1!$A2;0;0;(1!$A:$A)-1;1)

3. .
,
( 2) . ,
1.
4. , .
=(-1!$B$2;0;0;(1!$B:$B)-1;1)

18.

507


( 2). -, ,
1.
5. .
6. , .
.


, .
1. .
.
2. 1!.
3. 1!.
4. , , . 18.26,
.

. 18.26. ,

. 23 , .
( ),
. Excel , . , , .
=dailysales.xls!


, . ( .) ,
, .
='daily sales.xls'!

Excel .

508

V.

Excel
Excel : . , .
, .
.
(, 1!
). .
=*4
, .
=1!*4

. , .
, .
, , ,
.
.

,
.



. , . ,
. , .

?
, ,
. . . . , , . , .


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

18.

509

. ,
.
, .


.
, .

( ).
.
, .
;
#!.
__ ,
, . , , 5 __,
,
. __ ( ) (
).
__ ,
, .
, , 5 __,
,
. __
( ) ( ).
( ) . .
( ) .
.

, ,
.
, .

.
=(1!$B$2;0;0;(1!$B:$B)-1;1)

11 , 11.
, . .
=(1!$B$2;0;0;10;1)

2 ,
.
2 0 .
2 0 .

510

V.

, 10 .
, 1 .
, 2:11, .
2:12.

, ,
. , , .


, . 18.27, , ( 284 ) , ,
.

. 18.27.

Excel
. ,
, .
.
,
.

-.

18.

511


Web .
Excel, .
, 13 . , .


,
.
.
, 3. ,
, 1 4
.
3. , 4, .
=(O3;"TemperatureData";"PrecipitationData";"SunshineData";"WinData")

, 4
. .


,
.
Excel.
. J11:M11
City1. J13:M13 City2.
CityList,
PrecipitationData.
.
1. J11:M11 (, ).
2. .
.
3. .
4. .
5. =CityList.
6. .
7. J11:M11 J13:M13.
. 18.28 .

. 18.28.

512

V.

:
.
, . . 18.29 , .

. 18.29. ,
A22:M24

23 ,
City1.
=(City1;(DataTable);();)

24 , City2.
=(City2;(DataTable);();)

12 .

,
.
. .

.
=" " &(DataTable;(DataTable)-4)


. , A22:M24.
21. A22:M24 .

18.

513

19

Excel
...
Excel , , , . , , Excel
.
, Excel.
, .
, Worksheet, Chart UserForm.
Application .
.
VBA,
.
, .
CommandButton1_Click, , CommandButton,
.
Excel .
Excel .
, Excel:
;
;
;
;
;
;
;
;
;
;
.

Excel
Excel ,
. .
Workbook .
Open ( ), BeforeSave (
) NewSheet ( ).
Worksheet .
Change ( ), SelectionChange ( ) Calculate ( ).
Chart . Select ( ) SeriesChange
( ).

(. 18).
Application Excel. NewWorkbook ( ), WorkbookBeforeClose
( ) SheetChange (
). Application
.
UserForm. UserForm . ,
UserForm Initialize ( UserForm). CommandButton, UserForm, Click
( ).
, . ( Application),
On-: OnTime OnKey. , .
. ,
.


,
.


.
,
Application.

516

V.

WorkbookNewSheet: .
SheetDeactivate: , .
SheetActivate: , .

, .
Application.
( Workbook
Worksheet).

, .
.
, (
Application).


VBA- ,
. , .
VBE Projects.
, . 19.1.
:
(, 1, 2 ..);
(.. );
(ThisWorkbook);
VBA :
( );
.

. 19.1. VBA Projects

19. Excel

517

,
. , ,
, WorkbookSetup, VBA .
Private Sub Workbook_Open()
Call WorkbookSetup
End Sub


. , VBA.
Application.EnableEvents = False

.
Application.EnableEvents = True

, UserForm.
Click,
CommandButton UserForm.

, ? .
, A1 ,
12. , ,
. Change Worksheet,
, Worksheet_Change. , 12,
, . ,
VBA Change, . , .
, .

(Static Boolean) . .
Static AbortProc As Boolean

Excel
Excel 97 ,
.
, Auto_Open, VBA
, .
Excel 97, Auto_Open Workbook_Open, .
Auto_Open.

518

V.

Excel 97 . ,
, ,
.
Sheets("1").OnEntry = "ValidateEntry"
Excel, ValidateEntry ,
. Excel 97 , Worksheet_Change, 1.
Excel 97 ( ).
, Excel 97
, , .

, , AbortProc True ( , False).


.
If AbortProc Then
AbortProc = False
Exit Sub
End if

,
True AbortProc
. , AbortProc False.


, .
Excel
. ,
, Workbook_Open,
.


.
.
Worksheet_SelectionChange
Workbook_Open
Chart_Activate
Class_Initialize
,
VBE.
. 19.2 .
, Workbook .
.
, End Sub.

19. Excel

519

. 19.2.
VBE

, Workbook,
Open, VBE () :
Private Sub Workbook_Open()
End Sub

. ,
SheetActivate . , , VBE .
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
End Sub

(Sh), . Sh Object, Worksheet.


, .
, , . .
TypeName Name , .
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
MsgBox TypeName(Sh) & vbCrLf & Sh.Name
End Sub

Cancel
Boolean. , BeforePrint
.
Private Sub Workbook_BeforePrint(Cancel As Boolean)

Cancel, , False.
True, . .

520

V.

Private Sub Workbook_BeforePrint(Cancel As Boolean)


Msg = " ?"
Ans = MsgBox(Msg, vbYesNo, " ...")
If Ans = vbNo Then Cancel = True
End Sub

Workbook_BeforePrint , . , . 19.3.
, Cancel
True, .

BeforePrint
.

. 19.3.
,
Cancel

, Excel BeforePrint .
, , .

Workbook
Workbook .
. 19.1 , . Workbook ThisWorkbook ().

19.1. Workbook

Activate

AddinInstall

AddinUninstall

BeforeClose

BeforePrint

BeforeSave

Deactivate

NewSheet

Open

PivotTableCloseConnection*

PivotTableOpenConnection*

Excel 2002 .

19. Excel

521

. 19.1

SheetActivate

SheetBeforeDoubleClick

SheetBeforeRightClick

SheetCalculate

( )

SheetChange

SheetDeactivate

SheetFollowHyperlink

SheetPivotTableUpdate

WindowActivate

WindowDeactivate

WindowResize

SheetSelectionChange

, ,
Application (.
Application ). Workbook. , ,
.
, .

Open
Open
. ( ).
Workbook_Open. Workbook_Open
, :
;
;
;
;
(,
);
(,
. OnKey );
ScrollArea (
);
UserInterfaceOnly ,
.
Protect .

522

V.

<Shift>
, Workbook_Open .

Workbook_Open.
Weekday . , ,
.
, .
Private Sub Workbook_Open()
If Weekday(Now) = vbFriday Then
Msg = " . "
Msg = Msg & " ?"
MsgBox Msg, vbInformation
End If
End Sub

Activate
.
.
Private Sub Workbook_Activate()
ActiveWindow.WindowState = xlMaximized
End Sub

SheetActivate
, . ,
A1. , . VBA TypeName , , ( ).
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If TypeName(Sh) = "Worksheet" Then _
Range("A1").Select
End Sub


.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
On Error Resume Next
Range("A1").Select
End Sub

NewSheet
,
. .
, ,
. ,
A1.
Private Sub Workbook_NewSheet(ByVal Sh As Object)
If TypeName(Sh) = "Worksheet" Then _
Range("A1") = " " & Now()
End Sub

19. Excel

523

BeforeSave
BeforeSave .
, . ,
.
Workbook_BeforeSave
(SaveAsUI), . .
Private Sub Workbook_BeforeSave _
(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If SaveAsUI Then
MsgBox " ."
End If
End Sub

, Workbook_
BeforeSave.
, SaveAsUI True.
SaveAsUI;
, . Cancel True .

Deactivate
Deactivate.
.
.
Deactivate .
Private Sub Workbook_Deactivate()
Me.Windows(1).Activate
MsgBox " , !"
End Sub

.
Excel,
. .


. , , , .
Deactivate :
;
;
.
, , .
,
,
. , .

524

V.

BeforePrint
BeforePrint , ( )
. . Cancel,
True.
, ,
BeforePrint: .
Excel 2002
, . Excel 2002
. (
) .
Excel, , . BeforePrint . Workbook_BeforePrint,
, .
Private Sub Workbook_BeforePrint(Cancel As Boolean)
For Each sht In ThisWorkbook.Sheets
sht.PageSetup.LeftFooter = _
"&8" & ThisWorkbook.FullName
Next sht
End Sub


LeftFooter PageSetup FileName
( , ). ,
8 .

Excel.
, . , , "&8" 8 .
Font. ,
(
, ).

BeforePrint ( ),
.

BeforeClose
BeforeClose .
Workbook_Open. , Workbook_Open , , Workbook_BeforeClose
.
.
, Excel
(. 19.4).

19. Excel

525

. 19.4. ,
, Workbook_BeforeClose

, : BeforeClose , Workbook_BeforeClose.

:
.
Workbook_Open
, Workbook_BeforeClose . .
, .
Private Sub Workbook_Open()
Call CreateMenu
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Call DeleteMenu
End Sub

, Excel ...
, Workbook_BeforeClose .
, ,
!
Workbook_BeforeClose. , .
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim Msg As String
If Me.Saved Then
Call DeleteMenu
Exit Sub
Else
Msg = " ?"
Msg = Msg & Me.Name & "?"
Ans = MsgBox(Msg, vbQuestion + vbYesNoCancel)
Select Case Ans
Case vbYes
Me.Save
Call DeleteMenu
Case vbNo
Me.Saved = True
Call DeleteMenu
Case vbCancel
Cancel = True
End Select
End If
End Sub

526

V.

Saved Workbook
. ,
DeleteMenu, .
.
, Excel.
, , , . ,
Saved Workbook True ( )
. ,
BeforeClose .

Worksheet
Worksheet . ,
.

, , .
XLM
Excel 5/95.

19.2. Worksheet

Activate

BeforeDoubleClick

BeforeRightClick

Calculate

( )

Change

Deactivate

FollowHyperlink

PivotTableUpdate*

SelectionChange

* Excel 2002 .

,
.

,
.

Change
Change
VBA-. Change ,
.

19. Excel

527

Worksheet_Change Target Range. ,


.
, , Target.
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
MsgBox " " & Target.Address & " "
End Sub

,
Change ,
Worksheet. Excel
, .
Change ,
.
:
, ,
, , ,
Change!

Change, , ,
.
,
Change.
<Del> Change
, .
, Excel, ,
Change. ,
Change.
.
VBA , Change.
, ,
Change .

, Change Excel. Excel


2002
Change.
, .


Change
. ,
.
Worksheet_Change, Range.
, Change. , InputRange, ,

528

V.

. Change Range,
Worksheet_Change.
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim VRange As Range
Set VRange = Range("InputRange")
If Not Intersect(Target, VRange) Is Nothing Then _
MsgBox " ."
End Sub

Range, VRange.
,
. VBA Intersect, Target (
) VRange. Intersect ,
, . Intersect
Nothing, .
Not , True
,
VRange. , .
, .


( Change). CheckBox, ,
.

-.

Private Sub Worksheet_Change(ByVal Target As Excel.Range)


Dim cell As Range
Dim OldText As String, NewText As String
If CheckBox1 Then
For Each cell In Target
With cell
On Error Resume Next
OldText = .Comment.Text
If Err <> 0 Then .AddComment
NewText = OldText & " " & cell.Text & _
". " & Application.UserName & ", " & Now & vbLf
.Comment.Text NewText
.Comment.Visible = True
.Comment.Shape.Select
Selection.AutoSize = True
.Comment.Visible = False
End With
Next cell
End If
End Sub

, Worksheet_Change,
,
Target. , .
( ).

19. Excel

529

Excel ,
. ,
, ,
, , !
, .
Change Worksheet
.

- .
EnableEvents
Change.
(
).

19.1 ,
. ,
InputRange.
1 12.
19.1.
Private
Dim
Dim
Dim
Set
For

Sub Worksheet_Change(ByVal Target As Excel.Range)


VRange As Range, cell As Range
Msg As String
ValidateCode As Variant
VRange = Range("InputRange")
Each cell In Target
If Union(cell, VRange).Address = VRange.Address Then
ValidateCode = EntryIsValid(cell)
If ValidateCode = True Then
Exit Sub
Else
Msg = " " & cell.Address(False, False) & ":"
Msg = Msg & vbCrLf & vbCrLf & ValidateCode
MsgBox Msg, vbCritical, " "
Application.EnableEvents = False
cell.ClearContents
cell.Activate
Application.EnableEvents = True
End If
End If
Next cell
End Sub

Worksheet_Change Range. VRange . Target, .


, ,
, (EntryIsValid),
True .
, EntryIsValid , .
(. 19.5).
, . ,
. ,
Change .

530

V.

. 19.5.
,

EntryIsValid.
19.2.
Private Function EntryIsValid(cell) As Variant
'
True, 1 12
'
,
'

If Not WorksheetFunction.IsNumber(cell) Then


EntryIsValid = " ."
Exit Function
End If

'

?
If CInt(cell) <> cell Then
EntryIsValid = " ."
Exit Function
End If

'

?
If cell < 1 Or cell > 12 Then
EntryIsValid = " 1 12."
Exit Function
End If


EntryIsValid = True
End Function
'

SelectionChange
SelectionChange.
,
.
Private Sub Worksheet_SelectionChange(ByVal Target _
As Excel.Range)
Cells.Interior.ColorIndex = xlNone
With ActiveCell
.EntireRow.Interior.ColorIndex = 27
.EntireColumn.Interior.ColorIndex = 27
End With
End Sub

,
.
, . . 19.6 (, ).

19. Excel

531

. 19.6.

-.

, , . .

BeforeRightClick
, Excel . ,
BeforeRightClick. Cancel
True, BeforeRightClick.
, .

Private Sub Worksheet_BeforeRightClick _


(ByVal Target As Excel.Range, Cancel As Boolean)
Cancel = True
MsgBox " ."
End Sub

24 .

532

V.

Chart

,
. , .

18 Chart.
, 18 .

. 19.3 , ,
.

19.3. ,

Activate

BeforeDoubleClick

. ,

BeforeRightClick


. ,

Calculate

Deactivate

DragOver

DragPoint

MouseDown

MouseMove

MouseUp

Resize

Select

SeriesChange

Application
Workbook Worksheet.

.
,
Application.

19. Excel

533


Object Browser
, . , Object Browser , . ,
, MouseMove. VBE <F2>, Object Browser. ,
<All Libraries>, MouseMove .

Object Browser .
. , MouseMove. , , , MSForms. UserForm , MouseMove Chart.
: Library, Class Members. ,
, ,
: . .
, Object
Browser, , . , -.

Application
.

. 19.4 Application
.

534

V.

19.4. , Application

NewWorkbook
SheetActivate
SheetBeforeDoubleClick



.
,

.
,
( )




,






XML-
XML- XML-




XML- XML-

XML-







, ,

SheetBeforeRightClick

SheetCalculate
SheetChange
SheetDeactivate
SheetFollowHyperlink
SheetPivotTableUpdate*
SheetSelectionChange
WindowActivate
WindowDeactivate
WindowResize
WorkbookActivate
WorkbookAddinInstall
WorkbookAfterXMLExport**
WorkbookAfterXMLImport**
WorkbookAddinUninstall
WorkbookBeforeClose
WorkbookBeforePrint
WorkbookBeforeSave
WorkbookBeforeXMLExport**
WorkbookBeforeXMLImport**
WorkbookDeactivate
WorkbookNewSheet
WorkbookOpen
WorkBookPivotTableCloseConnection*
WorkbookPivotTableOpenConnection*
WorkbookSync**

* Excel 2002
** Excel 2003

19. Excel

535

Application
Application,
.
1. .
2. Properties. VBA
, Class1, Class2
.. .
3. Application,
WithEvents.
Public WithEvents XL As Application

4. ,
Application .
, VBA ( ).
Dim X As New clsApp

5. Application. Workbook_Open.
Set X.XL = Application

6. .


. 18.


, ,
.
, AppClass.
.
Public WithEvents AppEvents As Application
Private Sub AppEvents_WorkbookOpen _
(ByVal Wb As Excel.Workbook)
Call UpdateLogFile(Wb)
End Sub

Application, AppEvents . AppEvents_WorkbookOpen .


UpdateLogFile Wb, . VBA,
.
Sub UpdateLogFile(Wb)
On Error Resume Next
txt = Wb.FullName
txt = txt & "," & Date & "," & Time
txt = txt & "," & Application.UserName

536

V.

Fname = ThisWorkbook.Path & "\logfile.txt"


Open Fname For Append As #1
Write #1, txt
Close #1
MsgBox, txt
End Sub

AppClass (
). Init Workbook_Open,
. Workbook_Open
.
Private Sub Workbook_Open()
Call Init
End Sub

UpdateLogFile ( ,
) : , , , .
Workbook_Open Init. , Init .

-. ,
. , .

Application
, , .
- ,
Application,
(. 19.7).

. 19.7.

Application

19. Excel

537

21- ( ,
Application). .
Private Sub XL_NewWorkbook(ByVal Wb As Excel.Workbook)
LogEvent " : " & Wb.Name
End Sub

LogEvent . LogEvent.
Sub LogEvent(txt)
EventNum = EventNum + 1
With UserForm1
With .lblEvents
.AutoSize = False
.Caption = .Caption & vbCrLf & txt
.Width = UserForm1.FrameEvents.Width - 20
.AutoSize = True
End With
.FrameEvents.ScrollHeight = .lblEvents.Height + 20
.FrameEvents.ScrollTop = EventNum * 20
End With
End Sub

LogEvent UserForm,
Caption Label, lblEvents. ,
ScrollHeight ScrollTop Frame, FrameEvents. Label
Frame.

UserForm
UserForm , , , . . 19.5
UserForm, VBA.

19.5. , UserForm

Activate

AddControl

BeforeDragOver

BeforeDropOrPaste


(.. )

Click

DblClick

Deactivate

Error

Initialize

KeyDown

538

V.

. 19.5

KeyPress

KeyUp

LayOut

MouseDown

MouseMove

MouseUp

RemoveControl

Resize

Scroll

Terminate

Zoom

QueryClose

1315 .

, , (Application, Workbook, Sheet ..). , : OnTime OnKey.


Application.

, ,
OnKey OnTime , VBA
.

OnTime
OnTime .
Excel , 15:00 .
Sub SetAlarm()
Application.OnTime TimeValue("15:00:00"), "DisplayAlarm"
End Sub
Sub DisplayAlarm()
Beep
MsgBox ". !"
End Sub

19. Excel

539

SetAlarm OnTime
Application OnTime. :
( 3:00 p.m. 15:00) , (
DisplayAlarm). SetAlarm DisplayAlarm
15:00, ,
. 19.8.

. 19.8. ,


(, 20 ), .
Application.OnTime Now + TimeValue("00:20:00"), "DisplayAlarm"

OnTime ,
. DisplayAlarm
1 2004 12:01.
Application.OnTime DateSerial(2004, 4, 1) + _
TimeValue("00:00:01"), "DisplayAlarm"

OnTime .
,
.

. 1
. UpdateClock 1, 5 .
StopClock. , NextTick
, .
Dim NextTick As Date
Sub UpdateClock()
ThisWorkbook.Sheets(1).Range("A1") = Time
NextTick = Now + TimeValue("00:00:01")
Application.OnTime NextTick, "UpdateClock"
End Sub

OnTime , .
, StopClock,
(, ).
Workbook_BeforeClose .
Call StopClock

540

V.

OnKey
Excel . ,
.
OnKey OnKey.
<PgUp> <PgDn>. Setup_OnKey <PgDn> PgDn_Sub, <PgUp> PgUp_Sub. <PgDn>
, <PgUp> .
Sub Setup_OnKey()
Application.OnKey "{PgDn}", "PgDn_Sub"
Application.OnKey "{PgUp}", "PgUp_Sub"
End Sub
Sub PgDn_Sub()
On Error Resume Next
ActiveCell.Offset(1, 0).Activate
End Sub
Sub PgUp_Sub()
On Error Resume Next
ActiveCell.Offset(-1, 0).Activate
End Sub

, ,
.
. OnKey.

On Error Resume Next, . ,


,
. , ,
, ,
.
, OnKey .
Sub Cancel_OnKey()
Application.OnKey "{PgDn}"
Application.OnKey "{PgUp}"
End Sub

OnKey OnKey. Excel . ,


Excel,
<Alt+F4> ( <Alt>).

Application.OnKey "%{F4}", ""

, OnKey
, .
9.

19. Excel

541

20

...
,
Excel . ,
.
Excel
Windows

ADO
SendKeys

.

.
(, ) .

. Windows ,
.
Windows DDE (Dynamic Data Exchange
), .


Excel. ,
DOS.

.

Shell
Shell . 20.1
, Windows Character Map
( ), .

20.1. Windows
Sub RunCharMap()
On Error Resume Next
Program = "Charmap.exe"
TaskID = Shell(Program, 1)
If Err <> 0 Then
MsgBox " " & Program, vbCritical, ""
End If
End Sub

, , . 20.1.

Excel 2002 , Windows Character Map


( ) , Excel .

Shell . . Shell
( 1).
Shell ,
. , On Error , .
, VBA ,
Shell. , Shell
. Shell , .
(,
), Excel , .
Shell, VBA ,
, VBA.
, , ,
, ,
. 20.2 , , ,
Shell, .

. 20.1.
Windows Character Map
( ) Excel

544

V.

20.2.
Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long
Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, _
lpExitCode As Long) As Long
Sub RunCharMap2()
Dim TaskID As Long
Dim hProc As Long
Dim lExitCode As Long
ACCESS_TYPE = &H400
STILL_ACTIVE = &H103
Program = "Charmap.exe"
On Error Resume Next
'


TaskID = Shell(Program, 1)

'


hProc = OpenProcess(ACCESS_TYPE, False, TaskID)
If Err <> 0 Then
MsgBox " " & Program, vbCritical, ""
Exit Sub
End If
'

GetExitCodeProcess hProc, lExitCode

DoEvents
Loop While lExitCode = STILL_ACTIVE
Do

'
'

,
MsgBox Program & " "
End Sub
'


GetExitCodeProcess Do Loop. lExitCode. , lExitCode
, , VBA .

-.

API6 ShellExecute
ShellExecute Windows API, . , ,
. , ShellExecute Web- .

20.

545

API (
VBA).
Private
Alias
ByVal
ByVal
ByVal

Declare Function ShellExecute Lib "shell32.dll" _


"ShellExecuteA" (ByVal hWnd As Long, _
lpOperation As String, ByVal lpFile As String, _
lpParameters As String, ByVal lpDirectory As String, _
nShowCmd As Long) As Long

ShellExecute.
, GIF-.
Sub ShowGraphic()
Dim FileName As String
FileName = "c:\face.gif"
Call ShellExecute(0&, vbNullString, FileName, _
vbNullString, vbNullString, vbNormalFocus)
End Sub

.
Sub OpenFile()
Dim URL As String
URL = "http://www.microsoft.com"
Call ShellExecute(0&, vbNullString, URL, _
vbNullString, vbNullString, vbNormalFocus)
End Sub

. ,
.
Sub StartEmail()
Dim Addr As String
Addr = "mailto:bgates@microsoft.com"
Call ShellExecute(0&, vbNullString, Addr, _
vbNullString, vbNullString, vbNormalFocus)
End Sub


: ,
Shell . . , .

AppActivate
StartCalculator
AppActivate , (
Microsoft Calculator ()).
AppActivate .
AppActivate , Calculator () . .
Sub StartCalculator()
AppFile = "Calc.exe"
On Error Resume Next

546

V.

AppActivate "Calculator"
If Err <> 0 Then
Err = 0
CalcTaskID = Shell(AppFile, 1)
If Err <> 0 Then MsgBox " "
End If
End Sub

-.

Microsoft Office
Microsoft Office, ActivateMicrosoftApp Application. ,
Word.
Sub StartWord()
Application.ActivateMicrosoftApp xlMicrosoftWord
End Sub

Word , .
.
xlMicrosoftPowerPoint
xlMicrosoftMail
xlMicrosoftAccess
xlMicrosoftFoxPro
xlMicrosoftProject
xlMicrosoftSchedulePlus



Windows ,
. Excel
. , : , . 20.2.

. 20.2. VBA

20.

547


Shell.
,
: .
Sub ShowDateTimeDlg()
Arg = "rundll32.exe shell32.dll,Control_RunDLL timedate.cpl"
On Error Resume Next
TaskID = Shell(Arg)
If Err <> 0 Then
MsgBox (" ")
End If
End Sub

rundll32.exe.
rundll32.exe shell32.dll,Control_RunDLL _.cpl,@n,t

_.cpl. CPL .
n. CPL.

t. ( ).

, 12 ,
. 20.3 ( -).

. 20.3. Excel

Excel, Microsoft
Word. , Excel Word
. Excel , Word . ,
Visual Basic, Excel. OLE-, ActiveX-
(, Microsoft ).
.
, ,
, Chart
. , , . Access
.

548

( Excel ) ,
.
.

V.

VBA
, . Microsoft Word, ,
(
).


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


.
:
. ,
, , .



ToolsReferences VBE.
, . 20.4.
Object
Browser ( . 20.5) , .

. , Microsoft Word 8.0 Object
Library, Microsoft Word 9.0 Object Library, Microsoft Word 10.0 Object Library
Microsoft Word 11.0 Object Library.
.
Dim WordApp As New Word.Application

. 20.4.

20.

549

, .
,
. , , .
, . , Word ( Excel) ,
VBA.
. ,
, . Object
Browser Auto List Members VBE .
, .


CreateObject , GetObject .
Object.
.

. 20.5. Object Browser


550

V.

, , . , ,
Word 97 , Word.
Dim WordApp As Object
Set WordApp = CreateObject("Word.Application")

Word,
. Word 2000.
Set WordApp = CreateObject("Word.Application.9")

Windows Automation Word,


Application VBA : Word.Application. .
As Word.Application As New Word.Application, Application Word. CreateObject("Word.Application"), ,
Word Windows.
, Office.
Word 2000 Word 2003, CreateObject("Word.
Application") .
Word 2003, CreateObject("Word.Application.11"), Word 2003, .
CreateObject, ,
Word.Application Excel.Application, , .. . ,
, , .

, GetObject.
Office, , . ,
Word 97, Word 2000 Word 2002, Word 97,
. , Word.

GetObject CreateObject
VBA GetObject CreateObject ,
-.
CreateObject . , . , . , Excel XLApp
Excel.Application.
Set XLApp = CreateObject("Excel.Application")
GetObject , ,
. , , Excel
Myfile.xls. XLBook
Workbook ( Myfile.xls).
Set XLBook = GetObject("C:\Myfile.xls")

20.

551


Word
. , ,
Word ( ).
Sub GetWordVersion()
Dim WordApp As Object
Set WordApp = CreateObject("Word.Application")
MsgBox WordApp.Version
WordApp.Quit
Set WordApp = Nothing
End Sub

Word . ,
Word ,
Visible True .
WordApp.Visible = True

.
ToolsReferences Word. .
Sub GetWordVersion()
Dim WordApp As New Word.Application
MsgBox WordApp.Version
WordApp.Quit
Set WordApp = Nothing
End Sub

Word Excel
, , Word Excel. MakeMemos Word,
. ,
, . 20.6.
MakeMemos, 20.3, WordApp. 1,
Word . Message ( E6) , .

. 20.6. Word Excel

552

V.

20.3. Word Excel


Sub MakeMemos()
'
Word ( )
Dim WordApp As Object
Dim Data As Range, message As String
Dim Records As Integer, i As Integer
Dim Region As String, SalesAmt As String, SalesNum As String
Dim SaveAsName As String
'

Word
Set WordApp = CreateObject("Word.Application")

'


Set Data = Sheets("1").Range("A1")
message = Sheets("1").Range("Message")

'
'

1
Records = Application.CountA(Sheets("1").Range("A:A"))
For i = 1 To Records

Application.StatusBar = " " & i

'


Region = Data.Cells(i, 1).Value
SalesNum = Data.Cells(i, 2).Value
SalesAmt = Format(Data.Cells(i, 3).Value, "#,000")

'


SaveAsName = ThisWorkbook.Path & "\" & Region & ".doc"

'

Word
With WordApp
.Documents.Add
With .Selection
.Font.Size = 14
.Font.Bold = True
.ParagraphFormat.Alignment = 1
.TypeText Text:="M E M O A "
.TypeParagraph
.TypeParagraph
.Font.Size = 12
.ParagraphFormat.Alignment = 0
.Font.Bold = False
.TypeText Text:=":" & vbTab & _
Format(Date, "mmmm d, yyyy")
.TypeParagraph
.TypeText Text:=": " & vbTab & Region
.TypeParagraph
.TypeText Text:=":" & vbTab & _
Application.UserName
.TypeParagraph
.TypeParagraph
.TypeText message
.TypeParagraph
.TypeParagraph
.TypeText Text:=" :" & vbTab & SalesNum
.TypeParagraph
.TypeText Text:=" :" & vbTab & _
Format(SalesAmt, "$#,##0")
End With
.ActiveDocument.SaveAs FileName:=SaveAsName
End With
Next i

20.

553

'


WordApp.Quit
Set WordApp = Nothing


Application.StatusBar = ""
MsgBox Records & " " & ThisWorkbook.Path
End Sub

'

. 20.7 , MakeMemos.
.
Word. ,
, . Word
Word.
Excel. ,
With-End With. With End With
. , Word ( ) .
Documents.Add

.
With WordApp
.Documents.Add
'

End With

, Word, .
, ,
.
Immediate VBE Word.

. 20.7. Excel

554

V.

Excel
Excel (
Visual Basic Word) ,
Excel, Word.
Excel .
Application CreateObject("Excel.Application").
Workbook CreateObject("Excel.Sheet").
Chart CreateObject("Excel.Chart").
20.4 , VBA
Word 2003. Excel Worksheet ( Excel.Sheet) .
20.4. Excel Word
Sub MakeExcelChart()
Dim XLSheet As Object
'


Documents.Add

'


StartVal = InputBox(" ")
PctChange = InputBox(" ")

'

Sheet
Wbook = ThisDocument.Path & "\projections.xls"
Set XLSheet = GetObject(Wbook, "Excel.Sheet").ActiveSheet

'


XLSheet.Range("StartingValue") = StartVal
XLSheet.Range("PctChange") = PctChange
XLSheet.Calculate

'


Selection.Font.Size = 14
Selection.Font.Bold = True
Selection.TypeText " : " & _
Format(PctChange, "0.0%")
Selection.TypeParagraph
Selection.TypeParagraph

'


XLSheet.Range("data").Copy
Selection.Paste

'


XLSheet.ChartObjects(1).Copy
Selection.PasteSpecial _
Link:=False, _
DataType:=wdPasteMetafilePicture, _
Placement:=wdInLine, DisplayAsIcon:=False


Set XLSheet = Nothing
End Sub
'

20.

555

. 20.8. MakeExcelChart
.
. Excel .
. 20.9.

. 20.8. VBA Word

. 20.9. VBA Word Excel

556

V.

Outlook
Microsoft
Outlook.
. 20.10 , : , . 20.5
()
( Msg).

. 20.10. ,

20.5. Excel
Sub SendEmail()
'
' Outlook
Dim OutlookApp As Outlook.Application
Dim MItem As Outlook.MailItem
Dim cell As Range
Dim Subj As String
Dim EmailAddr As String
Dim Recipient As String
Dim Bonus As String
Dim Msg As String
' Outlook
Set OutlookApp = New Outlook.Application
'
For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
If cell.Value Like "*@*" Then
'
Subj = " "
Recipient = cell.Offset(0, -1).Value
EmailAddr = cell.Value
Bonus = Format(cell.Offset(0, 1).Value, "$0,000.")
'
Msg = " " & Recipient & vbCrLf & vbCrLf
Msg = Msg & " "
Msg = Msg & Bonus & vbCrLf & vbCrLf
Msg = Msg & " " & vbCrLf
Msg = Msg & ""
'
Set MItem = OutlookApp.CreateItem(olMailItem)
With MItem
.To = EmailAddr
.Subject = Subj
.Body = Msg
.Send
End With
End If
Next
End Sub

20.

557

,
Outlook. ,
: Outlook MailItem. .
Set OutlookApp = New Outlook.Application

MailItem .

Set Mitem = OutlookApp.CreateItem(olMailItem)

-.


Excel.

ADO
ADO (ActiveX Data Object) , , . , . .
DAO (Data Access Objects).
ADO Access.

ADO .
Excel , . , .

Access, budget.mdb. (Budget). . ,


, .
. Recordset. (. 20.11).
Sub ADO_Demo()
'

'
Microsoft ActiveX Data Objects 2.x
Dim
Dim
Dim
Dim
Dim

DBFullName As String
Cnct As String, Src As String
Connection As ADODB.Connection
Recordset As ADODB.Recordset
Col As Integer

Cells.Clear
MsgBox " _
= = . "
'


DBFullName = ThisWorkbook.Path & "\budget.mdb"

558

V.

'


Set Connection = New ADODB.Connection
Cnct = "Provider=Microsoft.Jet.OLEDB.4.0; "
Cnct = Cnct & "Data Source=" & DBFullName & ";"
Connection.Open ConnectionString:=Cnct

'

RecordSet
Set Recordset = New ADODB.Recordset
With Recordset

Src = "SELECT * FROM Budget WHERE = '' "


Src = Src & "and = '. '"
.Open Source:=Src, ActiveConnection:=Connection

'


For Col = 0 To Recordset.Fields.Count - 1
Range("A1").Offset(0, Col).Value = Recordset.Fields(Col).Name
Next

'


Range("A1").Offset(1, 0).CopyFromRecordset Recordset
End With
Set Recordset = Nothing
Connection.Close
Set Connection = Nothing
End Sub


'

, Access
-.

. 20.11. Access

20.

559


Excel
, Excel
. , VBA
. ( ) joeblow@anydomain.com.
.
Sub SendWorkbook()
ActiveWorkbook.SendMail "joeblow@anydomain.com", " "
End Sub

,
() . . 1 .
Sub SendSheet()
ActiveWorkbook.Worksheets("1").Copy
ActiveWorkbook.SendMail "joeblow@anydomain.com", " "
ActiveWorkbook.Close False
End Sub


(, Book2.xls).
, . 1 .xls.

Kill.
Sub SendOneSheet()
Dim Filename As String
FileName = " .xls"
ActiveWorkbook.Worksheets("1").Copy
ActiveWorkbook.SaveAs Filename
ActiveWorkbook.SendMail "joeblow@anydomain.com", " "
ActiveWorkbook.Close False
Kill Filename
End Sub

SendKeys
.
. Excel SendKeys,
.
, SendKeys
, .
, . , , SendKeys, . , SendKeys .
SendKeys
Windows Calculator (). TestKeys ( ).

560

V.

Sub TestKeys()
Shell "calc.exe", vbNormalFocus
AppActivate "Calculator"
Application.SendKeys "%vs", True
End Sub

<Alt+V+S> ( <Alt>). SendKeys


,
(, <Alt>).
20.7
SendKeys. ,
Outlook Express.
20.7. Excel
Sub SendEmail()
Dim cell As Range
Dim Subj As String
Dim EmailAddr As String
Dim Recipient As String
Dim Bonus As String
Dim Msg As String
Dim HLink As String
For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
If cell.Value Like "*@*" Then
'
Subj = " "
Recipient = cell.Offset(0, -1).Value
EmailAddr = cell.Value
Bonus = Format(cell.Offset(0, 1).Value, "$0,000.")
'
Msg = " " & Recipient & "%0A"
Msg = Msg & "%0A" & " "
Msg = Msg & Bonus & "%0A"
Msg = Msg & "%0A" & " "
Msg = Msg & "%0A" & ""
'
HLink = "mailto:" & EmailAddr & "?"
HLink = HLink & "subject=" & Subj & "&"
HLink = HLink & "body=" & Msg
'Send it
ActiveWorkbook.FollowHyperlink HLink
Application.Wait (Now + TimeValue("0:00:02"))
SendKeys "%s", True
End If
Next
End Sub

. 20.12 , ,
.

. 20.12. ,

20.

561

SendMail , Outlook Express


.
( Msg).
Outlook Express FollowHyperlink. .
mailto:jjones@anydomain.com?subject=Yuor Annual Bonus&body=
%0A%OA $2 000.%0A%0A
%0A

%0 .

,
SendKeys, <Alt+S> (
). ,
.
, ,
( 730 ). .
. 20.13 Outlook Express.

. 20.13. Outlook,
,

562

V.

21

...
.
, Excel.
, .
Excel.
.
XLA XLS.
VBA, .

.
Excel, ,
.
.


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


Excel
XLS.
. XLS ,
. Excel , .

IsAddin ThisWorkbook ()
True.
, . , (
).
Workbooks AddIns. Workbooks (
).
.
,
.
, ,
.

.xla. . .


,
XLS .
. , .
, , , .
.
, , , , .
XLS, .
. , ,
. ,
Newfuncs MOVAVG, .
=Newfuncs.xls!MOVAVG(A1:A50)

,
, .
MOVAVG(A1:A50)

. ,
.

564

V.

.
Excel, ,
.
. xxx?.

COM
Excel 2000 COM (Component
Object Model). DLL EXE. COM
, Office, .
, . XLA, COM Excel. COM Visual Basic 5 ( ) Office Developer Edition. COM
, .

Excel
Excel , . , . 21.1.
, Excel. , . . .

Excel 20022003 .
COM. , Excel
2000 COM,
.

. ,
.
Excel VBA,
.
, .

. 21.1.

21.

565

,
. , : Excel . , , . EuroValue. , .


, ,
.
,
, , . , ,
, . , .
.
.
1. , .
( ),
. , . 23 ,
22 .
2. , , .
,
( ).
3. VBE Project.
Toolsxxx Properties ( xxx),
Protection (). Lock project for viewing
( ) ().
OK.
, .


Microsoft Excel ,
.
Excel
. Excel 2003 ,
,
. , - ,
Excel .

566

V.

4. Excel .

. .
, ,
.
5. .
6. Microsoft Excel
.
7. .
*.xla.
.

, ,
. ,
Excel 5/95,
Microsoft Excel. ,
, .

(
Text Tools, 16).

XLS- Text Tools .


.


, .
, 1.
, .
UserForm1. . .
VBA, Module1. , FormMain.

, ThisWorkbook
(Workbook_Open Workbook_BeforeClose),
.

16
Text Tools.

21.

567


. , , ,
.
Text Tools. , . , . ,
.


.
, .
, . 21.2.
. . .
.

. 21.2.
,


, .
1. VBE .
2. DebugCompile (). VBA, . Excel , .
3. ToolsTextTools Properties ( Text Tools)
Protection () .
Lock project for viewing ( )
(). OK.
, .

568

V.

4. VBA VBProject.
TextTools.
5. .
6. .
Excel .
7. Microsoft Excel.
8. . ,
.

Excel
Excel , .
. , , .
VBA Title
AddIn AddIns. , ,
Installed True.
, . ,
. , . .
XLA: , XLS.
XLL: DLL, C.
( Excel 20022003),
COM. , ,
COM, Excel.
AddIns Add , VBA . ,
, Installed AddIn True. False .
Excel . , ,
Excel, Excel.


, XLS , .
, .
1. . Excel
.
2. ,
.
. . 21.3,

21.

569

,
.
3. OK,
.
Text Tools
, StartTextTools, .

. 21.3. ,


Excel,
XLA ( XLS ). .
.
, . , .


, ,
. , VBE Project.
.
, VBE ( FileSave
()).
, ,
IsAddIn False. Excel. Properties ThisWorkbook (. 21.4).
, IsAddIn
True. False, ( .xla). .

570

V.

. 21.4.

,

.
Excel?
VBA ?
VBAProject. .
?
?
VBA, , Private?
, .
,
?
? , , ( ).
?

.

21.

571

XLA XLS
, XLA XLS . ,
.


, XLS, ,
. VBA XLA , .


AddIns,
Workbooks. Workbooks, , .
, Myaddin.xla.
Set TestAddin = Workbook("Myaddin.xla")


Workbooks.
Workbooks, Myaddin.xla .
For Each w in Application.Workbooks
MsgBox w.Name
Next w

, For Next
Myaddin.xla (, , Excel ) .
For Each a in Application.AddIns
MsgBox a.Name
Next a

XLS .
,
.
MsgBox ActiveWorkbook.Windows.Count

XLS
Visible.
.
For Each Win In ActiveWorkbook.Windows
Win.Visible = False
Next Win

,
(). ,
. Myaddin.xla , 0.
MsgBox Workbooks("Myaddin.xla").Windows.Count

572

V.


XLS, XLS, . , ,
XLS , .
VBA , , . ,
Workbooks, , .
, A1
Myaddin.xla, .
MsgBox Workbooks("Myaddin.xla").Worksheets(1) _
.Range("A1").Value

, ,

.
,
( ).
Sub CopySheetFromAddin()
Set AddinSheet = Workbooks("Myaddin.xla").Sheets(1)
NumSheets = ActiveWorkbook.Sheets.Count
AddinSheet.Copy After:=ActiveWorkbook.Sheets(NumSheets)
End Sub

.
Sub CopySheetFromAddin()
Workbooks("Myaddin.xla").Sheets(1).Copy
End Sub

, , . VBA
ThisWorkbook, . , VBA .
A1 .
MsgBox ThisWorkbook.Sheets("1").Range("A1").Value

VBA6
VBA, , XLS.
,
, . Excel
.

,
,
. Sub , .

21.

573

,
, . : , ; ( ).
OnTime,
.
Run Application
, .
Application.Run "Myaddin.xla!DisplayNames"

ToolsReferences
VBE, . VBA, .
Run :
,
Private. DisplayNames, , ToolsReferences.
Call DisplayNames

,
XLS. , Excel
(
). ,
Private.
.
Private , , .


, .
,
( ). Object Browser.
, . Excel.
, .
1. VBE Lookup.xla Project.
2. <F2> Object Browser.
3. Libraries () lookup. .
4. Classes (), .

574

V.

, Lookup_Common , , . DoLookupCommand , . ,
Excel . DoLookupCommand . , .
VBA,
.

,
Private, .
. , ,
.
, .

, , , . ,
Newfuncs.xls MOVAVG,
.
=Newfuncs.xls!MOVAVG(A1:A50)

.
.
=MOVAVG(A1:A50)

21.

575


VBA
, VBA, .

AddIns
AddIns , Excel.
, .
,
AddIns. , .

ADDINS
, AddIns, . Excel , ,
Windows. Excel 2003 .
HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Excel\Add-in Manager

Windows (regedit.exe) . ,
, Excel, .
, , ,
( ).
Windows\Application data\Microsoft\Addins

AddIn AddIns ,
VBA.
, ,
.
AddIns VBA , Add AddIns.
Application.AddIns.Add "c:\files\newaddin.xla"

AddIns
,
. , , .
(, -), Excel Add. Myaddin.xla
A: AddIns. (
True) . , .
Application.AddIns.Add "a:\Myaddin.xla", True

576

AddIns .
,
Installed True.

V.

, Excel
. Excel
(.. ), , AddIns Excel.

ADDINS
,
AddIns. AddIns Delete Remove.
( regedit.exe). Excel. ,
.
AddIns , XLA, .
, . 21.5. AddIns.

. 21.5. AddIns

AddIn
AddIn AddIns. ,
, ,
AddIns, .
MsgBox AddIns(1).Name

AddIn 14 , . . ,
.

NAME
. Name ,
,
Name.

PATH
, , . .

FULLNAME
, ,
. ,

21.

577

Name Path. .
MsgBox AddIns(1).Path & "\" & AddIns(1).Name
MsgBox AddIns(1).FullName

TITLE
, . Title
.
,
(
). XLS ,
.
, Name.
AddIns .
Name Title.
View Manager (.. View.xls),
Title View Manager.
Sub ShowName()
MsgBox AddIns("View Manager").Name
End Sub

, , ,
.

COMMENTS
,
, . Comments .
.
255 ,
100.

INSTALLED
Installed True, (..
). Installed True .
False . (.. ) MS Query VBA.
Sub InstallQuery()
AddIns("MS Query").Installed = True
End Sub

MS Query. , Installed True - . (), Installed False.

,
. , Installed
False.

578

V.

, AddIns, , .
, , .
Sub CountInstalledAddIns()
Dim Count As Integer
Dim Item As AddIn
Dim Msg As String
Count = 0
For Each Item In AddIns
If Item.Installed Then Count = Count + 1
Next Item
Msg = ": " & AddIns.Count & Chr(13)
Msg = Msg & ": " & Count
MsgBox Msg
End Sub

AddIns
, .
, .
Sub InstallAll()
Dim Count As Integer
Dim Item As AddIn
Count = 0
For Each Item In AddIns
If Item.Installed Then
Item.Installed = False
Count = Count + 1
End If
Next Item
MsgBox " " & Count & " "
End Sub

IsAddIn ,
. , ,

IsAddIn True.


, :
.
. :
Installed True. , .
VBA. ,
Workbooks("Myaddin.xla").Close

Close ,
Installed False. ,
,
.
Installed False.

21.

579

, , Excel
.
.

AddIn
AddIn : AddInInstall ( ) AddInUninstall ( ).
,
ThisWorkbook, .
.
Private Sub Workbook_AddinInstall()
MsgBox ThisWorkbook.Name & _
" "
End Sub

AddInInstall Open. AddInInstall


.
, Workbook_Open.

19.



. .


,
, .
.
, .
Application.ScreenUpdating False.
,
. Option Explicit ,
.
, . ,
Series , .
Dim S1 As Series
Set S1 = ActiveWorkbook.Sheets(1).ChartObjects(1). _
Chart.SeriesCollection(1)

.
As Object.

580

V.

With-End With
, .
, .
, VBA, . , . . .

,
.
.
,
.


Excel ( ) . , , . , , .

.
( ),
, .
1. .
2. VBE , VBA (, , UserForm ,
, ThisWorkbook, ).
.
3. .
4.
.
( ).
5. , . 2.
6. .
7. , , .
8. .
9. , ,
.
, , . , , ,
XLA 55%.

21.

581

,

.
.
, .
, .


(
, ).
. , VBA (
AddIns)
.
21.1 (
ThisWorkbook). AddInInstall
Open.
21.1.
Dim InstalledProperly As Boolean
Private Sub Workbook_AddinInstall()
InstalledProperly = True
End Sub
Private Sub Workbook_Open()
If Not ThisWorkbook.IsAddin Then Exit Sub
'

If Not InstallProrerly Then


AddIns
If Not InAddInCollection(ThisWorkbook) Then _
AddIns.Add FileName:=ThisWorkbook.FullName

'


AddInTitle = GetTitle(ThisWorkbook)
Application.EnableEvents = False
AddIns(AddInTitle).Installed = True
Application.EnableEvents = True


Msg = ThisWorkbook.Name & _
" "
Msg = Msg & " "
MsgBox Msg, vbInformation, AddInTitle
End If
End Sub

'

, Workbook_
AddInInstall. InstalledProperly
True. , Workbook_AddInInstall , InstalledProperly
, False.

582

V.

Workbook_Open , . , .
,
InstalledProperly.
.
, AddIns.
, .
.
.
,
.

-.
,
( ).


, .
, .

. Path ,
.
, , , , .
.
Sub GetHelp()
Dim Path As String
Path = ThisWorkbook.Path
Application.Help Path & "\USER.CHM"
End Sub

API Windows,
, Windows . DLL, Windows\System ( -). System Windows API GetSystemDirectory.

Excel
,
Excel 2003, , Excel. .
Sub CheckVersion()
If Val(Application.Version) < 11 Then
MsgBox " Excel 2003 "
ThisWorkbook.Close
End If
End Sub

21.

583

Version Application . ,
11.0a. Val,
.
26.

584

V.

VI

...
22.

23.
24.
25.

22



...
.
. .
, .
Excel.
.
, VBA
.
Excel .
.
, ( , VBA). .


Excel 97, Microsoft
. , CommandBar.
, , .

, . .
. Worksheet Menu Bar
( ) Chart Menu Bar ( )
( 23).

, ( 23).

, ,
. 23 .


,
Excel.
.
, ,
.
.
.
, , . ,
, Excel.
.
.
.
.
.
, . Excel
,
.
.
.
Excel: , .

. ,
VBA.

.
, . .
.

Excel

. .


(XLS)
(XLA), (
). . , .

588

VI.

,
. .
Excel XLB, Windows XP .
\Document and Settings\< >\Application Data\Microsoft\Excel

Excel 2003 ,
XLB- Excel 2003. , .

XLB . ,
Excel, .
.
, .
Excel
XLB. (
),
Excel XLB . , XLB
Excel, Excel
XLB. , . ,
, .
.

XLB.
, Excel ,
XLB-.


Excel
. , , .
, . Excel
XLB .
- (,
),
.
, .
, , , , , . .
, VBA,
. , .

.
XLB . , . , VBA .

22.

589



Excel . VBA, .

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


( ),
Excel .
Excel .
.
.
.
Excel ,
.
. (. 22.1). .
.
. ,
. :
, .
. , .

.
. ,
.
, , .


.
, . Microsoft ,
. , .

, .

590

VI.

. 22.1.


( , ). ,
. .
.


. Excel . ( ).
. 22.2 , .
. ,
, , .


.
.
.
. 22.2. ,

22.

591


.
.



. .
,
. , , . ,
.


Excel (..
),
. ,
. . ,
<Ctrl> . , .


, (. 22.3).
17 .
. ,
. , .


, .
.
( ).

. 22.3.

592

VI.

, . 22.4.
, .

42 . , . .



. ,
, .


,
,
. ,
, . 22.5.
,
Toolbars (. ). ,
, .

. 22.4.

22.

593

,
. ,
.
.

. 22.5.

,
VBA. .

.
,
. , .

, , , , ,
. Excel .

21, .
.
.
: ,
. VBA . , . . XLS ,
,
XLS!
, , , XLS, .
.
XLS. ,

594

VI.

XLS,
. ( VBA) OnAction
, ,
, XLS. ,
, .
.

CommandBars
CommandBars, Application,
CommandBar. CommandBar
Control. , VBA.

( , ).
Excel ( ) , CommandBars.
.
63 Excel 2003.
.
. , .
. ,
.
.
61 , Excel 2003.


, ,
Type.
CommandBars . VBA , .

0
1
2

msoBarTypeNormal
msoBarTypeMenuBar
msoBarTypePopUp

CommandBar
CommandBars,
.
(. 22.6), CommandBar, CommandBars. Excel 2003 126
, . Index, Type Name (
Type ,
). , , .

22.

595

. 22.6. VBA
CommandBar
Sub ShowCommandBarNames()
Dim Row As Integer
Dim cbar As CommandBar
Cells.Clear
Row = 1
For Each cbar In CommandBars
Cells(Row, 1) = cbar.Index
Cells(Row, 2) = cbar.Name
Select Case cbar.Type
Case msoBarTypeNormal
Cells(Row, 3) = " "
Case msoBarTypeMenuBar
Cells(Row, 3) = " "
Case msoBarTypePopUp
Cells(Row, 3) = " "
End Select
Cells(Row, 4) = cbar.BuiltIn
Row = Row + 1
Next cbar
End Sub

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


VBA Add
CommandBars. ,
, (Custom 1).
CommandBars.Add

596

VI.

, ,
( Visible False).

. .
Sub CreateToolbar()
Dim TBar As CommandBar
Set TBar = CommandBars.Add
With TBar
.Name = ""
.Top = 0
.Left = 0
.Visible = True
End With
End Sub

CreateToolbar Add CommandBars Tbar, . , .


Top Left , , Excel.

CommandBars
UserForm , ,
Application.
Application.CommandBars.Add
VBA ,
.


CommandBar
Index Name. , Standard
() Index, 3. .
CommandBars(3)
CommandBars("Standard")

, . ,
, Standard, standard STANDARD.

Excel
Index ( ). , Excel 2002 3-D Settings ( ) Index, 58. Excel 2000 58 Index WordArt. Excel, Name, Index.

22.

597


, , ( ) .
, .
CommandBars("").Delete

,
.
, , . ,
. ,
.
On Error Resume Next
CommandBars("").Delete
On Error GoTo 0

, CommandBars. CommandBar
( ) True,
.
CommandBars , ,
.
Function CommandBarExists(n) As Boolean
Dim cb As CommandBar
For Each cb In CommandBars
If UCase(cb.Name) = UCase(n) Then
CommandBarExists = True
Exit Function
End If
Next cb
CommandBarExists = False
End Function


CommandBar.
BuiltIn . True,
Excel .
Left ( ).
Name .
Position , .
.
msoBarLeft .
msoBarTop .
msoBarRight .
msoBarBottom .
msoBarFloating ().
msoBarPopup .

598

VI.

Protection , .
.
msoBarNoProtection ( ) .
.
msoBarNoCustomize .
msoBarNoResize .
msoBarNoMove .
msoBarNoChangeVisible
.
msoBarNoChangeDock
.
msoBarNoVerticalDock
.
msoBarNoHorizontalDock .
Top ( ).
Type , .
.
msoBarTypeNormal .
msoBarTypeMenuBar .
msoBarTypePopUp .
Visible True .
VBA, ,
.


, . CommandBars
,
BuiltIn True.
Function CustomToolbars()
Dim cb As CommandBar
Dim Count As Integer
Count = 0
For Each cb In CommandBars
If cb.Type = msoBarTypeNormal Then
If Not cb.BuiltIn Then
Count = Count + 1
End If
End If
Next cb
CustomToolbars = Count
End Function

22.

599


Protection CommandBar
.
Protection .
CommandBars("").Protection = msoBarNoCustomize


.
, Protection,
, . , .
Set cb = CommandBars("")
cb.Protection = msoBarNoCustomize + msoBarNoMove


Excel
( ).
. ,
Chart () , . , .
Microsoft (toolbar autosensing). .
, , (autosensing) .

, ,
. ,
.


. , ,
. Excel
.
, 22.1, . SelectionChange
ToolbarRange.
, . . , ,
.
, Workbook_Open,
Autosense. , , Button1, Button2, Button3 Button4. ,
( ).

600

VI.

22.1. ,

Sub CreateToolbar()
'
AutoSense
Dim AutoSense As CommandBar
Dim Button As CommandBarButton
Dim i As Integer
'


On Error Resume Next
CommandBars("AutoSense").Delete
On Error GoTo 0


Set AutoSense = CommandBars.Add
For i = 1 To 4
Set Button = AutoSense.Controls.Add(msoControlButton)
With Button
.OnAction = "Button" & i
.FaceId = i + 37
End With
Next i
AutoSense.Name = "AutoSense"
End Sub

'

SelectionChange (
Sheet1) .
Private Sub Worksheet_SelectionChange(ByVal Target As _
Excel.Range)
If Union(Target, Range("ToolbarRange")).Address = _
Range("ToolbarRange").Address Then
CommandBars("AutoSense").Visible = True
Else
CommandBars("AutoSense").Visible = False
End If
End Sub

.
, ToolbarRange, Visible AutoSense True.
Visible False.
, Workbook_BeforeClose,
AutoSense . ,
, .

, Excel, 19.

( )

Excel
. , , .

, .

22.

601

, ,
. HideAllToolbars Workbook_Open.
RestoreToolbars
Workbook_BeforeClose.
, ,
TBSheet. ,
RestoreToolbars .
,
VBA ( ). 22.2.
22.2.

Sub HideAllToolbars()
Dim TB As CommandBar
Dim TBNum As Integer
Dim TBSheet As Worksheet
Set TBSheet = Sheets("TBSheet")
Application.ScreenUpdating = False
'


TBSheet.Cells.Clear

'

TBNum = 0
For Each TB In CommandBars
If TB.Type = msoBarTypeNormal Then
If TB.Visible Then
TBNum = TBNum + 1
TB.Visible = False
TBSheet.Cells(TBNum, 1) = TB.Name
End If
End If
Next TB
Application.ScreenUpdating = True
End Sub
Sub RestoreToolbars()
Dim TBSheet As Worksheet
Dim cell As Range
Set TBSheet = Sheets("TBSheet")
Application.ScreenUpdating = False

On Error Resume Next
For Each cell In TBSheet.Range("A:A") _
.SpecialCells(xlCellTypeConstants)
CommandBars(cell.Value).Visible = True
Next cell
Application.ScreenUpdating = True
End Sub
'

602

,
.
.
Enabled False
, .

VI.


CommandBar, ,
CommandBarControl. Controls CommandBar.
Button. (CommandBarButton).
ComboBox. (CommandBarComboBox).
Menu. (CommandBarPopup).
Test Caption
Control, Standard
(). CommandBar 3.
Sub Test()
MsgBox CommandBars(3).Controls(1).Caption
End Sub

,
. 22.7 (, Standard ()
).
, , (
).

. 22.7.
Caption

,
Caption.
, .
Sub Test2()
MsgBox CommandBars("Standard").Controls("").Caption
End Sub


. , , , , Excel. FindControl, Id.
23.

Caption , ,
(&). , , (, &). Caption .

Control Control.
, Drawing
() (
). Control,
Control, 23, .

22.

603


Caption Control,
CommandBar.
Standard ().
Sub ShowControlCaptions()
Dim Cbar as CommandBar
Set CBar = CommandBars("Standard")
Cells.Clear
Row = 1
For Each ctl In CBar.Controls
Cells(Row, 1) = ctl.Caption
Row = Row + 1
Next ctl
End Sub

ShowControlCaptions . 22.8.

.
(.. Type 1), Caption
.
ShowAllToolbarControls
. 22.9.

. 22.8. , Standard ()

604

. 22.9.

VI.

Sub ShowAllToolbarControls()
Dim row As Integer
Dim Cbar As CommandBar
Dim ctl As CommandBarControl
Cells.Clear
row = 1
For Each Cbar In CommandBars
If Cbar.Type = msoBarTypeNormal Then
Cells(row, 1) = Cbar.Name
For Each ctl In Cbar.Controls
Cells(row, 2) = ctl.Caption
row = row + 1
Next ctl
End If
Next Cbar
End Sub


CommandBar, Add Controls. . Type
,
msoControlButton, .
CommandBars("").Controls.Add _
Type:=msoControlButton

, ,
. .
,
.
, FaceId,
OnAction .
Sub AddButton()
Dim NewBtn As CommandBarButton
Set NewBtn = CommandBars("").Controls.Add _
(Type:=msoControlButton)
With NewBtn
.FaceId = 300
.OnAction = ""
.Caption = " "
End With
End Sub

AddButton (NewBtn), . With-With End


.
,
.
Sub AddButton()
With CommandBars("").Controls.Add _
(Type:=msoControlButton)
.FaceId = 300
.OnAction = ""
.Caption = " "
End With
End Sub

22.

605


CommandBar, Delete Controls.
.
CommandBars("").Controls(1).Delete

, , .
,
.
CommandBars("").Controls("").Delete


,
, .
.
BeginGroup True, .
BuiltIn True,
Excel (
).
Caption
. ,
.
Enabled True,
.
FaceId , ,
.
Id Excel (
).
OnAction VBA,
.
State .
CommandBarButton.
Style
.
CommandBarButton CommandBarComboBox.
ToolTipText ,
.
Type , .

STYLE
Style ( CommandBarButton CommandBarComboBox).
.

606

VI.

, ,
Style msoButtonIconAndCaption. Style CommandBarButton:
msoButtonAutomatic;
msoButtonCaption;
msoButtonIcon;
msoButtonAndCaption;
msoButtonIconAndCaptionBelow;
msoButtonAndIconAndWrapCaption;
msoButtonAndIconAndWrapCaptionBelow;
msoButtonWrapCaption.

CommandBarComboBox msoComboLabel msoComboNormal.


. 22.10 , ( ). .

, , -.

. 22.10. Style ()

, ,
Caption .
FaceId.


Excel ,

. 42 , . ,
.
VBA.
( ),
, FaceId. , Style
, msoButtonCaption.
FaceId
45,
.
CommandBars("").Controls(1).FaceId = 45

22.

607

, ,
FaceId.
FaceId . 22.3
200 . , ,
200 .

.

22.3.
Dim ButtonGroup As Long
Sub ShowFaceIDs()
Dim NewToolbar As CommandBar
Dim NewButton As CommandBarButton
Dim SetNum As CommandBarComboBox
Dim i As Integer
'


On Error Resume Next
Application.CommandBars("FaceIds").Delete
On Error GoTo 0
ButtonGroup = 1

'


Set NewToolbar = Application.CommandBars.Add _
(Name:="FaceIds", temporary:=True)
NewToolbar.Visible = True

'

200
For i = 1 To 200
Set NewButton = NewToolbar.Controls.Add _
(Type:=msoControlButton, ID:=2950)
Next i

'


Set SetNum = NewToolbar.Controls.Add(Type:=msoControlDropdown)
For i = 1 To 51
SetNum.AddItem "Set " & i
Next i
With SetNum
.ListIndex = ButtonGroup
.Caption = "Button Set Number"
.OnAction = "NewButtons"
End With
NewToolbar.Width = 400


Call NewButtons
End Sub
'

Sub NewButtons()
'

Dim i As Long
ButtonGroup = CommandBars("FaceIds").Controls("Button Set _
Number").ListIndex
For i = 1 To 200
With CommandBars("FaceIds").Controls(i)
.FaceId = (ButtonGroup - 1) * 200 + i

608

VI.

.Caption = "FaceID = " & (ButtonGroup - 1) * 200 + i


.OnAction = "EmptySub"
End With
Next i
End Sub
Sub EmptySub()
End Sub

. 22.11 , ShowFaceIDs.
ShowFaceIDs .
NewButtons, FaceId . .
NewButtons.
ButtonGroup .

-.


Excel
, . . 22.12 .
.
.

Excel 2003 ,
.

. 22.11.
,
200

. 22.12.

22.

609


22.4 ,
. (. 22.13). Worksheet . SelectionChange,
, .

. 22.13.

22.4.
Sub MakeNumberFormatDisplay()
Dim TBar As CommandBar
Dim NewBtn As CommandBarButton
'


On Error Resume Next
CommandBars(" ").Delete
On Error GoTo 0

'


Set TBar = CommandBars.Add
With TBar
.Name = " "
.Visible = True
End With

()
Set NewBtn = CommandBars(" ").Controls.Add _
(Type:=msoControlButton)
With NewBtn
.Caption = ""
.OnAction = "ChangeNumFormat"
.TooltipText = " "
.Style = msoButtonCaption
'.Width = 100
End With
Call UpdateToolbar
End Sub

'

19.

610

VI.

UpdateToolbar, ,
NumberFormat ActiveCell Caption ( ).
Sub UpdateToolbar()
On Error Resume Next
CommandBars(" "). _
Controls(1).Caption = ActiveCell.NumberFormat
If Err <> 0 Then CommandBars(" "). _
Controls(1).Caption = ""
End Sub

OnAction ()
ChangeNumFormat, .
Excel (. 22.14).

. 22.14.


Sub ChangeNumFormat()
Application.Dialogs(xlDialogFormatNumber).Show
Call UpdateToolbar
End Sub

, , ,
:
Formatting (),
, , .


Excel .
.
OnAction.
Sort Ascending ( )
.
CommandBars("Standard").Controls("Sort Ascending") _
.OnAction = "ShowMsg"

Sort Ascending (
) . VBA ShowMsg.

22.

611

,
OnAction .
CommandBars("Standard").Controls("Sort Ascending") _
.OnAction = ""


Execute.
, . , Sort Ascending ( )
Standard ().
CommandBars("Standard").Controls("Sort Ascending").Execute

Execute
,
OnAction.




, . Type.
, .
, :
msoControlButton ;
msoControlEdit ;
msoControlComboBox ;
msoControlDropdown ;
msoControlButtonPopup ,
.
, .

Type Control . ,
.

MonthList 22.5 ,

. , OnAction,
( ) , . , , . 22.15.

612

VI.

. 22.15.
( ),

22.5.
Sub MonthList()
Dim TBar As CommandBar
Dim NewDD As CommandBarControl
'


On Error Resume Next
CommandBars(" ").Delete
On Error GoTo 0

'


Set TBar = CommandBars.Add
With TBar
.Name = " "
.Visible = True
End With

'

DropDown
Set NewDD = CommandBars(" ").Controls.Add _
(Type:=msoControlDropdown)
With NewDD
.Caption = "DateDD"
.OnAction = "PasteMonth"
.Style = msoButtonAutomatic


For i = 1 To 12
.AddItem Format(DateSerial(1, i, 1), "mmmm")
Next i
.ListIndex = 1
End With
End Sub
'

22.

613

PasteMonth.
Sub PasteMonth()
'

On Error Resume Next
With CommandBars(" ").Controls("DateDD")
ActiveCell.Value = .List(.ListIndex)
End With
End Sub

:
, Worksheet_SelectionChange.
, , , . , . ,
ListIndex .
Private Sub Worksheet_SelectionChange(ByVal Target _
As Excel.Range)
For i = 1 To 12
Set ActCell = Target.Range("A1")
If ActCell.Value = Format(DateSerial(1, i, 1), _
"mmmm") Then
CommandBars(" ").Controls("DateDD") _
.ListIndex = i
Exit Sub
End If
Next i
End Sub

614

VI.

23


...
Windows ,
. Windows
. , . , .
.
Excel.
, .
VBA.
, .
( ) .
.
.
Excel ,
, . , Excel.

Excel
22, , (
) CommandBar, , 22,
.
?
Excel,
. . ( , ),
, .
,
. .
, .
.

Excel 2003 ,
.
, VBA-.
Application.CommandBars.DisableAskQuestionDropDown = False

Excel

Excel . , , . , . , ,
.
, Excel, ,
. ,
Excel . Excel
: VBA.
Excel ,
. Excel.
, , XLB.
XLB 22.

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

, .
. ,
, .
CommandBar Microsoft Office.
. , . Excel : ,
,
.
. . ,
Excel .
() . , ,
. , . .
. ,
.
.

616

VI.

. , .
, .
() . ,
. ,
: , , .
. ,
. .
. , .
, .
.
. , . , .
. ,
. VBA , FaceID.
. ,
.
. , <Ctrl+S>
,
.


Excel: ,
. ,
,
. , . ,
. , Excel
. .

, ,
.
, , , , , . ,
, ,
<Ctrl+N>, ( Excel 20022003)
.

Excel 5/95
Excel 5 Excel 95, . Excel 97,
.
.
, .

23.

617

, . (VBA)
(command bar).
Excel 5/95. ,
.
, Excel 5/95, , , Excel 97 . Excel 5/95.
VBA .
Excel 5/95 . VBA,
.
Excel 2000 , . ,
Microsoft. , . ,
.


. ,

, . , ,
Excel, , , .
Excel .


Excel ,
. ,
. , .
,
(, (?) , ).

CommandBars
CommandBars Application.
VBA Application
( ). , (
VBA ) CommandBars.
MsgBox CommandBars(1).Name
CommandBars Application, .
MsgBox Application.CommandBars(1).Name

618

Excel . Excel , , .
, , ,
. ,
FindControl .

VI.

VBA,
.
22 .

VBA
VBA,
Excel.


ListMenuInfo, ,
. (, ,
), .
Sub ListMenuInfo()
Dim row As Integer
Dim Menu As CommandBarControl
Dim MenuItem As CommandBarControl
Dim SubMenuItem As CommandBarControl
row = 1
On Error Resume Next
For Each Menu In CommandBars(1).Controls
For Each MenuItem In Menu.Controls
For Each SubMenuItem In MenuItem.Controls
Cells(row, 1) = Menu.Caption
Cells(row, 2) = MenuItem.Caption
Cells(row, 3) = SubMenuItem.Caption
row = row + 1
Next SubMenuItem
Next MenuItem
Next Menu
End Sub

On Error Resume Next


, ,
.
. 23.1 ListMenuInfo.

, ,
-.


VBA
. CommandBars, .
: CommandBars("Worksheet Menu Bar").
: CommandBars(1).

23.

619

. 23.1. ,
ListMenuItem

VBA Add
Controls. ; msoControlPopup.
. , .
.
1. Add ,
. Add , (
), ,
( Excel).
2. . , Caption OnAction.


, Windows
. ,
, ,
, . .
, ,
.
.
.

620

VI.

.
, .
.
( ),
.
, , (...).
. . , ,
.
, , . VBA, ( ), Enabled False.
. ,
.

:

. .
Sub AddNewMenu()
Dim HelpIndex As Integer
Dim NewMenu As CommandBarPopup
'

?
HelpIndex = CommandBars(1).Controls("Help").Index

'


Set NewMenu = CommandBars(1).Controls.Add _
(Type:=msoControlPopup, _
Before:=HelpIndex, _
Temporary:=True)


NewMenu.Caption = "&"
End Sub

'

.
, ,
.
, ?. .
, ? Help. Excel
( ).

:
23.1 .
FindControl, .
, .

23.

621

23.1. Excel
Sub AddNewMenu()
Dim HelpMenu As CommandBarControl
Dim NewMenu As CommandBarPopup
Dim MenuItem As CommandBarControl
Dim Submenuitem As CommandBarButton
'

,
Call DeleteMenu

'


Set HelpMenu = CommandBars(1).FindControl(Id:=30010)

'

'

If HelpMenu Is Nothing Then



Set NewMenu = CommandBars(1).Controls.Add _
(Type:=msoControlPopup, _
temporary:=True)
Else
Help
Set NewMenu = CommandBars(1).Controls.Add _
(Type:=msoControlPopup, _
Before:=HelpMenu.Index, _
temporary:=True)
End If


NewMenu.Caption = "&"
End Sub

'

( ).

.

FindControl,
ID .
Excel CommandBar ID.
ID .
MsgBox CommandBars(1).Controls("").ID

30010 ID,
FindControl. . 23.1
ID Excel.

23.1. ID Excel

File ()
Edit ()
View ()
Insert ()
Format ()
Tools ()
Data ()
Chart ()
Window ()
Help ()

30002
30003
30004
30005
30006
30007
30011
30022
30009
30010

622

VI.


, Delete.
. On Error Resume Next, , .
Sub DeleteMenu()
On Error Resume Next
CommandBars(1).Controls("").Delete
End Sub


.
NewMenu.Caption = "&"


, . 23.2 ,
.
23.2.
Sub CreateMenu()
Dim HelpMenu As CommandBarControl
Dim NewMenu As CommandBarPopup
Dim MenuItem As CommandBarControl
Dim Submenuitem As CommandBarButton
'

,
Call DeleteMenu

'


Set HelpMenu = CommandBars(1).FindControl(Id:=30010)

'

'

If HelpMenu Is Nothing Then



Set NewMenu = CommandBars(1).Controls.Add _
(Type:=msoControlPopup, _
temporary:=True)
Else

Set NewMenu = CommandBars(1).Controls.Add _
(Type:=msoControlPopup, _
Before:=HelpMenu.Index, _
temporary:=True)
End If

'


NewMenu.Caption = "&"

'


Set MenuItem = NewMenu.Controls.Add _
(Type:=msoControlButton)
With MenuItem
.Caption = "& ..."
.FaceId = 162
.OnAction = "Macro1"
End With

23.

623

'


Set MenuItem = NewMenu.Controls.Add _
(Type:=msoControlButton)
With MenuItem
.Caption = "& ..."
.FaceId = 590
.OnAction = "Macro2"
End With

'


Set MenuItem = NewMenu.Controls.Add _
(Type:=msoControlPopup)
With MenuItem
.Caption = " &"
.BeginGroup = True
End With

'


Set Submenuitem = MenuItem.Controls.Add _
(Type:=msoControlButton)
With Submenuitem
.Caption = " "
.FaceId = 420
.OnAction = "Macro3"
End With

'

SECOND SUBMENU ITEM


Set Submenuitem = MenuItem.Controls.Add _
(Type:=msoControlButton)
With Submenuitem
.Caption = " &"
.FaceId = 422
.OnAction = "Macro4"
End With

End Sub

CreateMenu , . 23.2.
, .

. 23.2. VBA
,

624

:
. .
,
( ). , , , .

VI.

CreateMenu .
msoControlButton,
. msoControlPopup, . , MenuItem CommandBarControl.
BeginGroup True, .
.
FaceID ( ), . FaceID
.
, Caption, (&)
.

.


23.2
.
Excel, , .
Excel 5 Excel 95
. , Excel 97.
VBA,
Excel .
23.3
. ClearAllButFormulas.
23.3.
Sub AddMenuItem()
Dim ToolsMenu As CommandBarPopup
Dim NewMenuItem As CommandBarButton
'

,
Call DeleteMenuItem


Set ToolsMenu = CommandBars(1).FindControl(Id:=30007)
If ToolsMenu Is Nothing Then
MsgBox " ."
Exit Sub
Else
Set NewMenuItem = ToolsMenu.Controls.Add _
(Type:=msoControlButton)
With NewMenuItem
.Caption = " & "
.FaceId = 348
.OnAction = "ClearAllButFormulas"
.BeginGroup = True
End With
End If
End Sub

'

23.

625

. 23.3 . ,
.
ID ( 30007).

-.

. 23.3.


,
Delete Controls.
. , FindControl , .
Sub DeleteMenuItem()
On Error Resume Next
CommandBars(1).FindControl(Id:=30007). _
Control(" & ").Delete
End Sub


Excel
. , .
,
ShortcutText. ,
ShortcutText .
. , VBA.
23.4 .
, ShortcutText
"Ctrl+Shift+C". MacroOptions, .

626

VI.

23.4.
Sub AddMenuItem()
Dim ToolsMenu As CommandBarPopup
Dim NewMenuItem As CommandBarButton
'

,
Call DeleteMenuItem

'


Set ToolsMenu = CommandBars(1).FindControl(Id:=30007)
If ToolsMenu Is Nothing Then
MsgBox " - Ctrl+Shift+C."
Exit Sub
Else
Set NewMenuItem = ToolsMenu.Controls.Add _
(Type:=msoControlButton)
With NewMenuItem
.Caption = " &, "
.FaceId = 348
.ShortcutText = "Ctrl+Shift+C"
.OnAction = "ClearAllButFormulas"
.BeginGroup = True
End With
End If

'


Application.MacroOptions _
Macro:="ClearAllButFormulas", _
HasShortcutKey:=True, _
ShortcutKey:="C"

End Sub

, . 23.4.

. 23.4. ,

23.

627


. VBA, .
, , .
: ,
. .
Workbook_Open,
.
, , .
, , Excel,
. Power Utility Pak ,
PUP 2000 . ,
.
<Ctrl+Shift+U>,
PUP 2000.
CreateMenu <Ctrl+Shift+U>.
Application.MacroOptions Macro:="CreateMenu", _
HasShortcutKey:=True, ShortcutKey:="U"

, .
, ,
, ,
Excel. ,
.
, , Excel.
, , , .
19.


, , Open Workbook. , , CreateMenu.
Private Sub Workbook_Open()
Call CreateMenu
End Sub

, , .
, DeleteMenu.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Call DeleteMenu
End Sub

628

VI.

,
. ...?
, BeforeClose, Workbook_BeforeClose . , ,
, !
Excel
, .
Workbook_BeforeClose.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Not Me.Saved Then
Msg = " "
Msg = Msg & Me.Name & "?"
Ans = MsgBox(Msg, vbQuestion + vbYesNoCancel)
Select Case Ans
Case vbYes
Me.Save
Case vbNo
Me.Saved = True
Case vbCancel
Cancel = True
Exit Sub
End Select
End If
Call DeleteMenu
End Sub

, .
, . DeleteMenu, . , , ,
Excel. ,
, , .
, Saved True
( ) .
, BeforeClose ,
.


, - . . Excel , .
, , .
VBA,
, . ,
.
.
.
Private Sub Workbook_Open()
Call AddMenu
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Call DeleteMenu
End Sub

23.

629

Private Sub Workbook_Activate()


Call UnhideMenu
End Sub
Private Sub Workbook_Deactivate()
Call HideMenu
End Sub

, AddMenu.
, DeleteMenu. , . UnhideMenu , ,
HideMenu , .
HideMenu Visible False, . UnhideMenu .
, . , , Caption , .
Sub UnhideMenu()
CommandBars(1).Controls("").Visible = True
End Sub
Sub HideMenu()
CommandBars(1).Controls("").Visible = False
End Sub

, ,
Visible Enabled.

-.


Excel
. , , .
, .
, .
.
. 23.5 , , . , . State .

. ,
, ,
. .

630

VI.


AddMenuItem, 23.5,
. .

. 23.5.
,

23.5. Excel
Dim AppObject As New XLHandler
Sub AddMenuItem()
Dim ViewMenu As CommandBarPopup
Dim NewMenuItem As CommandBarButton
'

,
Call DeleteMenuItem

'


Set ViewMenu = CommandBars(1).FindControl(ID:=30004)
If ViewMenu Is Nothing Then
MsgBox " ."
Exit Sub
Else
Set NewMenuItem = ViewMenu.Controls.Add _
(Type:=msoControlButton)
With NewMenuItem
.Caption = "& "
.OnAction = "ToggleGridlines"
End With
End If


Set AppObject.AppEvents = Application
End Sub
'

AddMenuItem ,
. ,
( ).
: AddMenuItem
, .
, XLHandler, .
Public WithEvents AppEvents As Application
Private Sub AppEvents_SheetActivate(ByVal Sh As Object)
Call CheckGridlines
End Sub

23.

631

Private Sub AppEvents_WorkbookActivate(ByVal Wb As Excel.Workbook)


Call CheckGridlines
End Sub
Private Sub AppEvents_WindowActivate _
(ByVal Wb As Workbook, ByVal Wn As Window)
Call CheckGridlines
End Sub

: .


CheckGridlines
. .
Sub CheckGridlines()
Dim TG As CommandBarButton
On Error Resume Next
Set TG = CommandBars(1).FindControl(ID:=30004). _
Controls("& ")
If ActiveWindow.DisplayGridlines Then
TG.State = msoButtonDown
Else
TG.State = msoButtonUp
End If
End Sub

State . ,
. ,
.


, OnAction ,
ToggleGridlines, .
Sub ToggleGridlines()
If TypeName(ActiveSheet) = "Worksheet" Then
ActiveWindow.DisplayGridlines = _
Not ActiveWindow.DisplayGridlines
Call CheckGridlines
End If
End Sub

.
If-Then ,
.

632

VI.



Excel 97, ,
.
, .
, . 23.6.
. VBA
, .
, .
. .
1, 2 3. 1 . 2 . 3 .
, .
, ( ).
. ,
. ,
(&).
/.
,
. ,
.
, .
. ,
.
FaceID. ,
, .

. 23.6.

23.

633

. 23.7 , ,
.

, ,
-. VBA,
. , , .

. 23.7. , ,

1. , .
2. Module1 .
3. , ,
.
Private Sub Workbook_Open()
Call CreateMenu
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Call DeleteMenu
End Sub

4. .

.
5. , .

,

.



Excel .
MakeMenuBar 23.6 , . . ( ). : (?).

634

VI.

23.6. Excel
Sub MakeMenuBar()
Dim NewMenuBar As CommandBar
Dim NewMenu As CommandBarControl
Dim NewItem As CommandBarControl
'

,
Call DeleteMenuBar

'


Set NewMenuBar = CommandBars.Add(MenuBar:=True)
With NewMenuBar
.Name = " "
.Visible = True
End With

'

File (ID=30002)
CommandBars("Worksheet Menu Bar").FindControl(ID:=30002).Copy _
Bar:=CommandBars(" ")

'


Set NewMenu = NewMenuBar.Controls.Add _
(Type:=msoControlPopup)
NewMenu.Caption = "&"

'


Set NewItem = NewMenu.Controls.Add(Type:=msoControlButton)
With NewItem
.Caption = "& "
.OnAction = "DeleteMenuBar"
End With


Set NewItem = NewMenu.Controls.Add(Type:=msoControlButton)
With NewItem
.Caption = "&"
.OnAction = "ShowHelp"
End With
End Sub
'

. 23.8 .
, , . Set NewMenuBar = CommandBars.Add(MenuBar:=True)
. Visible
True, .
.

( 22)
Type, msoBarTypeNormal.
, , Type, msoBarTypeMenuBar.

. 23.8.

23.

635


. (DeleteMenuBar) .
Sub DeleteMenuBar()
On Error Resume Next
CommandBars(" ").Delete
On Error GoTo 0
End Sub

FindControl.
Copy.
CommandBars("Worksheet Menu Bar").FindControl(ID:=30002).Copy _
Bar:= CommandBars ("My Menu Bar")

, ( )
. , . ,
Caption MyMenuBar (
New () New Workbook ( )). .
.


, Excel.
Excel
.
VBA.
, Type
msoBarTypePopup.
, Index Name. .
.
Index Name,
.
Sub ListShortCutMenus()
Dim Row As Long, Col As Integer
Dim cbar As CommandBar
Cells.Clear
Application.ScreenUpdating = False
Row = 1
For Each cbar In CommandBars
If cbar.Type = msoBarTypePopup Then
Cells(Row, 1) = cbar.Index
Cells(Row, 2) = cbar.Name
For Col = 1 To cbar.Controls.Count
Cells(Row, Col + 2) = _
cbar.Controls(Col).Caption
Next Col
Row = Row + 1
End If
Next cbar
Cells.EntireColumn.AutoFit
End Sub

636

VI.

. 23.9 .
. , , ,
, Ply?

,
Index, .
Index Excel.
Name.



.
Cell (), , , . , .
Sub AddItemToShortcut()
Set NewItem = CommandBars("Cell").Controls.Add
With NewItem
.Caption = " "
.OnAction = "ToggleWordWrap"
.BeginGroup = True
End With
End Sub

. 23.9. , ,

23.

637

ToggleWordWrap.
. 23.10 .
OnAction
. OnAction. . ,
.
Sub AddItemToShortcut()
Set NewItem = CommandBars("Document").Controls.Add(ID:=865)
NewItem.Caption = " "
End Sub

. 23.10.

.
ID, 865,
.
MsgBox CommandBars("Worksheet Menu Bar") _
.Controls("").Controls("").ID


Delete ,
.
Sub RemoveItemFromShortcut()
On Error Resume Next
CommandBars("Cell").Controls(" ").Delete
End Sub

On Error Resume Next


, , .
:
,
.

638

VI.

Sub RemoveHideMenuItems()
CommandBars("Column").Controls("").Delete
CommandBars("Row").Controls("").Delete
End Sub



, .
, - ,
.
Row () Column ().
Sub DisableHideMenuItems()
CommandBars("Column").Controls("").Enabled = False
CommandBars("Row").Controls("").Enabled = False
End Sub


. , , . DisableCell
Cell ().
.
Sub DisableCell()
CommandBars("Cell").Enabled = False
End Sub

,
.
Sub DisableAllShortcutMenus()
Dim cb As CommandBar
For Each cb In CommandBars
If cb.Type = msoBarTypePopup Then _
cb.Enabled = False
Next cb
End Sub

. ,
Excel. , Enabled True.


Reset
( ). ,
. , .
Cell ()
.
Sub ResetCellMenu()
CommandBars("Cell").Reset
End Sub

23.

639


. 23.7 , MyShortcut
. OnAction , ,
. , ShowNumberFormat .
23.7.
Sub CreateShortcut()
Dim myBar As CommandBar
Dim myItem As CommandBarControl
DeleteShortcut
Set myBar = CommandBars.Add _
(Name:="MyShortcut", Position:=msoBarPopup, Temporary:=True)
Set myItem = myBar.Controls.Add(Type:=msoControlButton)
With myItem
.Caption = "& ..."
.OnAction = "ShowFormatNumber"
.FaceId = 1554
End With
Set myItem = myBar.Controls.Add(Type:=msoControlButton)
With myItem
.Caption = "&..."
.OnAction = "ShowFormatAlignment"
.FaceId = 217
End With
Set myItem = myBar.Controls.Add(Type:=msoControlButton)
With myItem
.Caption = "&..."
.OnAction = "ShowFormatFont"
.FaceId = 291
End With
Set myItem = myBar.Controls.Add(Type:=msoControlButton)
With myItem
.Caption = "&..."
.OnAction = "ShowFormatBorder"
.FaceId = 149
.BeginGroup = True
End With
Set myItem = myBar.Controls.Add(Type:=msoControlButton)
With myItem
.Caption = "&..."
.OnAction = "ShowFormatPatterns"
.FaceId = 1550
End With
Set myItem = myBar.Controls.Add(Type:=msoControlButton)
With myItem
.Caption = "&..."
.OnAction = "ShowFormatProtection"
.FaceId = 2654
End With
End Sub

640

VI.

. 23.11 .
,
ShowPopup. ,
, ,
.
Private Sub Worksheet_BeforeRightClick(ByVal Target _
As Excel.Range, Cancel As Boolean)
If Union(Target.Range("A1"), Range("data")).Address = _
Range("data").Address Then
CommandBars("MyShortcut").ShowPopup
Cancel = True
End If
End Sub

. 23.11. VBA

, ,
,
MyShortcut. Cancel True ,
.

- Cell ().

23.

641

24



...
, Excel.
.
.
, Excel.

Windows HTML.
.
Office .
.
.
-
. , , .
.

( )!

Excel
Excel ,

. , ,
. ( ).

, . ,
, ,
,
. . .
, .


, . , , Internet. , .
, . , (.. ).
, Internet. Excel 2003 Internet, .

,
, . ,
, .
,
(C2, ), (C3), ,
(C4) , (5). , C3.
, C4 5.
. , .
.
, .
, .
,
.

644

VI.

PrintMod VBA, .
HelpMod VBA, ,
. .
UserForm1 , ,
UserForm.


.
.
Excel
(, UserForm).
.
HLP,
Windows Help System, CHM,
HTML Help System.


, , .
, .

-.

,
Excel
,
, Excel. WinHelp HTML Help.
.
, Excel .
. !
Text Box ( ). , , .
. , .
. , .
.
UserForm.

24.

645



. , . ,
, . .
, . VBA .
Application.DisplayCommentIndicator = xlCommentIndicatorOnly

Excel ,
.
,
. 250 .


Text Box . Text Box
. , .
. 24.1 Text Box,
.

. 24.1. Text Box

646

VI.

, ActiveX
,
. ,
.

, Text Box .
, Visible Text Box.
. Text Box HelpText.
Sub ToggleHelp()
ActiveSheet.TextBoxes("HelpText").Visible = _
Not ActiveSheet.TextBoxes("HelpText").Visible
End Sub




, ,
. , , .
. 24.2 , . ,
( , ).
,
ScrollArea . ,
,
. , ,
. ,
, , , .

.
,
, .




Excel UserForm, . , .

24.

647

LABEL

. 24.3 UserForm,
Label: , . SpinButton
.
. A, B.

. 24.2.


. 24.3.
SpinButton

SpinButton . Caption Label ,


.
Private Sub SpinButton1_Change()
HelpTopic = SpinButton1.Value
LabelTopic.Caption = Sheets(""). _
Cells(HelpTopic, 1)

648

VI.

LabelText.Caption = Sheets("").Cells(HelpTopic, 2)
Me.Caption = APPNAME & ": Topic " & HelpTopic & "/" _
& SpinButton1.Max
End Sub

APPNAME ,
.


LABEL

Label. ,
Label , Frame, . . 24.4 UserForm,
.
Frame.

. 24.4. Frame

Label

, Label,
.
UserForm. 24.1 UserForm_Initialize
. ,
ScrollHeight Frame
Label. APPNAME ,
.
24.1. Label ,
,
Private Sub UserForm_Initialize()
Me.Caption = APPNAME & ". "
LastRow = Sheets("").Range("A65536").End(xlUp).Row
txt = ""
For r = 1 To LastRow
txt = txt & Sheets("").Cells(r, 1).Text & vbCrLf
Next r
With Label1
.Top = 0
.Caption = txt
.Width = 160
.AutoSize = True
End With
Frame1.ScrollHeight = Label1.Height
Frame1.ScrollTop = 0
End Sub

24.

649

, Label ,
.



, , . . 24.5 UserForm,
ComboBox Label. ,
ComboBox, .

. 24.5. , Label,

( 24.2) , , .
Label Frame ( ),
.
,
. : .
, . ComboBox UserForm_Initialize.
CurrentTopic , .
24.2. Label Frame
Private Sub UpdateForm()
ComboBoxTopics.ListIndex = CurrentTopic - 1
Me.Caption = HelpFormCaption & _
" (" & CurrentTopic & " " & TopicCount & ")"
With LabelText
.Caption = HelpSheet.Cells(CurrentTopic, 2)
.AutoSize = False
.Width = 212
.AutoSize = True
End With
With Frame1
.ScrollHeight = LabelText.Height + 5
.ScrollTop = 1
End With
If CurrentTopic = 1 Then
NextButton.SetFocus

650

VI.

ElseIf CurrentTopic = TopicCount Then


PreviousButton.SetFocus
End If
PreviousButton.Enabled = CurrentTopic <> 1
NextButton.Enabled = CurrentTopic <> TopicCount
End Sub

Office

, Office , . .
, Microsoft , Office 2003 .
Excel 2003 .
.

Office , ( ) . . 24.6 Office,


.
Office
, 24.3.
.
. A , .

. 24.6. Office

24.3. Office

Public Const APPNAME As String = ""


Dim Topic
Dim HelpSheet
Sub ShowHelp()
Set HelpSheet = ThisWorkbook.Worksheets("")

24.

651

Application.Assistant.On = True
Topic = 1
With Assistant.NewBalloon
.Heading = " " & Topic & ": " & vbCrLf & HelpSheet.Cells(Topic, 1)
.Text = HelpSheet.Cells(Topic, 2)
.Button = msoButtonSetNextClose
.BalloonType = msoBalloonTypeButtons
.Mode = msoModeModeless
.Callback = "ProcessRequest"
.Show
End With
End Sub


Office. Balloon ( Office
)
Heading
Text . Balloon ,
, . Mode msoModeModeless,

. Callback ,
. , Show.
ProcessRequest, 24.4, , .
24.4.
Office
Sub ProcessRequest(bln As Balloon, lbtn As Long, lPriv As Long)
Dim NumTopics As Integer
NumTopics = Application.WorksheetFunction.CountA(HelpSheet.Range("A:A"))
Assistant.Animation = msoAnimationCharacterSuccessMajor
Select Case lbtn
Case msoBalloonButtonBack
If Topic <> 1 Then Topic = Topic - 1
Case msoBalloonButtonNext
If Topic <> NumTopics Then Topic = Topic + 1
Case msoBalloonButtonClose
bln.Close
Exit Sub
End Select
With bln
.Close
Select Case Topic
Case 1: .Button = msoButtonSetNextClose
Case NumTopics: .Button = msoButtonSetBackClose
Case Else: .Button = msoButtonSetBackNextClose
End Select
.Heading = " " & Topic & ": " & vbCrLf & _
HelpSheet.Cells(Topic, 1)
.Text = HelpSheet.Cells(Topic, 2)
.Show
End With
End Sub

652

VI.

ProcessRequest ,
Select Case
, , .
, ,
lbtn. , , , .

Office,
.

-.

?
Excel ,
. . Excel 2003
.
?
, .
. . , WhatThisButton
WhatThisHelp. , .
HTML .
UserForm ControlTipText.
.

MouseMove
. . 24.7 . Label.

. 24.7. Label

HTML Help System


Windows
HTML Help,
CHM. WinHelp HLP. , Microsoft, HTML Help.

24.

653

HTML Help.
, .
,
,
.
, . , -, . ,
RoboHELP
eHelp Corporation. RoboHELP
(WinHelp HTML Help). Web- http://www.ehelp.com.

, Microsoft HTML Help


.
HTML . HTML Help , ,
, ActiveX, , DHTML
(Dynamic HTML). . 24.8 ,
( , . ).

. 24.8. HTML Help

HTML Help HTML Help


Viewer, Internet Explorer.
, ,
. ,
, Internet. , HTML Help , Web-. ,
.

654

, Excel 2003 . , , . ,
Excel 2003 . , , .

VI.

WinHelp, ,
, HTML Help. HTML Help
Workshop,
Web- Microsoft : http://msdn.microsoft.com/library/
tools/htmlhelp/chm/HH1Start.htm.

HTML,
Excel.
. , .



(.. WinHelp HTML Help),
: Project Properties ( ) VBA.
VBE Toolsxxx Properties ( xxx) ( xxx ). Project Properties ( ) General () ,
( CHM, HLP).

, .
Myfuncs.chm. ,
.
ThisWorkbook.VBProject.HelpFile = _
ThisWorkbook.Path & "\Myfuncs.chm"

.
<F1>
.
<F1>
UserForm. ,
, <F1>.


VBA
VBA ,

. , <F1> .
,
.
1. .
2. , ( ).

24.

655

3. VBE <F2> Object Browser.


4. Project/Library.
5. Classes , .
6. Member () .
7. Properties . ,
Member Options ( ), . 24.9.

. 24.9.

8. ,
. .

Member Options
. ,
.

, VBA, . MacroOptions.
MacroOptions , (AddTwo Squared).
Sub SetOptions()
'
AddTwo
Application.MacroOptions Macro:="AddTwo", _
Description:=" ", _
HelpFile:=ThisWorkbook.Path & "\Myfuncs.hlp", _
HelpContextID:=1000
Squared
Application.MacroOptions Macro:="Squared", _
Description:=" ", _
HelpFile:=ThisWorkbook.Path & "\Myfuncs.hlp", _
HelpContextID:=2000
End Sub
'



WinHelp HTML Help
VBA
. .

656

VI.

Help
Help Application . WinHelp HLP,
HTML Help CHM. ,
.
Help .
Application.Help(helpFile, helpContextID)

. , Excel.
, , .
Myapp.hlp, . , ,
. : .
Sub ShowHelpContents()
Application.Help ThisWorkbook.Path & "\Myapp.hlp"
End Sub


1002.
HTML Help, Myapp.chm.
Application.Help ThisWorkbook.Path & "\Myapp.chm", 1002


VBA MsgBox
Help (), vbMsgBoxHelpButton
MsgBox. , . ( ) . , . 24.10.

. 24.10.

Sub MsgBoxHelp()
Msg = " ?"
Buttons = vbQuestion + vbYesNo + vbMsgBoxHelpButton
HelpFile = ThisWorkbook.Path & "\AppHelp.hlp"
ContextID = 1002
Ans = MsgBox(Msg, Buttons, , HelpFile, ContextID)
If Ans = vbYes Then Call CloseDown
End Sub



VBA InputBox Help (),
.
, . 24.11.

24.

657

Sub ShowInputBox()
Msg = " "
DefaultVal = 0
HFile = ThisWorkbook.Path & "\AppHelp.hlp"
ContextID = 1002
x = InputBox( _
Prompt:=Msg, _
Default:=DefaultVal, _
HelpFile:=HFile, _
Context:=ContextID)
End Sub

. 24.11.
Help ()

658

VI.

25



...
, .
, .
, ,

.

.
, .
, , . ,
, .

,

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


, .
. , , ,
, .
, .

(*.XLT) . , .
. 25.1 ,
.

-.
Excel.


, .
,
. .
UserForm MultiPage,
(. 25.225.6).

. 25.1.
, 30

660

VI.

. 25.2.

. 25.3.

. 25.4.

. 25.5.

. 25.6.


.
FormMain UserForm, .
FormHelp UserForm,
.
HelpSheet , , .
ModMain VBA, , UserForm.

25.

661

ThisWorkbook
Open BeforeClose Workbook,
.


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


Excel, .
, .

, Workbook_Open
. StartAmortizationWizard,
FormMain.

23 .

FORMMAIN
UserForm_Initialize FormMain
.
Value MultiPage
0. MultiPage, , .

ComboBox, .
GetDefaults , (

).

662

VI.

. ,
OptionButton,
.
, . ,
OptionButton,
.


USERFORM

FormMain Click Change , UserForm.

, MultiPage . MultiPage_Change
UserForm
, , . 15
.

.
,
UserForm. , .
, .
, , MultiPage.


UserForm 24.


.
Click .
DataIsValid, . , True, .
, DataIsValid , ,
(. 25.7).

. 25.7.
, ,

25.

663

,
, .
( , , ,
) .
If,
, .
.
. , , .
. , . ,
.
, R1C1 (
, ).

.
, , Subtotal . Excel,
.
, ,
,
.
Excel , .
,
ClearOutline .
, : ,
,
.
, , , .
, .
, SaveDefaults
UserForm .
,
(
).


, ,
FormMain , .
,
. -

664

VI.

- ,
.

UserForm. ,
, ,
UserForm.
, GetDefaults, UserForm.
TextBox, ComboBox, OptionButton, CheckBox SpinButton, VBA GetSetting . , GetSetting , , . ,
. APPNAME , .
Sub GetDefaults()
Dim ctl As Control
Dim CtrlType As String
For Each ctl In Me.Controls
CtrlType = TypeName(ctl)
If CtrlType = "TextBox" Or _
CtrlType = "ComboBox" Or _
CtrlType = "OptionButton" Or _
CtrlType = "CheckBox" Or _
CtrlType = "SpinButton" Then
ctl.Value = VBA.GetSetting _
(APPNAME, "Defaults", ctl.Name, ctl.Value)
End If
Next ctl
End Sub

. 25.8 , .

. 25.8.

25.

665

SaveDefaults . VBA SaveSetting .


Sub SaveDefaults()
Dim ctl As Control
Dim CtrlType As String
For Each ctl In Me.Controls
CtrlType = TypeName(ctl)
If CtrlType = "TextBox" Or _
CtrlType = "ComboBox" Or _
CtrlType = "OptionButton" Or _
CtrlType = "CheckBox" Or _
CtrlType = "SpinButton" Then
SaveSetting APPNAME, "Defaults", ctl.Name, ctl.Value
End If
Next ctl
End Sub

, CStr,
. ,
, .
GetSetting, SaveSetting
:
HKEY_CURRENT_USER\Software\VB and VBA Program Settings\


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

.


, - .
,
.
, ,
.
Excel.
, .

666

VI.

UserForm,
.
Excel.
Enabled .
TextBox SpinButton.
.
VBA.
VBA.
.

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

,
, ,
. .
?
,
.
? ,
.
? , , .
, ?
,
, , , .
? Excel , .
? , , .
? ,
?
? .
?
.
.

25.

667

VII

...

26.
27.
28.
29.
30.


VBA
Visual Basic


Excel

26


...
.
Excel 2003
, Excel
Excel 2003 Excel, .

Excel, Excel Macintosh, Excel, .


. .
, . ,
, 32-
(, Windows XP), 16-
Windows (3.). , 32-
Windows 3.x. , ,
Windows,
, MacOS Linux.
;
Excel 2003 Excel
Windows Excel Macintosh. , Excel , ,
. , Excel 97, Excel 2000 Excel 2002, Excel 2003, Excel 98
Macintosh , . , Excel , ,
VBA, .
, . Excel. ,
Excel 2000 : ,
SR-1 , SR-1a.
, Excel. , , , , Excel 2000 SR-1.

, Excel , , . ,
.
, .


. .
. Excel. ,
Excel.
. , ,
Excel,
.
32- 16- .
Windows API 16- Excel (Excel 5),
.
Windows Macintosh.
,
.
.
Excel, .
, :
, Excel.
. , Excel.

, Excel, . , .

Microsoft,
http://search.support.microsoft.com. , Excel.

Excel
Excel , . ,
( ). .

672

VII.

Excel, . Excel 2003 .


Microsoft Excel (*.xls). Excel 2003.
Excel 97, Excel 20002003.
Microsoft Excel 5.0/95. , Excel 5 .
Microsoft Excel 97-2000 & 5.0/95. , Excel 5 .
Microsoft Excel 4.0 (*.xls). Excel 4
. .
Microsoft Excel 3.0 (*.xls). Excel 3
. .
Microsoft Excel 2.1 (*.xls). Excel 2.1
. .
Microsoft Excel 4 (*.xlw). Excel 4
. ,
Excel 5.
VBA FileFormat Workbook, . ,
, .
MsgBox ActiveWorkbook.FileFormat

FileFormat
. , , ,
True, Excel 5.
MsgBox ActiveWorkbook.FileFormat = xlExcel5

. 26.1 ,
VBA Excel.

26.1. Excel
Excel

Excel 2.1

xlExcel2

16

Excel 3

xlExcel3

29

Excel 4

xlExcel4Workbook

35

Excel 5

xlExcel5

39

Excel 95/97

xlExcel9795

43

Excel HTML

xlHtml

44

Excel

xlAddIn

18

Excel 97/2000/2002/2003

xlWorkbookNormal

-4143

26.

673

Excel (Excel 2003


), ,
Excel, .
.
, , Excel , .
VBA, ,
, .
. Excel 2002, 2000, Excel 97 Excel 95, Excel 95,
.
Excel 95, UserForm
. Excel 97.
.

Excel
Version Application Excel.
, . VBA
Val . True, Excel 2002 (Excel 2002 10).
Function XL10OrLater()
XL10OrLater = Val(Application.Version) >= 10
End Function

Mac
Macintosh.
, Excel Macintosh Excel, . Microsoft
Excel . , VBA .
VBA, ,
. OperatingSystem
Application True,
Windows (.. "Win").
Function WindowsOS() As Boolean
If Application.OperatingSystem like "*Win*" Then
WindowsOS = True
Else
WindowsOS = False
End If
End Function

674

VII.

Windows- Mac- Excel .


(,
). . ,
Excel Macintosh ActiveX. , Excel
Macintosh 1904, , , 4 . Excel
Windows 1900. , Macintosh
1 1 1904 . Windows
1 1900 .
Windows API. Excel
Macintosh .
, , .
, , ( Macintosh
Windows).
VBA. PathSep.
PathSep = Application.PathSeparator

PathSep
.
, , ,

. (
Excel Windows), .
, .
Excel
Macintosh: . ,
.



. Excel .
Excel.
MsgBox Application.International(xlCountryCode)

United States/English 1.
. 26.2.
, , , , . ,
, .
.
.
.
, //.

26.

675

26.2. , Excel

30

31

33

34

36

39

42

45

46

47

48

49

()

55

66

81

82

84

86

90

91

92

351

358

886

966

972

982

, ,
. , , . .


,
. ,
, .
, (, , ).

676

VII.

- , : , .
, 14.


OptionButton, .
.
. 26.126.3 UserForm,
.

. 26.1.

. 26.2.

. 26.3.

VBA
, VBA . Excel
: Excel Object library VBA Object library.
Excel .
( Excel).


, , , , , .
, .
MsgBox Selection.Address

AddressLocal Address.
MsgBox Selection.AddressLocal

26.

677

, (A1 R1C1). .
MsgBox Selection.AddressLocal _
(ReferenceStyle:=Application.ReferenceStyle)

.
. 26.3 ( ,
).

26.3.

""

Address

AddressLocal

Category

CategoryLocal

Formula

FormulaLocal

Name

NameLocal

NumberFormat

NumberFormatLocal

RefersTo

RefersToLocal


, ,
, .
.
,
.
, .
,
.

International Application. ,
, .
MsgBox Application.International(xlDecimalSeparator)

45 ,
International. . 26.4.

26.4. International

xlCountryCode

Microsoft Excel

xlCountrySetting

xlDecimalSeparator

xlThousandsSeparator

xlListSeparator

xlUpperCaseRowLetter

( R1C1)

xlUpperCaseColumnLetter

678

VII.

. 26.4

xlLowerCaseRowLetter

xlLowerCaseColumnLetter

xlLeftBracket

,
([) R1C1

xlRightBracket

, (]) R1C1

xlLeftBrace

,
({)

xlRightBrace

,
(})

xlColumnSeparator

xlRowSeparator

xlAlternateArraySeparator

, ,

xlDateSeparator

(/)

xlTimeSeparator

(:)

xlYearCode

(y)

xlMonthCode

(m)

xlDayCode

(d)

xlHourCode

(h)

xlMinuteCode

(m)

xlSecondCode

(s)

xlCurrencyCode

xlGeneralFormatName

xlCurrencyDigits

xlCurrencyNegative

xlNoncurrencyDigits

xlMonthNameChars

. Windows

xlWeekdayNameChars

. Windows

xlDateOrder

xl24HourClock

True, 24- .
False, 12-

xlNonEnglishFunctions

True,

26.

679

. 26.4

xlMetric

True, .
False,

xlCurrencySpaceBefore

True,

xlCurrencyBefore

True, .
False

xlCurrencyMinusSign

True,
. False,

xlCurrencyTrailingZeros

True,
,

xlCurrencyLeadingZeros

True,
,

xlMonthLeadingZero

True,

xlDayLeadingZero

True,

xl4DigitYears

True, ,
False ( )

xlMDY

True,
--, False, -

xlTimeLeadingZero

True,


, , , .
VBA DateSerial, Excel
( ).
DateSerial
StartDate. A1 .
Sub WriteDate()
Dim StartDate As Date
StartDate = DateSerial(2001, 2, 15)
Range("A1") = StartDate
End Sub

, ,
. Excel
,
. .

680

VII.

27


VBA
...
VBA,
,
. VBA .

, FileSearch.
.
VBA.
, 256 .
, HTML.
Excel . ,
,
;
.. , Excel
, ,
Excel . ,
256 . , , .


Excel .
VBA.
Excel.
FileSearch, .
.
Excel 97 .
FileSystemObject,
Microsoft Scripting Library. Excel 2000
.

.

VBA
VBA, ,
. 27.1.

27.1. VBA,

ChDir

ChDrive

Dir

FileCopy

FileDateTime

FileLen

( )

GetAttr

Kill

MkDir

Name

RmDir

SetAttr

, .


True,
. , False.
Dir , .
False.
Function FileExists(fname) As Boolean
If Dir(fname) <> "" Then _
FileExists = True _
Else FileExists = False
End Function

FileExists .
, VBA.


True, .
False.
Function PathExists(pname) As Boolean
'
TRUE,
On Error Resume Next
PathExists = GetAttr(pname) And vbDirectory = vbDirectory
End Function

682

VII.


( ) ,
. ,
, .
Sub ListFiles()
Directory = "c:\windows\"
r = 1
'


Cells(r, 1) = " "
Cells(r, 2) = ""
Cells(r, 3) = "/"
Range("A1:C1").Font.Bold = True


f = Dir(Directory, 7)
Do While f <> ""
r = r + 1
Cells(r, 1) = f
Cells(r, 2) = FileLen(Directory & f)
Cells(r, 3) = FileDateTime(Directory & f)
'

f = Dir
Loop
End Sub
'

. 27.1 .
, Dir .
,
. , Dir .

-
. .

. 27.1.
ListFiles

27. VBA

683

Dir .
(, Excel), .
f = Dir(Directory & "*.xl?", 7)

.
*.xl?. Dir
. , 7, ,
, , ,
. .

,
, .
GetOpenFileName, 12.

FileSearch
FileSearch Microsoft Office.
VBA .
, ,
(, *.xls), ,
. Excel 97 .
. 27.2 ,
FileSearch. .

27.2. FileSearch

FileName

, ( )

FoundFiles

LookIn

SearchSubFolders

True,

Execute

NewSearch

FileSearch


FileSearch.


( ) ,
. , .
Sub ListFiles2()
Directory = "c:\windows\"
'


r = 1
Cells.ClearContents
Cells(r, 1) = " "
Cells(r, 2) = ""

684

VII.

Cells(r, 3) = "/"
Range("A1:C1").Font.Bold = True
r = r + 1
On Error Resume Next
With Application.FileSearch
.NewSearch
.LookIn = Directory
.Filename = "*.*"
.SearchSubFolders = False
.Execute
For i = 1 To .FoundFiles.Count
Cells(r, 1) = .FoundFiles(i)
Cells(r, 2) = FileLen(.FoundFiles(i))
Cells(r, 3) = FileDateTime(.FoundFiles(i))
r = r + 1
Next i
End With
End Sub

FileSearch Windows ( *.LNK).


( ) True, .
Execute Count FoundFiles 1,
.
Function FileExists2(path, fname) As Boolean
With Application.FileSearch
.NewSearch
.Filename = fname
.LookIn = path
.Execute
If .FoundFiles.Count = 1 Then
FileExists2 = True
Else
FileExists2 = False
End If
End With
End Function

FileSearch .

FileSystemObject
FileSystemObject Windows Scripting Host
. Web- (,
VBScript JavaScript) Excel 2000
.

Windows Scripting Host . , Windows Scripting Host . , , .

27. VBA

685

FileSystemObject http://msdn.
microsoft.com/scripting.


, , ( ),
True, .
Function FileExists3(fname) As Boolean
Set FileSys = CreateObject("Scripting.FileSystemObject")
FileExists3 = FileSys.FileExists(fname)
End Function

FileSystemObject, FileSys,
FileExists .

- , ( VBA, FileSearch FileSystemObject) .


, , ()
True, .
Function PathExists2(path) As Boolean
Set FileSys = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set FolderObj = FileSys.getfolder(path)
If Err = 0 Then
PathExists2 = True
Else
PathExists2 = False
End If
End Function

Folder,
FolderObj. , . , .


FileSystemObject .
Drives . . 27.2 ,
, -. (), , ,
, , .

. 27.2.
ShowDriveInfo

686

VII.

Windows TotalSize AvailableSpace , 2 .


Windows NT, Windows 2000
.

-.

Sub ShowDriveInfo()
Dim FileSys, Drv
Dim Row As Integer
Set FileSys = CreateObject("Scripting.FileSystemObject")
Cells.Clear
Row = 0
On Error Resume Next
For Each Drv In FileSys.Drives
Row = Row + 1
Cells(Row, 1) = Drv.DriveLetter
Cells(Row, 2) = Drv.IsReady
Select Case Drv.DriveType
Case 0: Cells(Row, 3) = ""
Case 1: Cells(Row, 3) = ""
Case 2: Cells(Row, 3) = ""
Case 3: Cells(Row, 3) = ""
Case 4: Cells(Row, 3) = "CD-ROM"
Case 5: Cells(Row, 3) = "RAM"
End Select
Cells(Row, 4) = Drv.VolumeName
Cells(Row, 5) = Drv.TotalSize
Cells(Row, 6) = Drv.AvailableSpace
Next Drv
End Sub

,
*.xls
, . ListBox UserForm.
Sub FindFiles()
With Application.FileSearch
.NewSearch
.LookIn = "C:\ "
.SearchSubFolders = True
.TextOrProperty = ""
.MatchTextExactly = False
.Filename = "*.xls"
.Execute
For i = 1 To .FoundFiles.Count
UserForm1.ListBox1.AddItem .FoundFiles(i)
Next i
End With
UserForm1.Show
End Sub

27. VBA

687


VBA ,
. / , Excel.
.
. .

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


.
. FileSystemObject TextStream, .
FileSystemObject Windows Scripting Host. ,
- .


VBA Open ( Open Application) . ,
, .
Open ,
.
Open For [Access ] [] _
As [#]_ [Len=_]

Open .
, ( ).
, ( ). :
Append , , ;
Input , ,
;

688

VII.

Output ,
.
( );
Binary , ;
Random ,
, _
Open.

( ). Read, Write
Read Write.

( ).
: Shared, Lock Read, Lock Write,
Lock Read Write.
_ , 1 511
( ).
FreeFile.
_ ( )
( ) .


VBA .
1. Open.
2. Seek ( ).
3. Input, Input # Line Input #.
4. Close.


.
1. Open.
2. Seek ( ).
3. Write # Print #.
4. Close.


, VBA,
Open.
Open "myfile.txt" For Input As #1

#1.

27. VBA

689

, #2.
Open "another.txt" For Input As #2

Excel
Excel .
CSV (Comma Separated Values) ( ).
, . Excel
.
PRN. ,
.
TXT (Tab-delimited) ( ). , .

, . , Excel . ,
, , , .

VBA FreeFile, .
. .
FileHadle = FreeFile
Open "myfile.txt" For Input As FileHandle



.
, Seek.


VBA .

.
Input .
Input # ;
.
Line Input # (
/ ).

690

VII.

.
Write # , . ,
/ . ,
Write #, Input #.
Print # , . ,
/ . , Print #,
Line Input # Input.


,
.



( ).
Sub ImportData()
Set ImpRng = ActiveCell
Open "c:\windows\desktop\textfile.txt" For Input As #1
r = 0
Do Until EOF(1)
Line Input #1, data
ActiveCell.Offset(r, 0) = data
r = r + 1
Loop
Close #1
End Sub

,
.
.


( 27.3) ,

CSV.
, Write #.
, / .
Write # , .
Data .
, ,
. , Value
0. , (
IsEmpty) 0 .

27. VBA

691

27.3. CSV@
Sub ExportRange()
Dim Filename As String
Dim NumRows As Long, NumCols As Integer
Dim r As Long, c As Integer
Dim Data
Dim ExpRng As Range
Set ExpRng = Selection
NumCols = ExpRng.Columns.Count
NumRows = ExpRng.Rows.Count
Filename = "c:\windows\textfile.txt"
Open Filename For Output As #1
For r = 1 To NumRows
For c = 1 To NumCols
Data = ExpRng.Cells(r, c).Value
If IsNumeric(Data) Then Data = Val(Data)
If IsEmpty(ExpRng.Cells(r, c)) Then Data = ""
If c <> NumCols Then
Write #1, Data;
Else
Write #1, Data
End If
Next c
Next r
Close #1
End Sub

-.

. 27.3 .


(. 27.4)
, . , .
. ,
.

. 27.3. ,
VBA

692

VII.

27.4. ,

Sub ImportRange()
Dim ImpRng As Range
Dim Filename As String
Dim r As Long, c As Integer
Dim txt As String, Char As String * 1
Dim Data
Dim i As Integer
Set ImpRng = ActiveCell
On Error Resume Next
Filename = "c:\windows\textfile.txt"
Open Filename For Input As #1
If Err <> 0 Then
MsgBox " : " & Filename, vbCritical, ""
Exit Sub
End If
r = 0
c = 0
txt = ""
Application.ScreenUpdating = False
Do Until EOF(1)
Line Input #1, Data
For i = 1 To Len(Data)
Char = Mid(Data, i, 1)
If Char = "," Then '
ActiveCell.Offset(r, c) = txt
c = c + 1
txt = ""
ElseIf i = Len(Data) Then '
If Char <> Chr(34) Then txt = txt & Char
ActiveCell.Offset(r, c) = txt
txt = ""
ElseIf Char <> Chr(34) Then
txt = txt & Char
End If
Next i
c = 0
r = r + 1
Loop
Close #1
Application.ScreenUpdating = True
End Sub

, , : ,
. ,
, : #2001-05-12#.

-.

Excel
, , Excel.
, , Excel. .

27. VBA

693

, ,
.
Private Sub Workbook_Open()
Open Application.Path & "\excelusage.txt" _
For Append As #1
Print #1, "Started " & Now
Close #1
End Sub

, excelusage.txt.
:
Started 03/09/00 9:27:43 PM

. ,
Stopped, .
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Open Application.Path & "\excelusage.txt" _
For Append As #1
Print #1, "Stopped " & Now
Close #1
End Sub


. FilterFile, ,
(infile.txt) , ,
(output.txt).

Sub FilterFile()
Open "infile.txt" For Input As #1
Open "output.txt" For Output As #2
TextToFind = "January"
Do Until EOF(1)
Line Input #1, data
If InStr(1, data, TextToFind) Then
Print #2, data
End If
Loop
Close
End Sub

-.

256
,
Excel 256 .
, Excel ,
256- ( )!
( 27.5) ImportRange,
. .
256- , .

694

VII.

27.5.

Sub ImportLongLines()
'
256
Dim
Dim
Dim
Dim
Dim
Dim
'

ImpRange As Range
r As Long, c As Integer
CurrLine As Long
Data As String, Char As String, Txt As String
i As Integer
CurrSheet As Worksheet


Workbooks.Add xlWorksheet
Open ThisWorkbook.Path & "\longfile.txt" For Input As #1
r = 0
c = 0
Set ImpRange = ActiveWorkbook.Sheets(1).Range("A1")
Application.ScreenUpdating = False

, ( )
CurrLine = CurrLine + 1
Line Input #1, Data
For i = 1 To Len(Data)
Char = Mid(Data, i, 1)
'
?
If c <> 0 And c Mod 256 = 0 Then
Set CurrSheet = ActiveWorbook.Sheets.Add(after:=ActiveWorkbook. _
Sheets(ActiveWorkbook.Sheets.Count))
Set ImpRange = CurrSheet.Range("A1")
c = 0
End If
'
?
If Char = "," Then
ImpRange.Offset(r, c) = Txt
c = c + 1
Txt = ""
Else
'

If Char <> Chr(34) Then _
Txt = Txt & Mid(Data, i, 1)
'

'

?
If i = Len(Data) Then
ImpRange.Offset(r, c) = Txt
c = c + 1
Txt = ""
End If
End If
Next i

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'

c = 0
CurrLine = 1
Set ImpRange = ActiveWorkbook.Sheets(1).Range("A1")
r = r + 1
Do Until EOF(1)
Set ImpRange = ActiveWorkbook.Sheets(1).Range("A1")
CurrLine = CurrLine + 1
Line Input #1, Data
Application.StatusBar = " " & CurrLine

27. VBA

695

For i = 1 To Len(Data)
Char = Mid(Data, i, 1)
?
If c <> 0 And c Mod 256 = 0 Then
c = 0
Set ImpRange = ImpRange.Parent.Next.Range("A1")
End If

'


If Char = "," Then
ImpRange.Offset(r, c) = Txt
c = c + 1
Txt = ""
Else

If Char <> Chr(34) Then _
Txt = Txt & Mid(Data, i, 1)

'

'

'

?
If i = Len(Data) Then
ImpRange.Offset(r, c) = Txt
c = c + 1
Txt = ""
End If
End If
Next i
c = 0
Set ImpRange = ActiveWorkbook.Sheets(1).Range("A1")
r = r + 1
Loop

Close #1
Application.ScreenUpdating = True
Application.StatusBar = False
End Sub
'

.
, . . ,
, , .

-. ,
, 100 600 .

HTML
HTML. HTML, , , , .
Excel Web ? , , :
HTML. , ExportToHTML
70 . 2,7 K.
Excel Web , 15,8 K ( ). ,
ExportToHTML .

696

VII.

. , ExportToHTML :
.
ExportToHTML.
27.6. HTML@
Sub ExportToHTML()
'
Dim ws As Worksheet
Dim Filename As Variant
Dim TDOpenTag As String, TDCloseTag As String
Dim CellContents As String
Dim Rng As Range
Dim r As Long, c As Integer
'


Set Rng = Application.Intersect(ActiveSheet.UsedRange, Selection)

'


Filename = Application.GetSaveAsFilename( _
InitialFileName:="myrange.htm", _
fileFilter:="HTML Files(*.htm), *.htm")
If Filename = False Then Exit Sub

'


Open Filename For Output As #1

'

<TABLE>
Print #1, "<TABLE BORDER=1 CELLPADDING=3>"

'


For r = 1 To Rng.Rows.Count
Print #1, "<TR>"
For c = 1 To Rng.Columns.Count
TDOpenTag = "<TD ALIGN=RIGHT>"
TDCloseTag = "</TD>"
If Rng.Cells(r, c).Font.Bold Then
TDOpenTag = TDOpenTag & "<B>"
TDCloseTag = "</B>" & TDCloseTag
End If
If Rng.Cells(r, c).Font.Italic Then
TDOpenTag = TDOpenTag & "<I>"
TDCloseTag = "</I>" & TDCloseTag
End If
CellContents = Rng.Cells(r, c).Text
Print #1, TDOpenTag & CellContents & TDCloseTag
Next c
Print #1, "</TR>"
Next r

Print #1, "</TABLE>"

'
'


Close #1


MsgBox Rng.Count & " " & Filename
End Sub


'

-.

27. VBA

697

.
. ,
.
. .
For-Next. HTML
( ) .
, , .
. 27.4 , . 27.5 ,
HTML.
ExportToHTML .

. 27.4. ,
HTML

. 27.5. ,
HTML

698

VII.

XML6
Excel
XML-. , XML
.
. . 27.6 , . 27.7
XML-, Internet Explorer.

Excel 2003 XML, XML-


() XML.

. 27.6. , XML

. 26.7.

27. VBA

699

ExportToHTML
.
27.7. XML
Sub ExportToXML()
'
Dim ws As Worksheet
Dim Filename As Variant
Dim TDOpenTag As String, TDCloseTag As String
Dim CellContents As String
Dim Rng As Range
Dim r As Long, c As Integer
'


Set Rng = Range("A1:L11")

'


Filename = Application.GetSaveAsFilename( _
InitialFileName:="myrange.xml", _
fileFilter:="XML Files(*.xml), *.xml")
If Filename = False Then Exit Sub

'


Open Filename For Output As #1

'

<xml>
Print #1, "<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>"
Print #1, "<EmployeeList xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">"

'


For r = 2 To Rng.Rows.Count
Print #1, "<Employee>"
For c = 1 To Rng.Columns.Count
Print #1, "<" & Rng.Cells(1, c) & ">";
If IsDate(Rng.Cells(r, c)) Then
Print #1, Format(Rng.Cells(r, c), "yyyy-mm-dd");
Else
Print #1, Rng.Cells(r, c).Text;
End If
Print #1, "</" & Rng.Cells(1, c) & ">"
Next c
Print #1, "</Employee>"
Next r

Print #1, "</EmployeeList>"

'
'


Close #1


MsgBox Rng.Rows.Count - 1 & " " & Filename
End Sub

'

700

VII.

28


Visual Basic
...
,
, VBA .
.
Excel 20022003.
VBA .
VBA VBA.
VBA UserForm.
UserForm.
VBA , VBA, .
VBA, ,
VBA UserForm.

IDE
IDE OLE Visual Basic Editor.
Visual Basic Extensibility Library ( ToolsReferences ())
, VBE,
- IDE.
References Microsoft Visual Basic for Application
Extensibility. VBIDE. VBIDE
, VBIDE,
, IDE. , IDE
,
IDE, , IDE.

Excel 20022003
Excel 20022003, ,
Excel 2002 . , Microsoft VBA
VBA. , ,
, .

,
Excel (
). Visual Basic Project
. ,
, , VBA. , .

.
VBProject,
. .
On Error Resume Next
Set x = ActiveWorkbook.VBProject
If Err <> 0 Then
MsgBox " "
Exit Sub
End If

, ,
.
.
Visual Basic Project.

OLE 20.

IDE , .
VBA.
VBA.
.
UserForm.

IDE
IDE .
VBE (Visual Basic Environment
Visual Basic). Excel, VBE . IDE .
VBE
VBProject
VBComponent
CodeModule
Designer

702

VII.

Property
Reference
Window
CommandBar

Windows CommandBars, Extensibility Library, Excel. VBProject,


(
Excel 2003).

VBProjects
VBProject.
VBProject, , VBProject Workbook.
, VBProject .
Dim VBP As VBProject
Set VBP = ActiveWorkbook.VBProject

Dim , Microsoft Visual Basic for Application Extensibility.


VBProject VBA, ( UserForm, , , ). VBComponents. ,
VBProject References ,
, .

VBProjects. Excel. VBProjects. , VBProject. , .

VBCOMPONENTS
VBComponents, VBComponents . VBA.
Set VBC = ThisWorkbook.VBProject.VBComponents(1)
Set VBC = ThisWorkbook.VBProject.VBComponents("Module1")

REFERENCES
VBA Excel .
,
ToolsReferences () (. 28.1).
(, VBA, Excel, OLE Automation, Office Object
Library), .
VBA.
References Reference, . ,
Name, Description FullPath
Reference .

28. Visual Basic

703

Sub ListReferences()
Dim Ref As Reference
Msg = ""
For Each Ref In ActiveWorkbook.VBProject.References
Msg = Msg & Ref.Name & vbCrLf
Msg = Msg & Ref.Description & vbCrLf
Msg = Msg & Ref.FullPath & vbCrLf & vbCrLf
Next Ref
MsgBox Msg
End Sub

. 28.2 .
.

. 28.1. References
() ,

. 28.2.

, Reference,
ListReferences VBA Extensibility Library. Ref Object, VBA
Extensibility Library .

. Reference. AddFromFile ,
, . AddFromGuid ,
, GUID. .


ShowComponents, 28.1,
VBA
:
;
;
.

704

VII.

28.1. VBA
Sub ShowComponents()
Dim VBP As VBProject
Set VBP = ActiveWorkbook.VBProject
NumComponents = VBP.VBComponents.Count
Cells.ClearContents
For i = 1 To NumComponents
'

Cells(i, 1) = VBP.VBComponents(i).Name

Select Case VBP.VBComponents(i).Type


Case 1
Cells(i, 2) = ""
Case 2
Cells(i, 2) = " "
Case 3
Cells(i, 2) = " "
Case 100
Cells(i, 2) = " "
End Select
'

Cells(i, 3) = _
VBP.VBComponents(i).CodeModule.CountOfLines
Next i
End Sub

'

. 28.3 ShowComponents. VBA , .

. 28.3.
ShowComponents

-. , VBA Extensibility Library.


, , VBA
VBA. VBComponent
(Export, Remove Import), . ,
, , , , .
,
.
, , VBA , .

28. Visual Basic

705

.
UserBook.xls (Module1), .
UpdateUserBook.xls VBA, Module1
UserBook.xls .
BeginUpdate, 28.2,
UpdateUserBook,
UserBook.xls. ,
UserBook.xls . (. 28.4).

. 28.4.

28.2.
Sub UpdateUserBook()
Filename = "UserBook.xls"
'


On Error Resume Next
Workbooks(Filename).Activate
If Err <> 0 Then
MsgBox Filename & " !", vbCritical
Exit Sub
End If

Msg = " Module1 UserBook.XLS "


Msg = Msg & " " & vbCrLf & vbCrLf
Msg = Msg & " OK "
If MsgBox(Msg, vbInformation + vbOKCancel) = vbOK Then
Call ReplaceModule
Else
MsgBox " !", vbCritical
End If
End Sub

OK, ReplaceModule. ,
28.3, Module1, UserBook.xls,
UpdateUserBook.
28.3.
Sub ReplaceModule()
'
Module1
Filename = ThisWorkbook.Path & "\tempmodxxx.bas"
ThisWorkbook.VBProject.VBComponents("Module1") _
.Export Filename
'

Module1 UserBook.xls
Set VBP = ActiveWorkbook.VBProject
On Error GoTo ErrHandle

706

VII.

With VBP.VBComponents
.Remove VBP.VBComponents("Module1")
.Import Filename
End With
'


Kill Filename
MsgBox " ", vbInformation
Exit Sub

ErrHandle:
'
?
MsgBox ". ", _
vbCritical
End Sub

.
1. Module1 ( ).
, .
2. UserForm.xls Module1 (
). Remove VBComponents.
3. ( )
UserBook.xls.
4. .

5. ,
.
.

( )
-. ,
, .

VBA VBA
, , VBA
VBA. AddSheetAndButton
.
1. .
2. CommandButton.
3. , CommandButton.
4.
CommandButton. CommandButton1_Click.

1.
28.4 AddSheetAndButton.

28. Visual Basic

707

28.4. ,

Sub AddSheetAndButton()
Dim NewSheet As Worksheet
Dim NewButton As OLEObject
'


Set NewSheet = Sheets.Add

'


Set NewButton = NewSheet.OLEObjects.Add _
("Forms.CommandButton.1")
With NewButton
.Left = 4
.Top = 4
.Width = 100
.Height = 24
.Object.Caption = " 1"
End With

'


Code = "Sub CommandButton1_Click()" & vbCrLf
Code = Code & "
On Error Resume Next" & vbCrLf
Code = Code & "
Sheets(""1"").Activate" & vbCrLf
Code = Code & "
If Err <> 0 Then" & vbCrLf
Code = Code & "
MsgBox "" 1.""" & vbCrLf
Code = Code & "
End If" & vbCrLf
Code = Code & "End Sub"

With ActiveWorkbook.VBProject. _
VBComponents(NewSheet.Name).CodeModule
NextLine = .CountOfLines + 1
.InsertLines NextLine, Code
End With
End Sub

. 28.5 , AddSheetAndButton.
VBA
. , Code.
.
InsertLines .
NextLine
.
. ,
,
Option Explicit , .
. 28.6 , AddSheetAndButton.

. 28.5. ,
CommandButton,
VBA

708

VII.


UserForm

, UserForm,
, ,
, .
VBE,
.
UserForm, . 28.7, 100 CommandButton.
. , CommandButton
.
, .
VBA .

. 28.6. VBA

. 28.7.

CommandButton UserForm VBA

28. Visual Basic

709

UserForm

UserForm
. UserForm ,
. ,
, . ,
Caption ,
.
VBE, , UserForm . IV ,
UserForm
.
, .
VBE. , VBA

UserForm.
, Designer
UserForm.

, ,
CommandButton UserForm.
,
.
RunTimeButton, , .
CommandButton .
UserForm.
CommandButton .
VBE, , .
Sub RunTimeButton()
'

Dim Butn As CommandButton
Set Butn = UserForm1.Controls.Add("Forms.CommandButton.1")
With Butn
.Caption = " "
.Width = 100
.Top = 10
End With
UserForm1.Show
End Sub

DesignTimeButton. ,
Designer, VBComponent. ,
Add CommandButton. Designer, CommandButton UserForm , .

710

VII.

Sub DesignTimeButton()
'

Dim Butn As CommandButton
Set Butn = ThisWorkbook.VBProject. _
VBComponents("UserForm1") _
.Designer.Controls.Add("Forms.CommandButton.1")
With Butn
.Caption = " "
.Width = 120
.Top = 40
End With
End Sub

100 CommandButton


Designer UserForm. 100
CommandButton ( ), Caption
CommandButton 100 (
CommandButton).
28.5 Add100Buttons.
28.5. UserForm, 100
Sub Add100Buttons()
Dim UFvbc As Object 'VBComponent
Dim CMod As Object '
Dim ctl As Control
Dim cb As CommandButton
Dim n As Integer, c As Integer, r As Integer
Dim code As String
Set UFvbc = ThisWorkbook.VBProject.VBComponents("UserForm1")
'
For Each ctl In UFvbc.Designer.Controls
UFvbc.Designer.Controls.Remove ctl.Name
Next ctl
' VBA
UFvbc.CodeModule.DeleteLines 1, UFvbc.CodeModule.CountOfLines
' 100 CommandButton
n = 1
For r = 1 To 10
For c = 1 To 10
Set cb = UFvbc.Designer.Controls.Add("Forms.CommandButton.1")
With cb
.Width = 22
.Height = 22
.Left = (c * 26) - 16
.Top = (r * 26) - 16
.Caption = n
End With
'


With UFvbc.CodeModule
code = ""
code = code & "Private Sub CommandButton" & n & "_Click" & vbCr

28. Visual Basic

711

code = code & "Msgbox ""This is CommandButton" & n & """" & vbCr
code = code & "End Sub"
.InsertLines .CountOfLines + 1, code
End With
n = n + 1
Next c
Next r
VBA.UserForms.Add("UserForm1").Show
End Sub

Add100Buttons ,
UserForm1.
.
. DeleteLines CodeModule. CommandButton
For-Next.
. (
CommandButton1).
Private Sub CommandButton1_Click()
MsgBox " CommandButton1"
End Sub

, ,
.
, .
.
, End Sub.
VBA.UserForms.Add("UserForm1").Show

, ,
UserForm. VBA
UserForm, 100 ,
, . UserForm1 UserForms, Add. (, ) .
Add Show. ,
UserForms.


UserForm
VBA UserForm .
: , .

712

VII.


, , .
, . . MakeForm .
1. UserForm .
Add VBComponents.
2. CommandButton UserForm.
Designer.
3.
UserForm. (CommandButton1_Click) .
4. UserForm.
5. UserForm.
UserForm, . , .
, .

UserForm
, . .

MakeForm.
28.6. UserForm
Sub MakeForm()
Dim TempForm As Object 'VBComponent
Dim NewButton As Msforms.CommandButton
Dim Line As Integer
Dim TheForm
Application.VBE.MainWindow.Visible = False
'

UserForm
Set TempForm = ThisWorkbook.VBProject. _
VBComponents.Add(3) 'vbext_ct_MSForm
With TempForm
.Properties("Caption") = " "
.Properties("Width") = 200
.Properties("Height") = 100
End With

'

CommandButton
Set NewButton = TempForm.Designer.Controls _
.Add("forms.CommandButton.1")
With NewButton
.Caption = "!"
.Left = 60
.Top = 40
End With

28. Visual Basic

713

'

CommandButton
With TempForm.CodeModule
Line = .CountOfLines
.InsertLines Line + 1, "Sub CommandButton1_Click()"
.InsertLines Line + 2, "MsgBox ""!"""
.InsertLines Line + 3, "Unload Me"
.InsertLines Line + 4, "End Sub"
End With

'

UserForm
VBA.UserForms.Add(TempForm.Name).Show

'
'

UserForm
ThisWorkbook.VBProject.VBComponents.Remove TempForm
End Sub

, . 28.8.
. 28.8.
UserForm,
,
VBA

, MakeForm, VBA Extensibility Library, TempForm


Object ( VBComponent). ,
.

, VBE,
Visible False. .


, . GetOption, UserForm.
OptionButton,
. , OptionButton, .
28.7.
28.7. @

Function GetOption(OpArray, Default, Title)


Dim TempForm As Object 'VBComponent
Dim NewOptionButton As Msforms.OptionButton
Dim NewCommandButton1 As Msforms.CommandButton
Dim NewCommandButton2 As Msforms.CommandButton
Dim i As Integer, TopPos As Integer
Dim MaxWidth As Long
Dim Code As String
'

VBE
Application.VBE.MainWindow.Visible = False

'

UserForm
Set TempForm = _

714

VII.

ThisWorkbook.VBProject.VBComponents.Add(3) 'vbext_ct_MSForm
TempForm.Properties("Width") = 800
'

OptionButton
TopPos = 4
MaxWidth = 0
For i = LBound(OpArray) To UBound(OpArray)
Set NewOptionButton = TempForm.Designer.Controls. _
Add("forms.OptionButton.1")
With NewOptionButton
.Width = 800
.Caption = OpArray(i)
.Height = 15
.Left = 8
.Top = TopPos
.Tag = i
.AutoSize = True
If Default = i Then .Value = True
If .Width > MaxWidth Then MaxWidth = .Width
End With
TopPos = TopPos + 15
Next i

'


Set NewCommandButton1 = TempForm.Designer.Controls. _
Add("forms.CommandButton.1")
With NewCommandButton1
.Caption = ""
.Height = 18
.Width = 44
.Left = MaxWidth + 12
.Top = 6
End With

'

OK
Set NewCommandButton2 = TempForm.Designer.Controls. _
Add("forms.CommandButton.1")
With NewCommandButton2
.Caption = "OK"
.Height = 18
.Width = 44
.Left = MaxWidth + 12
.Top = 28
End With

'

CommandButton
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code

=
=
=
=
=
=
=
=
=
=
=
=
=
=
=

""
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code

&
&
&
&
&
&
&
&
&
&
&
&
&
&

"Sub CommandButton1_Click()" & vbCrLf


" GETOPTION_RET_VAL=False" & vbCrLf
" Unload Me" & vbCrLf
"End Sub" & vbCrLf
"Sub CommandButton2_Click()" & vbCrLf
" Dim ctl" & vbCrLf
" GETOPTION_RET_VAL = False" & vbCrLf
" For Each ctl In Me.Controls" & vbCrLf
"
If TypeName(ctl) = ""OptionButton"" Then" & vbCrLf
"
If ctl Then GETOPTION_RET_VAL = ctl.Tag" & vbCrLf
"
End If" & vbCrLf
" Next ctl" & vbCrLf
" Unload Me" & vbCrLf
"End Sub"

With TempForm.CodeModule
.InsertLines .CountOfLines + 1, Code
End With

28. Visual Basic

715

'


With TempForm
.Properties("Caption") = Title
.Properties("Width") = NewCommandButton1.Left + _
NewCommandButton1.Width + 10
If .Properties("Width") < 160 Then
.Properties("Width") = 160
NewCommandButton1.Left = 106
NewCommandButton2.Left = 106
End If
.Properties("Height") = TopPos + 24
End With

'


VBA.UserForms.Add(TempForm.Name).Show

'


ThisWorkbook.VBProject.VBComponents.Remove VBComponent:=TempForm


GetOption = GETOPTION_RET_VAL
End Function
'

GetOption , ,
.
.
UserForm .

GETOPTION
GetOption .
OpArray , ,
OptionButton.
Default , OptionButton,
UserForm.
0, OptionButton.
Title , UserForm.

GETOPTION
GetOption .
1. VBE, UserForm
.
2. UserForm TempForm.
3. OptionButton.
, OpArray. Tag . Tag .
4. CommandButton:
OK .

716

VII.

5. CommandButton
.
6. UserForm:
CommandButton
UserForm.
7. UserForm . OK, CommandButton1_Click. , OptionButton ,
GETOPTION_RET_VAL (
Public).
8. UserForm .
9. GETOPTION_RET_VAL
.

UserForm VBA Extensibility Library. ,


( modOptionsForm).
GetOption.

GetOption.
UserForm (
Ops).
Sub TestGetOption()
Dim Ops(1 To 5)
Dim UserOption
On Error Resume Next
Dim x
Set x = ActiveWorkbook.VBProject
If Err <> 0 Then
MsgBox " ", vbCritical
On Error GoTo 0
Exit Sub
End If
Ops(1) = ""
Ops(2) = ""
Ops(3) = ""
Ops(4) = ""
Ops(5) = " "
UserOption = GetOption(Ops, 5, " ")
MsgBox Ops(UserOption)
End Sub

UserOption .
, UserOption
False.
. 28.9 UserForm,
.

. 28.9.
UserForm
GetOption

28. Visual Basic

717

UserForm , ,
. , UserOption
. ,
UserForm .

, GETOPTION

CommandButton. GetOption UserForm.
Sub CommandButton1_Click()
GETOPTION_RET_VAL = False
Unload Me
End Sub
Sub CommandButton2_Click()
Dim ctl
GETOPTION_RET_VAL = False
For Each ctl In Me.Controls
If TypeName(ctl) = "OptionButton" Then
If ctl Then GETOPTION_RET_VAL = ctl.Tag
End If
Next ctl
Unload Me
End Sub

, UserForm , VBE.
UserForm , , ('):
ThisWorkbook.VBProject.VBComponents.Remove _
VBComponent:=TempForm

718

VII.

29



...
,
, .


,
VBA . Excel 97
.

(class module) VBA,


. , . , Excel
. ,
, .


(. 15, 18, 19 23).

: ?. : . ,
. , . .
.
, . (
18).
. . ( 19 23.)

Windows API
. , , <NumLock> <CapsLock>.
, .
UserForm.
.
15 ,
CommandButton Click.
, ; .
, .

: NumLock
,
, . NumLock, : Value.
<NumLock> Windows API.
<NumLock>.
API, (
VBA). ? , .
VBA, <NumLock>
, Value.
MsgBox NumLock.Value

<NumLock>. ,
<NumLock>.
NumLock.Value = True

, NumLock
.
NumLock.Toggle

, , ,
.
VBA , .
,
. .


VBE
).
Class1. Properties
Properties

720

InsertClass Module (
,
, <F4>.
NumLock (. 29.1).

VII.

. 29.1. , NumLockClass

VBA
, Value.
<NumLock>,
Windows API,
<NumLock>. 29.1
.
29.1.
'
Private Type OSVERSIONINFO
dwOSVersionInfoSize As Long
dwMajorVersion As Long
dwMinorVersion As Long
dwBuildNumber As Long
dwPlatformId As Long
szCSDVersion As String * 128
End Type
' API
Private Declare Function GetVersionEx Lib "Kernel32" _
Alias "GetVersionExA" _
(lpVersionInformation As OSVERSIONINFO) As Long
Private Declare Sub keybd_event Lib "user32" _
(ByVal bVk As Byte, _
ByVal bScan As Byte, _
ByVal dwflags As Long, ByVal dwExtraInfo As Long)
Private Declare Function GetKeyboardState Lib "user32" _
(pbKeyState As Byte) As Long
Private Declare Function SetKeyboardState Lib "user32" _
(lppbKeyState As Byte) As Long
'
Const VK_NUMLOCK = &H90

29.

721

Const
Const
Const
Const
Const
Const

VK_SCROLL = &H91
VK_CAPITAL = &H14
KEYEVENTF_EXTENDEDKEY = &H1
KEYEVENTF_KEYUP = &H2
VER_PLATFORM_WIN32_NT = 2
VER_PLATFORM_WIN32_WINDOWS = 1

, <NumLock>. Value .
. Value .
, Property Get.

Property Get Value() As Boolean


'

Dim keys(0 To 255) As Byte
GetKeyboardState keys(0)
Value = keys(VK_SCROLL)
End Property

Property .
.

, Windows API GetKeyboardState,


<NumLock>. ,
VBA Value. , VBA,
, Property Get.
MsgBox NumLock.Value

, <NumLock>. : . Property Let


( 29.2).
29.2. Property Let
Property Let Value(boolVal As Boolean)
Dim o As OSVERSIONINFO
Dim keys(0 To 255) As Byte
o.dwOSVersionInfoSize = Len(o)
GetVersionEx o
GetKeyboardState keys(0)
'

If boolVal = True And keys(VK_SCROLL) = 1 Then Exit Property
If boolVal = False And keys(VK_SCROLL) = 0 Then Exit Property
'

If o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then '(Win95)
'
keys(VK_SCROLL) = IIf(keys(VK_SCROLL) = 0, 1, 0)
SetKeyboardState keys(0)
ElseIf o.dwPlatformId = VER_PLATFORM_WIN32_NT Then ' (WinNT)
'
keybd_event VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
'
keybd_event VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0
End If
End Property

722

VII.

Property Let ,
True, False. VBA, ,
Value NumLock True.
Property Let.
NumLock.Value = True

, NumLock ( 29.3).
29.3. Toggle
Sub Toggle()
'

Dim o As OSVERSIONINFO
o.dwOSVersionInfoSize = Len(o)
GetVersionEx o
Dim keys(0 To 255) As Byte
GetKeyboardState keys(0)
If o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then '(Win95)
'
keys(VK_SCROLL) = IIf(keys(VK_SCROLL) = 0, 1, 0)
SetKeyboardState keys(0)
ElseIf o.dwPlatformId = VER_PLATFORM_WIN32_NT Then ' (WinNT)
'
keybd_event VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
'
keybd_event VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0
End If
End Sub

, .
, .

NumLock
NumLockClass
. , VBA ( ), .
Dim NumLock As New NumLockClass

, NumLockClass (.. ). ,
NumLock .
Value NumLock
True. <NumLock>.
Sub NumLockOn()
Dim NumLock As New NumLockClass
NumLock.Value = True
End Sub

,
<NumLock> (True ,
False ).
Sub GetNumLockState()
Dim NumLock As New NumLockClass
MsgBox NumLock.Value
End Sub

29.

723

<NumLock>.
Sub ToggleNumLock()
Dim NumLock As New NumLockClass
NumLock.Toggle
End Sub

, <NumLock>
Toggle.

Sub ToggleNumLock2()
Dim NumLock As New NumLockClass
NumLock.Value = Not NumLock.Value
End Sub


-.
<CapsLock> <ScrollLock>.


,
Value. .
, .


, ,
. , Class1,
Class2 .. .


.
. ,
-.
.

VBE Auto List Members ,


. .
, ,
, , . , , Property Get.
Property Get.
Property Get FileNameOnly() As String
FileNameOnly = ""
For i = Len(FullName) To 1 Step -1
Char = Mid(FullName, i, 1)
If Char = "\" Then
Exit Function
Else
FileNameOnly = Char & FileNameOnly
End If
Next i
End Property

724

VII.

, Property Get . , .
FileNameOnly.
, FullName. , FullName
c:\windows\myfile.txt, myfile.txt.
FileNameOnly , VBA .
, , : Property Get ( ) Property Let ( ). , ,
( ) Property Get.
.
Property Get SaveAsExcelFile() As Boolean
SaveAsExcelFile = XLFile
End Property
Property Let SaveAsExcelFile(boolVal As Boolean)
XLFile = boolVal
End Property

, Property Let
Property Set.

, Public,
. Property Get Property Let, .
Public SaveAsExcelFile As Boolean

, , Property Let Property Get.


XLFile,
. Property Get
. FileSys,
SaveAsExcelFile.
MsgBox FileSys.SaveAsExcelFile

, Property Let
. , ( ), SaveAsExcelFile
True.
FileSys.SaveAsExcelFile = True

True Property Let,


.
XLFile. .
, .

. , VBA .
, .

29.

725


.
Sub Function,
. , , .
.
.

VBA,
. ,
.
XLFile. , .
Sub SaveFile()
If XLFile Then
ActiveWorkbook.SaveAs FileName:=FName, _
FileFormat:=xlWorkbookNormal
Else
ActiveWorkbook.SaveAs FileName:=FName, _
FileFormat:=xlCSV
End If
End Sub

, ,
, .


: Initialize Terminate.
Initialize ,
Terminate . Initialize
, .
.
Private Sub Class_Initialize()
'

End Sub
Private Sub Class_Terminate()
'

End Sub

( ), , , . , Nothing. , MyObject.
Set MyObject = Nothing

: CSVFile
, , ,
CSVFileClass. .

ExportRange .
, CSV.
ImportRange . , CSV.

726

VII.


Import
CSV, CSVFileName.
, ImportRange.
Export , ExportRange, CSV, CSVFileName.


,
. CSVFileClass , .
.
Private RangeToExport As Range
Private ImportToCell As Range

RangeToExport Range,
. ImportToCell Range,
,
CSV. Property Get
Property Let (. ).


CSVFileClass 29.4.
Property Get , Property Let .
29.4. CSVFileClass
Property Get ExportRange() As Range
Set ExportRange = RangeToExport
End Property
Property Let ExportRange(rng As Range)
Set RangeToExport = rng
End Property
Property Get ImportRange() As Range
Set ImportRange = ImportToCell
End Property
Property Let ImportRange(rng As Range)
Set ImportToCell = rng
End Property


CSVFileClass ,
. .

EXPORT
Export, 29.5,
Export. : , . -

29.

727

. ,
ExportRange. RangeToExport. .
29.5.

Sub Export(CSVFileName)
'
CSV
Dim ExpBook As Workbook
If RangeToExport Is Nothing Then
MsgBox " "
Exit Sub
End If
On Error GoTo ErrHandle
Application.ScreenUpdating = False
Set ExpBook = Workbooks.Add(xlWorksheet)
RangeToExport.Copy
Application.DisplayAlerts = False
With ExpBook
.Sheets(1).Paste
.SaveAs FileName:=CSVFileName, FileFormat:=xlCSV
.Close SaveChanges:=False
End With
Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
ErrHandle:
ExpBook.Close SaveChanges:=False
Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox " " & Err & vbCrLf & vbCrLf & Error(Err), _
vbCritical, " "
End Sub

Export
RangeToExport .
CSV, .
, .
(, ), ErrHandle
, .

IMPORT
Import, 29.6,
CSV, CSVFileName. , ImportToCell.
ImportRange. . Export, Import .

728

VII.

29.6.

Sub Import(CSVFileName)
'
CSV
Dim CSVFile As Workbook
If ImportToCell Is Nothing Then
MsgBox " "
Exit Sub
End If
If CSVFileName = "" Then
MsgBox " "
Exit Sub
End If
On Error GoTo ErrHandle
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open CSVFileName
Set CSVFile = ActiveWorkbook
ActiveSheet.UsedRange.Copy Destination:=ImportToCell
CSVFile.Close SaveChanges:=False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
ErrHandle:
CSVFile.Close SaveChanges:=False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox " " & Err & vbCrLf & vbCrLf & Error(Err), _
vbCritical, " "
End Sub

CSVFileClass
CSVFileClass VBA,
, CSVFileClass.
.
Dim CSVFile As New CSVFileClass

,
, . Dim Set.
Dim CSVFile As CSVFileClass
'
Set CSVFile = New CSVFile

Dim Set , , Set.


: , . , , , . , Set .
, ,
.

29.

729

VBE Auto List Members .


,
.

CSV, temp.csv.
, .
Sub ExportARange()
Dim CSVFile As New CSVFileClass
With CSVFile
.ExportRange = ActiveWindow.RangeSelection
.Export CSVFileName:=ThisWorkbook.Path & "\temp.csv"
End With
End Sub

With-End With . ,
.
Sub ExportARange()
Dim CSVFile As New CSVFileClass
CSVFile.ExportRange = ActiveWindow.RangeSelection
CSVFile.Export CSVFileName:=ThisWorkbook.Path & "\temp.csv"
End Sub


CSV. , .
Sub ImportAFile()
Dim CSVFile As New CSVFileClass
With CSVFile
On Error Resume Next
.ImportRange = ActiveCell
.Import CSVFileName:=ThisWorkbook.Path & "\temp.csv"
End With
If Err <> 0 Then _
MsgBox " " & ThisWorkbook.Path & "\temp.csv"
End Sub

VBA .
CSVFileClass.
Sub Export3Files()
Dim CSVFile(1 To 3) As
CSVFile(1).ExportRange
CSVFile(2).ExportRange
CSVFile(3).ExportRange

New CSVFileClass
= Range("A1:A20")
= Range("B1:B20")
= Range("C1:C20")

For i = 1 To 3
CSVFile(i).Export CSVFileName:="File" & i & ".csv"
Next i
End Sub

730

VII.

30



Excel
...
, Internet, , FAQ
(). (frequently asked questions) (
), . , , ,
. , .
Excel
, ?
,
VBA, ,
Excel 97 .
,
. ( ) .
microsoft.public.excel.*.
comp.apps.spreadsheet.
Microsoft.
, .

...
. , . , , , A.

.
.
Excel.
Visual Basic.

.
, , .
.
.
CommandBar.
,
.
, .
, , , .

Excel
EXCEL
?
Excel , XLM.
VBA Excel 5, XLM.
XLM ,
VBA.


EXCEL 4.
XLM?
. Excel 97,
VBA. , Excel,
, .

EXCEL 97 ,
XLM?
.

,
EXCEL 4 VBA. ?
. , , .
. Excel
XLM, , . , Excel.

VBA XLM
EXCEL 4?
. XLM RUN. , Test, Module1
Book1.xls.
=RUN(Book1.xls!Module1.Test)

732

VII.


LOTUS 16263
QUATTRO PRO VBA?
. Excel .

VBA?
Internet VBA.
http://www.j-walk.com/ss/


EXCEL EXE6?
, .

,

?
. ,
. , ,
. .
,
. , .
, , . .

,

?
. (, ListEntries).
=ListEntries .
, ,
.

APPLICATION.CALCULATION
.
,
.
Calculation Application. , .
. Excel 2000
Worksheet, EnableCalculation.
False, ,
. True .

?
.
. Microsoft .

30. Excel

733

?
, .


?
Excel 2002 ,
. Excel .


?
, Excel. Windows
. :
. . .
.


, ?
. Windows .
: .
.
.
.

EXCEL?
. WAV MIDI, Windows API ( 11). Excel 2002 ,
Speech. (, ).
Application.Speech.Speak ("" & Application.UserName)

EXCEL .
?
Excel *.xlb,
. ,
. . *.xlb 500 .
Excel ,
*.xlb. . . Excel
.


?
Excel 2002 , . ,
.
, ,
. :

734

VII.

, ( ).
Excel VBA WorkbookBeforePrint. ,
.
.
Private Sub Workbook_BeforePrint(Cancel As Boolean)
For Each sht In ThisWorkbook.Sheets
sht.PageSetup.LeftHeader = ThisWorkbook.FullName
Next sht
End Sub

Visual Basic
EXCEL 95 VBA
, EXCEL 97,
.
, , , VBE.
<Alt+F11> Excel VBE.

VBA
?
. . , , ,
.
, .

EXCEL 95
, ,
.
?
. , Excel 97.
, , .

,
.
?
. ()
, Excel .
.
Personal.xls \XLStart.

.
?
Personal.xls ,
.

30. Excel

735

VBA
. ?
, . Web. Excel password. , Excel ,
.


?
. VBA
. , .


OPTION EXPLICIT. ?
Option Explicit , , ,
( ). ,
, VBE ToolsOptions ().
Editor () Require Variable Declaration
( ). VBA.

VBA ?
?
VBA : ,
, , ..
, , ,
, .. ToolsOptions ( Editor Format ( )) VBE.

VBA VBA.
?
. Module1 .
With ActiveWorkbook.VBProject
.VBComponents.Remove .VBComponents("Module1")
End With

Excel 2002 .
.

EXCEL 2000, VBA


. EXCEL 2003,
. ?
Excel 2002 : Visual Basic Project.
. ,

.

736

VII.


?
,
.
VBA . .


.
! ?
, . , VBA,
.

, USERINTERFACEONLY
.
.
ActiveSheet.Protect UserInterfaceOnly:=True

, . ,
. ,
, UserInterfaceOnly.

, ?
VBE , .
VBA, . .
.


(&) VBA.
, .
, VBA .
, .


VBA ().
:
.

VBA
, XLS
. ?
Excel .
, .
,
.

30. Excel

737

XLS
.
. ?
,
Break on All Errors ( ).
Options ( General ()) VBE. ,
VBA. , XLA.

VBA ?
. (macro)
. .

?
VBA, .
(, ) ,
,
Function. Sub.

?
, ,
. VBA . , , . . Dim, Public Private.
.


?
: ( ). , .
Dim X As Variant
X = Array(30, 40, 50)

,
( ). , 3- .
Dim X (0 To 2) As Variant

, , Variant, , .

738

VII.

?
VBA ,
. , MyVar,
integer. %.
Dim MyVar%

, VBA.

Integer

Long

&

Single

Double

Currency @

String

VBA,
.
, .
?
VBA, ,
. ,
, ,
.
, .
.
VBA MsgBox.
.
.

,
, .
, , 0,
. ?
, .
Excel .
.

,

.
Change . - , Change.
Sheet () Worksheet_Change,
Change .

?
!
.

30. Excel

739


(SUB WORKBOOK_OPEN),
. ?
, , .
ThisWorkbook
().
Sheet (), Project VBE.


.

?
, .
19.

EXCEL. VBA
?
. , VBA ,
. .

\
Eqv


True, True
False



True , True

Imp
Is
Like
Xor

,
?
Run Application. Macro1, Personal.xls.
Run "Personal.xls!Macro1"

. ToolsReferences VBA.

VBA

,
.
?
. , Excel.
, .

740

VII.

, , ,
. ,
ToolsReferences VBE.

,
, EXCEL. ,
EXCEL
. ?
? , \XLStart.
, Workbook_Open .

,
WORKBOOK_OPEN.

?
. <Shift> .
Workbook_BeforeClose,
<Shift> . <Shift> .

VBA
?
VBA , XLM. , XLM VBA. A1 Sheet1
myfile.xls, c:\files.
MsgBox ExecuteExcel4Macro("'c:\files\[myfile.xls]Sheet1'!R1C1")

, R1C1.



VBA?
.
ActiveWorkbook.Close SaveChanges:=False

Saved Workbook
True. .
ActiveWorkbook.Saved = True

,
.
Excel .
Application.DisplayAlerts = False

30. Excel

741

,
?
OnTime Application.
,
. ,
OnTime, .

,
?
Private.
Private Sub MyMacro()

.
Sub MyMacro (Optional FakeArg as Integer)


GIF?
.
1 GIF Mychart.gif.
Set CurrentChart = Sheets("1").ChartObjects(1).Chart
Fname = ThisWorkbook.Path & "\Mychart.gif"
CurrentChart.Export Filename:=Fname, FilterName:="GIF"

VBA
VBA? ,
?
.
: , ().
.
,
.
, .
, .

Public.

.



.
?
, ,
.
. ,

742

VII.

. .
.



?
, .



. ?
VBA. MyFunc 1 ( ).
Application.MacroOptions Macro:="MyFunc", Category:=1

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

( )

( )
( )
( )
DDE/External ( )
( )
( , )

?
XLM. ,
.

,
. ,

(#!)?
MyFunction, , .

30. Excel

743

MyFunction = CVErr(xlErrValue)

xlErrValue .
.

,
?
<Ctrl+Alt+F9>.

EXCEL
VBA?
. Excel
WorksheetFunction Application. ,
POWER () , .
Ans = Application.WorksheetFunction.Power(5, 3)

5 , (125).
VBA ,
. , VBA (Sqr), SQRT VBA .

EXCEL 95 WORKSHEETFUNCTION.
, EXCEL 2003
EXCEL 95?
. WorksheetFunction .
.
Ans = Application.WorksheetFunction.Power(5, 3)
Ans = Application.Power(5, 3)

VBA
?
, . Excel Analysis ToolPak
VBA. VBA ToolsReferences (
). atpvbaen.xls,
. .
, CONVERT
, 5000 .
MsgBox CONVERT(5000, "m", "mi")


?

. , , . vbCr ,
.
MsgBox "Hello" & vbCr & Application.UserName

744

VII.

, ,
.
EXCEL, ?
. .

.
,
?
. Object Browser, VBE. <F2> Object Browser Excel Libraries/Workbooks ( ). Classes ()
() Excel. Members ().
,
. , .
Range("A1").

Range. , ToolsOptions,
Editor Auto List Members.
VBA .
, . Immediate
VBE
<F1>. , .

?
? ?
, .
. , Worksheets , Worksheet
. : Worksheets(1)
Worksheet Workbooks. , , , Worksheets("1").
.
For Each-Next.

VBA ,
"SUBSCRIPT OUT OF RANGE".
. ?

. , ,
, MySheet.
Set X = ActiveWorkbook.Worksheets("MySheet")

30. Excel

745


?
, VBA . 1 ,
B2:D50.
Worksheets("1").ScrollArea = "B2:D50"

,
.
Worksheets("1").ScrollArea = ""

, ScrollArea
. , .
Workbook_Open.

SELECT
APPLICATION.GOTO?
Select Range
. Application.Goto
. Application.Goto ,
. , Goto
, .


?
Activate Select . . , A1:C3. C3.
, C3 , .. .
Range("C3").Activate

, A1:C3 . , .
Range("C3").Select


?
.
, ( ).
On Error Resume Next
Cells.SpecialCells(xlCellTypeConstants, 23).ClearContents

On Error Resume Next


, , .

746

VII.

, VBA
, . ,
,
?
Cells.
(.. L5).
Cells(5, 12).Select

VBA EXCEL?
, EXCEL
,
!
Excel .
Application.Quit


?

, .
Application.ScreenUpdating = False

VBA
?
,
.
Range("D14:G20").Select
ActiveWorkbook.Names.Add Name:="InputArea", _
RefersToR1C1:="=1!R14C4:R20C7"

.
Sheets("1").Range("D14:G20").Name = "InputArea"

,
?
Name Name,
Range.
, .
, False.
Function RangeName(rng) As Variant
On Error Resume Next
RangeName = rng.Name.Name
If Err <> 0 Then RangeName = False
End Function

30. Excel

747


,
?
. .
ActiveSheet.PrintPreview EnableChanges:=False

EnableChanges PrintPreview
, Object Browser.


Application. .

StatusBar

Application.StatusBar = " " & FileNum

.
Application.StatusBar = False

VBA,
.
SELECT.
?
. ,
.
VBA,
. Select.
Range("A1").Select
Selection.Copy
Range("B1").Select
ActiveSheet.Paste

,
.
Range("A1").Copy Range("B1")

,
Select.

VBA. ,

RANGE.SORT?
VBA . , . , VBA.
VBA .

748

VII.

,
,
. ,
?
VBA TypeName, Selection. .
If TypeName(Selection) <> "Range" Then
MsgBox " !"
Exit Sub
End If

RangeSelection,
Range, .
,
. Window,
Workbook. .
MsgBox ActiveWindow.RangeSelection.Address

,
.
If ActiveChart Is Nothing Then MsgBox " !"

,
( , ).

VBA ,
. SELECTION.ROWS.COUNT
, .
?
. Count
(,
). , VBA
. Selection.Area.Count, . ,
NumRows.
NumRows = 0
For Each areaCounter In Selection.Areas
NumRows = NumRows + areaCounter.Rows.Count
Next areaCounter

, .

EXCEL .
?
.
.
Counter = GetSetting("XYZ Corp", "InvoiceNum", "Count", 0)
Counter = Counter + 1
SaveSetting "XYZ Corp", "InvoiceNum", "Count", Counter

30. Excel

749

, Counter.
.
Counter .

EXCEL,

?
, .

EXCEL,
? ,
,
.
Excel:
Application.DisplayAlerts = False

VBA
? ,
<CTRL+SHIFT+
> <CTRL+SHIFT+ >
, ?
<Ctrl+Shift+ > VBA

Selection.End(xlDown).Select

: xlToLeft, xlToRight
xlUp.


?

.
MsgBox ActiveSheet.Range("A65536").End(xlUp).Address

, 65536 .
MsgBox ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Address

, A65536
!
, .
With ActiveSheet.Cells(Rows.Count, 1)
If IsEmpty(.Value) Then
MsgBox .End(xlUp).Address
Else
MsgBox .Address
End If
End With

750

VII.

VBA ,

.
?
. Set .
.
Dim MyRange as Range
Set MyRange = ThisWorkbook.Worksheets("1").Range("A1")

Set Range
MyRange. ,
.
MyRange.Value = 10

,
.

,
, ?
. Dim.
. ,
, ReDim, . ReDim Preserve .


?
, . ,
VBA , .
.
, OnUndo .
, , , .
Application.OnUndo " ", "MyUndoMacro"

LOTUS 16263,

.
VBA?
Excel ,
Excel InputBox,
. , ,
. , A1.
UserVal = Application.InputBox(prompt:=" ", Type:=1)
If UserVal <> False Then Range("A1") = UserVal

30. Excel

751

VBA INPUTBOX,
APPLICATION.
?
. Excel InputBox ,
. Type InputBox ( ). ,
.

RGB
.
?
, . Excel 56
( 56 ). RGB ,
Excel .

VBA,
. , ,
(") . ?
, VBA
B1.
=(A1="";;)

.
Range("B1").Formula = "=IF(A1="Yes",TRUE,FALSE)"

. .
Range("B1").Formula = "=IF(A1=""Yes"",TRUE,FALSE)"

VBA Chr 34.


. .
Range("B1").Formula = _
"=IF(A1=" & Chr(34) & "Yes" & Chr(34) & ",TRUE,FALSE)"

,
. ?
, VBA 0
. , 1,
VBA.
Option Base 1

, .
Dim Months(1 To 12) As String

752

VII.

VBA
. ?
. , . Option Explicit ,
. Excel
, .
With-End With , . ,
Application.ScreenUpdating = False. ,
, , .


,
USERFORM
. ?
. VBA MsgBox InputBox. , Excel InputBox.

, USERFORM
12 COMMANDBUTTON.
,
?
,
CommandButton Click.

CommandButton_Click.
(. 15).


USERFORM?
.
,
GIF GIF Image.

X
USERFORM?


UserForm
Windows API.
.
UserForm_QueryClose, UserForm.
,
.
Private Sub UserForm_QueryClose _
(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then

30. Excel

753

MsgBox " "


Cancel = True
End If
End Sub

USERFORM,

CONTROLSOURCE.
?
,
, . , ,
.


USERFORM?
VISUAL BASIC 6.0, ,
VBA.
,
Control. ,
CommandButton.
Private
Dim
Cnt
For

Sub UserForm_Initialize()
Buttons() As CommandButton
= 0
Each Ctl In UserForm1.Controls
If TypeName(Ctl) = "CommandButton" Then
Cnt = Cnt + 1
ReDim Preserve Buttons(1 To Cnt)
Set Buttons(Cnt) = Ctl
End If
Next Ctl
End Sub


USERFORM ?
. Hide UserForm , . Unload , ( Terminate UserForm)
UserForm .

USERFORM
?
UserForm
. , . Excel 2000,
UserForm. Show vbModeless.
.
UserForm1.Show vbModeless

754

VII.

EXCEL ,
USERFORM1.SHOW
VBMODELESS.
EXCEL 2003, EXCEL 97?
, Excel ,
. .
Sub ShowUserForm()
If Val(Application.Version) >= 9 Then
ShowModelessForm
Else
UserForm1.Show
End If
End Sub
Sub ShowModelessForm()
Dim frm As Object
Set frm = UserForm1
frm.Show 0 ' vbModeless
End Sub

ShowModelessForm Excel 97,


.


,
. ?
UserForm. 15 , , .

EXCEL,

USERFORM?

, .
. .
UserForm Image.
<F4> Properties. Picture <Ctrl+V>,
Image. ,
AutoSize True.


USERFORM,
?
UserForm . VBA GetOpenFilename. , , .

30. Excel

755

LOTUS 16263 WINDOWS


QUATTRO PRO WINDOWS,
.

EXCEL?
, .


LISTBOX.

.
?
,
Courier New. ListBox
( 14).


EXCEL VBA?
( ) Excel
Application.Dialogs. , , .
Application.Dialogs(xlDialogFormatNumber).Show

, ,
Object Browser. VBE <F2>, Excel xlDialog. , .

,
, .
?
Dialogs , .
,
(xlDialogChartType), , .

USERFORM
OK .
?
. UserForm,
, . FileExport
File ( ) .
,
FileImport File ( ).


USERFORM ?
. , , ,
Caption .

756

VII.

VBA,
.

.
Excel 2000. Excel 2000
PrToFileName PrintOut. .
ActiveSheet.PrintOut PrintToFile:=True, _
PrToFileName:="test.prn"

USERFORM,
. ?
, UserForm,
, .
UserForm,
.

,
,
?
, ,
? , Zoom UserForm .
, 640480.


USERFORM,
?
. RefEdit.
14.


USERFORM?
. Left Top UserForm. ,
StartUpPosition 0.


EXCEL 5/95?
.
. Excel 5.0. , Excel 5/95.

30. Excel

757


EXCEL?
Excel .
Excel ,
.
Microsoft Office Update.
, .

Web-.
.

?

. , , ,
VBA.



. ?

, . .
,
. . .

,
, ,
. ?
, Excel.
, .
, .
Excel
.

?
.
Microsoft Excel (*.xla).

,

.
, .

758

VII.


?
! ,
, .
, .
.


: XLS XLA?
Excel 97 .
Excel 97, . .

?
VBE ( <Alt+F11>)
IsAddIn ThisWorkbook False. , IsAddIn True .

XLS XLA,
XLS?
XLA? , ?
, . VBA .
XLS, XLA. XLA VBA, .


?
VBE Toolsxxx Properties ( xxx)
( xxx ). Protection ()
Lock project from viewing ( ), .

? ,
XLA, ,
?
. . Excel , . ,
.

CommandBar
EXCEL 95 , EXCEL 97
. ?
Excel 97, Excel .
CommandBar. Excel,
( ).

30. Excel

759

,
EXCEL 95?
, Excel 95.



.
?
VBA, , VBA, .

, FACEID
.
FACEID
?
Microsoft ,
,
FaceId . 22 .


, EXCEL
. EXCEL ?
Excel , , . VBA,
.
, VBA,
.


EXCEL.
?

. .
Sub ResetAllToolbars()
For Each tb In CommandBars
If tb.Type = msoBarTypeNormal Then
If tb.BuiltIn Then tb.Reset
End If
Next tb
End Sub

, ,
, .


.
WorkbookActivate WorkbookDeactivate. , ,
, , ,
, .

760

VII.


?
BeginGroup ,
, True.

?
, ,
State. My Item.
CommandBars(1).Commands("MyMenu"). _
Commands("My Item").State = msoButtonDown

, State msoButtonUp.


. EXCEL


. .

?
.
Sub DisableAllShortcutMenus()
Dim cb As CommandBar
For Each cb In CommandBars
If cb.Type = msoBarTypePopup Then _
cb.Enabled = False
Next cb
End Sub

,

?
. .
CommandBars("Toolbar List").Enabled = False

30. Excel

761

,
Excel
, , , . , ,
. , , . ,
, Excel. .
Microsoft.
.
Web-.


Microsoft
.
. ,
Microsoft.
Microsoft .


,
. . ,
, Microsoft. .
, . ,

( ). , , .

URL,
, Internet , . Web-
( ,
microsoft.com). , URL, , . URL , , , ,
.

, , ,
.
.

Microsoft
Microsoft Knowledge Base ( Microsoft).
Microsoft , , , , ..
Internet . http://support.microsoft.com/.

Microsoft Excel
Microsoft Excel
http://www.microsoft.com/office/excel/.

Microsoft Office
, Office (
Excel), : http://office.microsoft.com/.


Usernet Internet, , .
, . ,
, (
, , ). , , 24 (,
, ).

Internet, , .
Microsoft Outlook Express
.

,
, , comp.apps.spreadsheet. , 90% Excel.
? Microsoft.

Microsoft
Microsoft ,
Excel . Microsoft,
, Microsoft. msnews.microsoft.com.

764

. , Excel

. .1 ,
.

.1. Microsoft, Excel

microsoft.public.excel.programming

Excel
VBA XLM

microsoft.public.excel.123quattro

Lotus
1-2-3 Quattro Pro Excel

microsoft.public.excel.worksheet.functions

microsoft.public.excel.charting


Excel

microsoft.public.excel.printing

Excel

microsoft.public.excel.queryDAO

Microsoft Query
Data Access Objects (DAO) Excel

microsoft.public.excel.datamap

Excel
Data Map

microsoft.public.excel.crashesGPFs


General Protection Fault

microsoft.public.excel.misc

microsoft.public.excel.links

Excel

microsoft.public.excel.macintosh

, Excel
Macintosh

microsoft.public.excel.interopole

OLE, DDE

microsoft.public.excel.setup

Excel

microsoft.public.excel.templates

Spreadsheet Solutions
XLT

microsoft.public.excel.sdk

,
Excel Software Development Kit


,
.
, .
.
http://groups.google.com/

Deja.com.
, Google.

. , Excel

765


1. , . FAQ ( ) Google (
" " ).
2. . ! Excel , VBA
Excel 2002.
3. ,
.
Excel.
4. , .
5. , , .
, .
6. , .
7. ,
, .
8. .
.
9. .
10. HTML.
11. , , .
, ?

? , ListBox, UserForm. : Excel, ListBox


UserForm. Google , .
, ,
.

Web6
Internet , Excel.
.

Spreadsheet Page
Web- . ,
, . , ,
Excel,
, . , . http://j-walk.com/ss/

766

. , Excel

, Excel,
, . (, !)

Web6 , Excel
Pearson Software Consulting.
VBA, .
http://www.cpearson.com.

Web6 , Excel
Excel .
Business Modelling Solutions, Ltd.
VBA Excel, , .
http://www.bmsltd.co.uk/excel/.

,

. , .
comp.apps.spreadsheet
http://www.faqs.org/faqs/spreadsheets/faq.

. , Excel

767


VBA
VBA
.
Excel.

Excel 2002 Excel 2003 VBA .

.1. VBA

AppActivate

Beep

Call

ChDir

ChDrive

Close

Const

Date

Declare

DLL

DefBool

Boolean ,

DefByte

Byte ,

DefDate

Date ,

DefDec

Decimal ,

DefDouble

Double ,

DefInt

Integer ,

DefLng

Long ,

DefObj

Object ,

. .1

DefSng

Single ,

DefStr

String ,

DefVar

Variant ,

DeleteSetting

Dim

Do-Loop

End

, ;
, End , If, Sub, Function, Property,
Type Select

Enum*

Erase

Error

Event*

Exit Do

Do-Loop

Exit For

Do-For

Exit Function

Function

Exit Property

Exit Sub

FileCopy

For Each-Next

For-Next

Function

Function

Get

GoSub...Return

GoTo

If-Then-Else

Implements*

Input #

Kill

Let

Line Input #

Load

Lock...Unlock

Lset

Mid

MkDir

Name

770

. VBA

. .1

On Error

On...GoSub

On...GoTo

Open

Option Base

Option Compare

Option Explicit

Option Private

, Private

Print #

Private

Property Get

Property Get

Property Let

Property Let

Property Set

Property Set

Public

Put

RaiseEvent

Randomize

ReDim

Rem

( , ['])

Reset

Resume

RmDir

Rset

SaveSetting

Seek

Select Case

SendKeys

Set

SetAttr

Static

Stop

Sub

Sub

Time

Type

Unload

While...Wend

Width #

With

Write #

. VBA

771

Excel
VBA
VBA , Excel,
Excel VBA.
WorksheetFunction. , VBA . Excel
, VBA.
Deg = Application.WorksheetFunction.Degrees(3.14)

WorksheetFunction Excel 97. Excel WorksheetFunction


, .
Deg = Application.Degrees(3.14)

Excel 2002 Excel 2003 VBA .

.2. VBA

Abs

Array

Asc

ASCII

Atn

CallByName

Cbool

Boolean

Cbyte

Byte

Ccur

Currency

Cdate

Date

CDbl

Double

Cdec

Decimal

Choose

Chr

Cint

Integer

CLng

Long

Cos

CreateObject

OLE Automation

CSng

Single

CStr

String

CurDir

Cvar

Variant

CVDate

Date (
; )

772

. VBA

. .2

CVErr

Date

DateAdd

DateDiff

DatePart

DateSerial

DateVAlue

Day

DDB

Dir

DoEvents

Environ

EOF

True,

Err

Error

Exp

(e),

FileAttr

FileDateTime

FileLen

Filter

Fix

Format

FormatCurrency*

( )

FormatDateTime

FormatNumber

FormatPercent

FreeFile

FV

GetAllSettings

GetAttr

GetObject

OLE Automation

GetSetting

Hex

Hour

IIF

. VBA

773

. .2

Input

InputBox

InStr

InStrRev*

Int

Ipmt

IRR

IsArray

True,

IsDate

True,

IsEmpty

True,

IsError

True,

IsMissing

True,

IsNull

True, Null

IsNumeric

True,

IsObject

True,
OLE Automation

Join

LBound

LCase

Left

Len

Loc

LOF

Log

LTrim

Mid

Minute

MIRR

Month

MonthName

MsgBox

Now

NPer

NPV

Oct

774

. VBA

. .2

Partition

, ,

Pmt

Ppmt

PV

QBcolor

RGB

Rate

Replace*

RGB

, RGB

Right

Rnd

0 1

Round

RTrim

Second

Seek

Sgn

Shell

Sin

SLN

Space

Spc

Split*

Sqr

Str

StrComp

StrConv

String

StrReverse*

Switch

,
, True

SYD

Tab

Tan

Time

Timer

, ,

TimeSerial

TimeValue

Trim

TypeName

Ubound

. VBA

775

. .2

UCase

Val

VarType

Weekday

WeekdayName*

Year

* Excel 97 .

776

. VBA

VBA
, . .
Excel.

Return GoSub

(, Integer)

.
, . , , Excel
Windows (, , )

.
, .
, Sheets("Sheet2"), Sheet2

10

11

13

14

16

17

18

. ,
,

20

. ,
Exit Sub

28

35

47

DLL

48

DLL

49

DLL

51

52

53

54

55

57

58

59

61

62

63

67

68

70

71

74

75

76

91

With .
, Set
. ,
, (,
ActiveCell),

92

For

93

94

Null

96

97

98

321

322

325

380

381

382

Set

383

Set ( )

385

387

Set

393

Get

394

Get ( )

422

423

424

. ,

778

. VBA

429

ActiveX ( , )

430

432

438

440

442


. OK

443

Automation ,

445

446

447

448

449

450

451

Property Let Property Get


452

453

DLL

454

455

457

458

Automation, Visual Basic

459

460

461

462

463

481

482

735

TEMP

744

746

1004

, . . , VBA. , Excel ( ) VBA. , (


Raise Err), VBA

. VBA

779

6
-.


, , .
, , , -.
Windows 9x, Windows 2000, Windows NT4 (c SP4 ), Windows Me
Windows XP:
120
.
32 . 64 .
-.

6 Windows
-
.
1. - -.
2. .

Install: / ,
.
Explore: -.
eBook: .
Exit: .


, ,
- . ,
3 Examples\chap 03\(\ 03).
.
.

3
array examples.xls .

count and sum.xls .


megaformula-1.xls (
).
megaformula-2.xls
().
megaformula-3.xls
VBA.
named formula.xls .
xdate.exe Extended Date Functions.

4
\amortizations ,
, .
employee list.xml XML-, .
message.xml XML-,
.

6
controls on sheet.xls
.

7
comment objects.xls VBA, Comment.
hello world.xls VBA-, .

8
timing test.xls , .

9
sheet sorter.xls .

10
commission.xls Commission, .
draw.xls Draw,
.
key press.xls API
<Shift>, <Ctrl> <Alt>.
month names.xls MonthNames,
.
mysum.xls MySum,
Excel .

782

. <

reverse.xls Reverse, , .
uppercase.txt UpCase,
Excel .
win32api.xls Windows API.
windows directory.xls ShowWindowsDir,
API Windows.

11
about selection.xls , .
auto average.xls AVERAGE,
. , : Enter Average Formula.
batch processing.xls . : text01.txt, text02.txt
text03.txt.
cell type.xls CellType .
data type.xls CellType , .
date and type.xls ,
.
delete empty rows.xls
.
disk info.xls API,
.
extract element.xls ExtractElement.
file association.xls API,
, .
fill range.xls , .
find by format.xls .
in range.xls , True,
.
inputBox.xls VBA InputBox
.
last saved and printed.xls LastSaved LastPrinted,
.
list fonts.xls .
max all sheets.xls MaxAllSheets,
.
next empty row.xls
.

. <

783

page count.xls , ,
.
play sound.xls Alarm,
sound.wav .
printer info.xls API, .
random functions.xls RandomIntegers ( )
RangeRandomize ( ).
range selections.xls .
Selection Demo.
registry.xls API,
.
select max.xls , .
selective color.xls
.
sheet offset.xls SheetOffset.
sorting demo.xls VBA,
.
sound.xls API, .
sound.wav , sound.xls.
stat functions.xls StatFunction.
synchronize sheets.xls .
toggles.xls .
utility functions.xls : FileExists,
FileNameOnly, PathExists, RangeNameExists, SheetExists WorkBookIsOpen.
variant transfer.xls , .
video mode.xls API,
.
worksheet functions.xls :
SheetName,
WorkbookName,
AppName,
CountBetween,
LastInColumn,
LastInRow IsLike.
write and read range.xls
.

12
erase a range.xls InputBox
.
get a filename.xls GetOpenFilename.
get directory.xls API , .

784

. <

get user name.xls InputBox


.

13
controls on sheet.xls
( ) .
controls on sheet2.xls , .
get name and sex.xls , 13.
newcontrols.pag , Toolbox ( ) VBE.
Toolbox
Import Page ( ).
spinbutton events.xls ,
SpinButton.
spinbutton textbox.xls
SpinButton TextBox.
userform events.xls ,
UserForm.

14
change size.xls UserForm .
fill listbox.xls
ListBox.
listbox activate sheet.xls ,
ListBox
listbox item transfer.xls
ListBox.
listbox move items.xls ListBox.
listbox select rows.xls ListBox,
.
multicolumn listbox.xls ListBox,
,
.
multicolumn listbox2.xls ListBox,
, .
multiple lists.xls
ListBox.
queryclose.xls ,
UserForm .
refedit.xls RefEdit.
selected items.xls
ListBox.

splash.xls - .

. <

785

unique1.xls ListBox .
unique2.xls ListBox .
userform menus.xls ,
CommandButton ListBox.
zoom and scroll sheets.xls
.
zoom.xls Zoom .

15
\dataform ,
Excel . .
chart in userform.xls UserForm.
color picker.xls ,
.
modeless userform.xls
UserForm, .
modeless userform2.xls UserForm,
.
multiple buttons.xls
.
my msgbox.xls MyMsgBox,
VBA MsgBox.
owc chart - simple.xls UserForm.
Office Web Components.
owc chart - advanced.xls UserForm
Office Web Components.
owc spreadsheet.xls
Spreadsheet, Office Web Components.
progress-1.xls . ( UserForm.)
progress-2.xls . ( UserForm.)
progress-3.xls
. (
UserForm.)
wizard.xls , .

16
\helpsource HTML- Text Tools.
text tools.xls ,
15 ( ).
text tools.chm .
undo.xls ,
VBA.

786

. <

17
budget.xls
( VBA).
budget.mdb Access, .
external db.xls
( VBA).
budget.mdb.
modify pivot.xls VBA, .
simple db.xls ,
. , .
survey data.xls
.

18
animated chart.xls .
autofilter chart.xls
.
chart active cell.xls
.
chart formatting.xls , .
chart image map.xls , -.
chart in userform.xls
.
climate date.xls ,
.
clock hart.xls ,
() .
combobox chart.xls
ComboBox .
convert chart to picture.xls ,
.
create chart.xls , .
, .
dailysales.xls .
data labels.xls .
events - chart sheet.xls .
events - embedded.xls
.

. <

787

get chart range.xls , Range, .


hypocycloid animated.xls ,
, .
hypocycloid.xls ,
.
mouseover event chart sheet.xls ( ).
mouseover event embedded.xls
( ).
multipe charts.xls .
printed embedded chart.xls
.
size and align charts.xls
.

19
application events.xls Application.
UserForm,
Excel 2000
.
log workbook open.xls .
make formulas bold.xls .
onkey demo.xls OnKey .
selection change.xls SelectionChage
Worksheet .
track changes in comments.xls ,
, .
validate entry1.xls . EnableEvents.
validate entry2.xls .
EnableEvents .

20
automate Excel.doc Microsoft Word,
Excel.
projectsion.xls.
budget.mdb Access, .
control panel dialogs.xls 50 .
make memos.xls
Microsoft Word, , .

788

. <

personalized email OE sendkey.xls Excel Outlook.


personalized email Outlook.xls
Excel Outlook.
simple ado example.xls Microsoft Access
( budget.mdb).
start calculator.xls ( ) Microsoft
Calculator ().
start charmap.xls
Microsoft Character Map ( ).

21
is addin installed.xla , .
text tools.xls ,
16.

22
autosense.xls , , .
button styles.xls
CommandBarButton.
hide and restore.xls .
list all controls.xls , Caption .
list commandbars.xls , , CommandBar.
month list.xls
CommandBar.
number format toolbar.xls ,
.
show face ids.xls FaceId
.

23
add new menu.xls .
add to Tools menu.xls .
hide menu.xls
.
list menu info.xls ,
(, ) .
list shortcut menus.xls , .

. <

789

menu maker.xls
, .
new menubar.xls Excel.
new shortcut menu.xls .
shortcut key.xls
.
toggle gridlines.xls .

24
\assistant\formletter.xls Office.
\comments\formletter.xls .
\function\myfunc.xls .
\htmlhelp\formletter.xls HTML Help ( ).
\other\myapp.xls
: Help, .
\textbox\formletter.xls TextBox, .
\userform1\formletter.xls Label, UserForm.
\userform2\formletter.xls
Label UserForm.
\userform3\formletter.xls ComboBox Label, UserForm.
\worksheet\formletter.xls .
24 .
.
.

25
loan amortization wizard.xla -,
. . .

26
multilingual wizard.xls ,
.

27
does file exist.xls .
.
does path exist.xls .
.

790

. <

export import.xls CSV,


CSV, .
export to HTML.xls HTML.
export to XML.xls XML.
filter text file.xls
(infile.txt), output.txt , .
import more than 256.xls
Sheet1. 256 , . longfile.txt,
600 .
list files1.xls , , . ,
.
list files2.xls , ,
. ,
. FileSearch.
longfile.txt , import more than
256.xls.
show drive info.xls , FileSystemObject .

28
add 100 buttons.xls , 100
CommanButton UserForm .
add button and code.xls CommandButton VBA.
add controls.xls UserForm .
add userform.xls
UserForm .

options form.xls UserForm


( OptionButton), , , .
replace module.xls . UserBook.xls.
show components.xls ,
VBA, .

29
csvclass.xls ,
CSV.
keyboard.xls , NumLock
CapsLock.

. <

791


A
ActiveX, 125; 380; 548
ADO, 42; 558
Analysis ToolPack, 61
API, 279
Apple II, 33
Application, 177

L
Label, 356
ListBox, 356; 384; 391
Lotus 1-2-3, 34; 89
LotusScript, 36

B
BASIC, 141
Boeing Calc, 35
Boolean, 305

M
Microsoft Query, 42
MsgBox, 207; 339; 420
MultiPage, 356; 406
MultiPlan, 38

Object Browser, 184


Office Web Components, 434
OLE, 548
OptionButton, 357

Cells, 180
CheckBox, 355
COM, 565
ComboBox, 356
CommandButton, 383
Comments, 173
CSV, 690
CubeCalc, 35

P
D

DAO, 42
DDE, 543
DDL, 326
Dialogs, 348

Q
QuattroPro, 37

E
Excel
Excel
Excel
Excel

PathExists, 311
PRN, 690
Project Explorer, 148
Public, 225

2.1, 39
4, 40
95, 40
3, 39

R
R1C1, 70
Range, 179
RangeNameExists, 311
RefEdit, 385; 447
Rem, 188

F
FileDialog, 347
FileExists, 310
FileNameOnly, 311
Frame, 356

GetOpenFilename, 342
GetSaveAsFilename, 345

H
HLP, 645
HTML, 94
HTML Help, 653; 654
HTML Help System, 645

TextBox, 357
Toolbox, 379
Twin, 35
TXT, 690

U
I

IDE, 701
InputBox, 288; 336; 337

S
ScrollBar, 357
SheetExists, 312
SpinButton, 357
SuperCalc, 34
SuperCalc 5, 35

UI Builder, 37

V
VBA, 42; 121; 142

VBE, 46
VGA, 137
VisiCalc, 33
VP Planner, 35

W
Windows API, 279; 326
Windows Help System, 645
Windows 3.0, 36
WordPerfect, 37
WorkbookIsOpen, 312
Workbooks, 209

X
XLA, 572
XLB, 589
XLM, 38; 48; 142
XLS, 572

, 69
, 69
, 69
, 43; 548

, 157
, 489
, 600
, 156
, 158
, 628
, 58

, 474
, 546
, 617
, 46

, 80
, 258
, 500
, 171; 235; 520
, 262

, 58
, 122; 566
, 563
-, 131
, 184; 534; 550
, 202
, 308

, 151; 189

, 52
, 289
Excel, 10; 122; 135; 583
, 543

, 136; 328
, 536
, 59
, 549
, 463
, 109
, 516
, 71
, 82

, 420
, 720
, 276
, 354
, 54
, 592

, 348
, 192
, 205

, 481
, 385
, 351
, 492
, 429

, 453
, 476
, 287
, 55
, 402
, 300
, 396

Office, 651
, 260
Windows API, 326
, 225
, 260
, 167
, 68

, 711
, 553
, 501

, 481
, 200
, 82; 680
, 688
, 475
, 157
, 57; 469
, 488
, 502
, 50; 335
, 429
, 565

793

, 48
, 284
, 295
, 200

, 203
, 543
, 610
, 713

, 416
, 149
, 619
, 277
, 568
, 623
, 392
, 370
, 592
, 618
, 355; 605; 709

, 58
, 573

, 545
, 243

, 365
, 303
, 634
, 705

, 689
, 331
, 244; 471
, 154; 161
, 297
, 600

Excel, 87
VBE, 146
Windows, 544
, 191
, 386
, 160

, 132
, 36
, 77

, 678
, 45; 168

, 607
, 570
, 618
, 154
, 362
, 478
, 389

794

, 478
, 617
, 724
, 76

, 691
, 729
, 71
, 165
, 409
, 662
, 60
, 34
, 96
, 675
, 141

, 686
, 362
Excel, 135
, 71
, 480
, 362
BASIC, 141
, 243

, 79
, 546
, 495
, 276
, 110
, 116
, 35

, 448
, 448
, 448

, 458
, 676
, 317
, 168; 572
AddIns, 576
CommandBars, 595; 618
Comments, 173
Dialogs, 348
References, 703
VBComponents, 703
VBProjects, 703
Workbooks, 209
, 378
, 154; 161
, 587; 616
, 51; 129; 165; 227; 363; 617
, 379
, 172; 188
, 646
, 517
, 109
, 198; 673
, 271


For Each-Next, 209
If-Then, 211
Select Case, 214
With-End With, 208
, 169
, 587; 617; 636
, 93
, 666
, 284
, 285
, 156
, 158

, 632
, 573
, 47
, 48
, 165
, 195
, 678

, 57
, 35
, 300
, 77; 202
, 415
, 659
, 54; 276
, 390
, 84
, 48; 126; 616
, 497

Excel GetSaveAsFilename, 345


GetOpenFilename, 342
InputBox, 337
SendKeys, 560
, 308
, 196

Comment, 173
FileSearch, 684
, 170
, 726
VBA, 304
, 203
, 136
, 676
, 719

, 35; 62; 93; 279; 563


, 115

, 224
, 363
, 255

, 42

, 126
, 128
, 567
, 358
VBE, 156
, 423
, 267
, 398
, 672
, 672

, 74; 195
, 225
, 260

, 706
, 135

, 122; 239
, 309
, 366; 370
, 235
, 122
, 361
, 45; 168
AddIn, 577
Application, 177
Comment, 172
FileDialog, 347
FileSearch, 684
FileSystemObject, 685
Range, 179
UserForm, 538
, 45; 142
IDE, 702
, 470
, 151
, 450
, 198
, 203
, 494
, 193
, 224
, 259

, 157
, 195
, 115
, 113
VBE, 147
, 572
Immediate, 235
Properties, 360
, 336
, 148; 150
, 67
GoTo, 211
, 73
, 201

795

, 690

, 165
, 277
, 568

, 171
Excel, 674
, 396
, 305
, 291
, 191; 193
, 296
, 292
, 580
, 616
VBA, 143
, 131

, 388
, 639
, 629
, 518

, 536
, 688
, 275
, 453
, 68

, 306
, 430
, 626
, 591
, 487
, 364
, 683
, 663
, 419

, 528
, 537
, 253; 455
, 459
, 473
, 130
, 200

Excel, 130
, 76

, 61
, 49; 93; 128; 147; 587
, 358
, 358
, 547

Excel, 103
, 165
, 227
, 327

796

, 235
, 398
, 591
Excel, 88
, 357
, 190
, 204
Public, 197
, 197

, 285
, 399

, 298
, 299
, 73
, 264
, 51; 159
, 239
, 444
, 497

Mac, 674
, 493
, 136
, 617
, 80
, 550

, 574
, 687
, 357

, 313
, 314
, 689
, 487
, 457
, 109

, 124; 353; 643


, 205
, 42; 256

, 504
, 48; 123
Office, 651
, 318
, 517
, 688
, 120
, 199
, 199
, 107
-, 114

, 366
, 458
, 262; 256
, 240
, 176

, 456

, 119
, 290

, 74
, 74
, 75
, 72
, 564
, 672

, 372; 530
, 289
, 531
, 312
, 369

, 417
VBA, 187
, 724
, 518
, 148
, 121
, 329
, 122
, 136
, 688
, 390

, 60
, 85
, 293
, 457
, 693
, 223
, 411; 494; 515
, 259

, 727
, 727
, 33
, 247; 308

, 46; 91
, 447
, 47
, 159
, 690
, 616

, 46
, 581
, 160
, 517
, 444
, 109
, 136; 328
, 549
, 469

, 570
, 593
, 134

, 103

, 618
, 97
, 472

, 639
, 592
, 619

, 479
, 61; 457

, 598
AddIn, 577
Application, 177
Comment, 173
FileSearch, 684
, 169
, 359; 606

Boolean, 305
Cells, 180
Comment, 174
Offset, 182
Range, 179
Style, 606
Tag, 377
, 655
, 548
, 196

, 632
, 304
, 48
, 548
, 102; 330; 665
, 580
, 602
, 591
, 73
, 323
, 366; 515
Activate, 523
BeforeClose, 525
BeforePrint, 525
BeforeRightClick, 532
BeforeSave, 524
Change, 527
Deactivate, 524
NewSheet, 523
OnKey, 541
OnTime, 539
Open, 522
SelectionChange, 531
SheetActivate, 523
, 628
, 491
, 375
, 533
, 726
, 375

797

AddIn, 580
Application, 533
Chart, 533
SpinButton, 374
UserForm, 372; 538
Workbook, 521
Worksheet, 527
, 62; 671
Windows Macintosh, 672

, 375
, 620

, 443
, 433
UserForm, 410
, 335
, 386
, 410
, 675
, 720
, 596
, 129
, 640
, 415
, 84
, 383
, 494
, 566
, 587; 591
, 124
, 555
, 460
, 461
, 255
, 381
, 240
, 247
, 308
, 444

VBA, 150
, 568
, 302
, 165
, 109
, 356

, 373
, 307
, 195
, 172; 643

VBA XLM, 142


, 238
, 126

, 69
, 68
, 583
, 597
, 378; 603
, 67

798

, 70
R1C1, 70
, 73
, 169
, 147
, 56

, 464
, 147; 587; 615; 616
, 464
, 410
, 199
, 199
, 60
., 121
, 661
, 217
, 80

, 544
, 647
, 357
, 445
, 90; 688
, 151

, 363
, 130
, 250
, 568
, 194

, 191
, 296
, 483
, 292
, 196

, 595
, 516
, 112
, 242

, 476
, 598
, 623
, 149
, 592
, 295
, 606
, 617

, 474
, 328
, 576
, 588
, 504
, 302
, 681

, 122

, 439; 569
, 630
, 443

, 87
, 92
, 92
, 42; 121

Lotus 1-2-3, 89
Quattro Pro, 90
, 56
, 694
, 355

, 438
R1C1, 70
, 91
, 672
, 610
, 55; 314
, 477

, 90
, 88
, 53; 67; 121
, 77
, 480
, 53
, 53; 151; 255
CreateObject, 551
FileExists, 310
FileNameOnly, 311
GetOption, 716
IIf, 214
InputBox, 288; 336
MsgBox, 207; 339
PathExists, 311
RangeNameExists, 311
SheetExists, 312
Shell, 544
Windows API, 279; 326
WorkbookIsOpen, 312
, 262
, 267
, 266
, 267
, 272
, 264
, 271

, 444
, 497

, 505
, 588

, 159
, 446
, 242
, 216
Do Until, 220
Do While, 219
For-Next, 217
, 478

, 55
, 331
, 689

, 381
, 159

, 728
, 149
, 691

CheckBox, 355
ComboBox, 356
CommandButton, 383
Frame, 356
Image, 356
Label, 356
ListBox, 356; 384; 391
MultiPage, 356; 406
OptionButton, 357
RefEdit, 385; 447
ScrollBar, 357
SpinButton, 357
TextBox, 357

, 125
VBA, 187
Excel, 381
MsgBox, 420

VBA, 677
, 672

799

VBA Excel 2003


..
..
..
.. ,
..


101509, . , . , . 43, . 1
. . 090230 23.06.99

25.02.2005. 70100/16.
Times.
. . . 64,5. .-. . 45,65
3000 .


,

197110, .-, ., 15