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

()

. . .

. .


Microsoft Visual
Basic for Applications

2013

__ ____________ 2013 .

___________________________________________________
___________________________________________________
004.65
32.973.26 - 018.2
89
.. Microsoft Visual Basic for
Applications: . .
, - . . . -, 2013. 35 .

Visual Basic for Application Microsoft Word, Excel
Access.

.
.
. 19. . 7. . 3 .

.. , 2013


1. VBA
Microsoft Office Word ............................................................................... 4
1 ................................... 12
2. VBA
Microsoft Office Excel ............................................................................. 13
2 ................................... 21
3. VBA
Microsoft Office Access ........................................................................... 23
3 ................................... 33
. ADO.Recordset .................. 34
.............................................................................................. 36

1.
VBA Microsoft Office Word
Microsoft Visual Basic for Applications (VBA) Microsoft Office
(Word, Excel, Access, PowerPoint, Outlook, FrontPage, InfoPath),
(Microsoft Visio Project, CorelDRAW, CorelWordPerfect Office 2000, AutoCAD). Office
Visual Studio Tools for Office (VSTO).
VBA VBScript [1].
, , :
1) VBA Microsoft Office
. ,
, !, @, &, $, #. .
2)
Dim <> [As <>]. . [1,
5.4].
3) ( ). ,
: Sub <_>,
Sub 1_Click().
VBA
( Word MSWORD.OLB). (Object Browser)
Microsoft Visual Basic, Word
Office ( View Object Browser).
Word ,
Windows-, , ,
,

.
, Excel,
Access.

Word
4

Excel,
, , VBA.
Word ,
Word ,
. , Word
( )
Word (Word 2010, 2013).
,
Office . , VBA.
:
1) , ,
, ,
: ;
2) (
), Ctrl+End;
3) Enter !;
4) 3;
5) , Shift+Home Delete;
6) !,
Shift+End Delete;
7)
, Visual Basic ;
8) Microsoft Visual Basic
Project
Progect(< >) Modules NewMacros
VBA, 1.1.

1.1 VBA
Microsoft Visual Basic
, , Word , .
1 (Sub 1() VBA, .
1.1) Selection , ( Application) . :
Application.Selection, ,
Word Application
.
1 :
Selection.EndKey Unit:=wdStory

Selection.TypeText Text:="!"

Selection.TypeParagraph

Selection.TypeText Text:="!"

Selection.HomeKey Unit:=wdLine, Extend:=wdExtend

Selection.Delete Unit:=wdCharacter, Count:=1

Selection.MoveUp Unit:=wdLine, Count:=1


Selection.EndKey Unit:=wdLine, Extend:=wdExtend

Selection.Delete Unit:=wdCharacter, Count:=1

, Word , 1
.
.
Visual Basic ( 1.2).

1.2 Microsoft Visual Basic


Debug ( 1.3)
:
Step Into ;
Step Over ;
Step Out
;
Run To Cursor ;
7

Add Watch
Watches.
Toggle Breakpoints
.

.
,
1 ,
Watches
(.
1.2).

, - 1.3
Debug VBA

.
. 1 : S Debug.Print ( Immediate).
.
Visual Basic Tools-Options
Auto Syntax Check, , .
,
Visual Basic
( 1.4).
Me ,
Me.TextBox1.Value , ThisDocument.TextBox1.Value.
,
Ctrl+.

1.4
( )
,
(. 1.5).

1.5 VBA
Word ActiveX, ( 1.6).

1.6 Word

:

11,1237

12,3456

= 23.4693

(
,
) Visual Basic, Private Sub TextBox1_Change(), ( Change ,
9

).
Calc1 Private Sub Calc1().
:
Private Sub TextBox1_Change()
' Change TextBox1
Calc1
End Sub
Private Sub TextBox2_Change()
' Change TextBox1
Calc1
End Sub
Private Sub Calc1()
If Me.TextBox1 = "" Or Me.TextBox2 = "" Then
Me.TextBox3 = ""
Exit Sub
End If
On Error Resume Next
Me.TextBox3 = CSng(Me.TextBox1) +
CSng(Me.TextBox2)
If Err <> 0 Then
MsgBox " , " & _
" Windows", _
vbCritical, " "
End If
End Sub

Properties Enabled
False, 1.7.

TextBox1 TextBox2 TextBox3 .
Calc1

(CSng(TextBox1)

CSng(TextBox1.Value)), . . TextBox3 = TextBox1 + TextBox2,



.
:
10

1.7

= 28
CommandButton1
:
Private Sub CommandButton1_Click()
TextBox5 = Tables.Count
End Sub

Word, Y = F(X) X, X. X.
, ,
[1, . 5.4.2.1].

11

1
1) Word,
, VBA VBS.
. 3
. Microsoft Visual Basic For
Applications, .
2) Word ( ActiveX) :

Change _, , . Locked =
True, .

12

2.
VBA Microsoft Office Excel
Excel.Application,
, Word.Application, 2.1.

2.1 Excel.Application

13

Application :
Cells ,
Range (
Range ),
Columns ,
Rows ,
Sheets , , Sheet
(, );
Worksheets , ,
Worksheet
,
Selection (, , (Chart), , .

Microsoft Visual Basic Excel (


, Excel
*.xlsm)
Application.
.
, Microsoft Word, VBA Excel ,
, , , .
, , ,
A2 Range("A2").Select . . , ,
(, Range
, Select , Selection , Font , Size
, Sheet , Cell , Characters , Active , Formula , Center , Border , Edge
, Alignment ) , . Excel, , .
[1] , Y = F(X), Word VBA-.
14


1. :
Sub 1()

1 A1
A1:A10

ActiveCell.FormulaR1C1 = "1"

Range("A1:A10").Select
Selection.DataSeries Rowcol:=xlColumns, _
Type:=xlLinear,Date:=xlDay, Step:=1, Trend:=False


End Sub

Range ( ActiveSheet)
Cells(_, _). Offset , . . <>.Offset(_, _), Range.
1 , :
Sub 1()
ActiveCell.Formula = "1"
adr1 = ActiveCell.Address
adr2 = ActiveCell.Offset(9, 0).Address

9
Range(adr1, adr2).Select
Selection.DataSeries Rowcol:=xlColumns, Type:=xlLinear, _
Date:=xlDay, Step:=1, Trend:=False
End Sub

Excel
. ,
,
VBA.
:

x
y

X Y .
, Y
Z ( 2.2).
15

2.2
0 - , ,
2.3.

2.3

X.
.
, Z
X Y,
X Y, . Change, B3
SelectionChange. 2.4 .

16

B3;
B3
2.4
:
Private Sub Worksheet_Change(ByVal Target As Range)

' Target
Application.EnableEvents = False

' ,
'. .
Adr = Target.Address
'
If (Adr = "$A$3" Or Adr = "$B$3") Then

' A3 B3
If [A3].Value < 0 Or [B3].Value = 0 And _
Range(ADR).Interior.Color <> RGB(250, 200, 250)

' A3 < 0 B3 = 0 ADR


[C3].ClearContents
' C3
Range(ADR).ClearContents
' ADR
Range(ADR).Interior.Color = RGB(250, 200, 250)

' ADR,

MsgBox ADR & " - !", _
vbExclamation, ""
Else
If IsEmpty(Range("c3").Value) Then
Range("C3").Formula = "=SQRT($A$3)/$B$3"
Range(ADR).Interior.Pattern = xlNone
End If

17

' ADR

End If
End If
Application.EnableEvents = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If IsEmpty([A3].Value) Then [A3].Select

' A3,
If IsEmpty([B3].Value) Then [B3].Select

' B3,
End Sub

.
Excel.
2.5.
()
()

2.5
()
()

VBA X
2.6. ,
Xmin Xmax ,
Y = X/Xmax.

18

2.6
Change,
, :
Private Sub Worksheet_Change(ByVal Target As Range)
Adr = Target.Address
If Adr = "$A$4" Or Adr = "$B$4" Or Adr = "$C$4" Then
ActiveSheet.Unprotect
Call
Call
[A4].Select
ActiveSheet.Protect DrawingObjects:=True, _
Contents:=True
End If
End Sub
'------- General ----Sub ()
n = [C4] '
adr2 = "A6:A" & (5 + n)
' , =C4
Randomize
Range("A6:A105").ClearContents '
Range("A6:A105").NumberFormat = "0.0000" '

19

For I = 1 To n '
Adr = "A" & I + 5
Range(Adr).Value = [B4] - ([B4] - [A4]) * Rnd
Next
xmin = [A6]
xmax = [A6]
For I = 1 To n '
Adr = "A" & I + 5
xt = Range(Adr).Value
If xt < xmin Then xmin = xt
If xt > xmax Then xmax = xt
Next
[D4] = xmin
[E4] = xmax
For I = 1 To n ' Y
Adr1 = "A" & I + 5
Adr2 = "B" & I + 5
Range(Adr2).Value = (Range(Adr1).Value) / xmax
Next
End Sub
Sub ()
ActiveSheet.Unprotect
If ActiveSheet.Shapes.Count > 0 Then
'
ActiveSheet.ChartObjects("Grafik").Activate
ActiveChart.Parent.Delete
End If
Rng = "A6:A" & (5 + [C4]) '
ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
ActiveChart.SetSourceData Source:=Range(Rng)
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = " "
ActiveChart.Parent.Name = "Grafik"
ActiveChart.Axes(xlValue).Select
Selection.TickLabels.NumberFormat = "0"
ActiveSheet.Shapes("Grafik").Left = 120
ActiveSheet.Shapes("Grafik").Top = 80
ActiveSheet.Shapes("Grafik").Width = 300
ActiveChart.Axes(xlValue).HasTitle = True
ActiveChart.Axes(xlValue, xlPrimary). _
AxisTitle.Text = "Y"
ActiveChart.SetElement _

20

(msoElementPrimaryValueAxisTitleHorizontal)
ActiveChart.Axes(xlCategory).HasTitle = True
ActiveChart.Axes(xlCategory, xlPrimary). _
AxisTitle.Text = "X"
ActiveChart.Legend.Select
Selection.Delete
End Sub

,
Basic .

2
1) Excel .
, A1 1,11;
B1 2,22; C1
=A1*B1. .
A1:C1 .
Microsoft Visual Basic For Applications,
Excel. .
2) ( VBA-)
( , ):

1

a
2b

y ab

b
5a

y lg( a) 2 b

2a 3
y
lg( 2b 3)

lg( 10 b)
a
a3
y
a b
21


a >= 0,
b <> 0
a + b >= 0;
a <> 5
a > 0, b >= 2
a >= 1,5;
b > 1,5
a <> 0,
b < 10
a <> b

2a b
b lg( a)

a>1
b<>0
a < 1; b > 0

y (1 a) / b

1
14 b
2a

a>0
b < 14

10

2 a
y
2b

a >= 0
b <> 2

3) n ( 2.6)
VBA
( , ):
1

1)

yi xi xi x j

2)

yi xi xi
i 1

i 1

j n

3)

yi

xi
n

4)

xi

zi

( n i ) xi

yi

i 1

yi

5)

xi

yi

xmax xmin

6)

i 1

7)

yi xi xi /i

8)

i 1

9)

x xi / n

xmax , xmin -

xi
x

yi

xi
n

xi

i 1
n 1

yi axi bxi c
2

10)

22

xi
i 1 xi 1

yi xi

3.
VBA Microsoft Office Access
Microsoft Office Access.Application. Access, ,
,
, .
Access () ( ) Microsoft Access Object Library.
, Access ADO (Microsoft ActiveX Data Objects)
DAO (Microsoft Data Access Objects),
. ADO , DAO, , .
,
Recordset ( ) (cursor ),
.
Recordset (. 3.1
ADO).
3.1 Recordset ADO

Dynamic cursor

Keyset cursor


, ,
, .
<Recordset>.Update .
,
, ,
.

23

3.1

Static cursor

Forward-only cursor


,
, . , ,
, ,
.
, .

Recordset. , . ,
Recordset.

Recordset ADO, DAO , , ADO. Recordset .


Access ADO DAO [1] .

Access.
Windows-.
1.

-4 ( 30.10.97 71), 3.1.
3 : , (
) .
( 3.1) ( 3.3)
( 3.2).
, . . .
( 3.2) (
3.3).

24

3.1 -4
3.2

25

127
127
15
25
25
25
25

.


,
( )

3.2


.
. - .

= 2.
3.3

, , ,


-
-

127

25
25
127

.
25
15

26


( )

3.4

127

3.2

3.3
27

3.3
, , , VBA:
Option Compare Database
Sub ()
Me.______ = _
Me._ * Me.___
snds = Me.____
otv = MsgBox(" 18%?", _
vbYesNo, " :")
If otv = 6 Then '
Me.____ = _
Me.______ * 0.18
End If
Me._____ = _
Me.______ +
Me.____
NN = Me.[ ]
Me.Refresh '
Dim rs As New ADODB.Recordset
' SQL-:
sq = "SELECT DISTINCTROW [ ].[ ], " + _
"Sum([ ].[ , ]) " + _
"AS sbn, Sum([ ].[ , ]) " + _
"AS sn, Sum([ ].[ ]) " + _
"AS ssn, Sum([ ].[ ]) " + _
"AS sk FROM [ ] INNER JOIN [ ] "
+_
"ON [ ].[ ] = [ ].[ ] "
+_
"GROUP BY [ ].[ ], " + _
"[ ].[ ] " + _
"HAVING ((([ ].[ ])= " & NN & "))"
rs.Open sq, CurrentProject.Connection, adOpenDynamic, _
adLockOptimistic
'
'
Me.Parent._ = rs!sk
Me.Parent.___ = rs!sbn
Me.Parent.__ = rs!sn
Me.Parent.___ = rs!ssn
Me.Refresh

28

End Sub
Private Sub __AfterUpdate()
If Me.___ > 0 Then
Call
'
Me._.SetFocus
End If
End Sub

Private Sub _______AfterUpdate()


all
End Sub
Private Sub _____AfterUpdate()
If IsNull(Me.____) Then _
Me.____ = 0
Call
End Sub
Private Sub ____AfterUpdate()
If Me._ > 0 Then
Call
Me.___.SetFocus
End If
End Sub

Me.
, 3.4 (
.Value,
, ).

3.4 VBA

29

SQL-
Access.
AfterUpdate ( ) [ ], [
, ], [ , ] [, ].
3.5.

3.5

. Access
Excel, , XML-,
Word. *.doc *.docx . , Word
2 ( 3.5).
3.5 d:\asg\ .docx


115
2.03.2013

256000
506000
114520 2.0-6.0
12,596 2.0-4.0


1
-
3
3
2
2

30

-

1
1.5
50
100

3500
4800
300
200

, (Click)
, .
:
Private Sub _Click()
'On Error Resume Next '
Dim rs1 As New ADODB.Recordset ' Recorgset
Dim rs2 As New ADODB.Recordset
SQL1 = "SELECT [ ].* FROM [ ]"
SQL2 = "SELECT [ ].* FROM [ ]"

' SQL- Recordset


rs1.Open SQL1, CurrentProject.Connection, _
adOpenDynamic, adLockOptimistic
rs2.Open SQL2, CurrentProject.Connection, _
adOpenDynamic, adLockOptimistic

'
'
Set objWord = CreateObject("Word.Application")

' Word.Application
'objWord.Visible = True '
Set objDoc = _
objWord.Documents.Open("d:\asg\ .docx ")

' objWord
N_ord = objDoc.Tables(1).Cell(2, 1).Range.Calculate
Data_ord = objDoc.Tables(1).Cell(2, 2)
Data_ord = CDate(Left(Data_ord, Len(Data_ord) - 2))
Str_podrazd = objDoc.Tables(1).Cell(2, 3).Range.Calculate
With rs1
.AddNew
'
.Fields(" ") = N_ord
.Fields(" ") = Data_ord
.Fields(" ") = Str_podrazd
.Update
'
If Err.Number <> 0 Then '
otv = MsgBox(" " _
& N_ord & ". ?", _
vbYesNo + vbExclamation, " !")
If otv = 7 Then '
rs1.Close
rs2.Close
objDoc.Close
objWord.Quit

31

Exit Sub

'

End If
End If
End With
n = objDoc.Tables(2).Rows.Count '

' 2 Word
no_dat = "" ' .Update
yes_dat = "" ' .Update
For i = 2 To n
s = objDoc.Tables(2).Rows(i)

' i- 1
fld = Split(s, Chr(13) + Chr(7))

' i- fld
With rs2 ' rs
' ,
.AddNew '
.Fields(" ") = N_ord
.Fields(", , , ") = fld(0)
.Fields(" - ") = fld(1)
.Fields(" ") = Eval(fld(2))
.Fields(", ") = Eval(fld(3))

'
If Err.Number <> 0 Then '

.Update

no_dat = no_dat & fld(0) & vbLf


Else
yes_dat = yes_dat & fld(0) & vbLf
End If
End With
Next
rs.Close
objDoc.Close
objWord.Quit
MsgBox " . 2 Word " & n & " " & vbLf & _
" " & N_ord & vbLf & _
" [ ] :" & vbLf & _
yes_dat & _
" - ::" _
& vbLf & no_dat, , " "
rs1.Close
rs2.Close
objDoc.Close
objWord.Quit

32

Me.Requery
Me.Recordset.MoveLast
End Sub


MsgBox (. 3.6).

3.6.


Access

Word

3

.

33

.
ADO.Recordset
/

AbsolutePage
AbsolutePosition
ActiveCommand
ActiveConnection
BOF, EOF
Bookmark
CacheSize
CursorLocation
CursorType
DataMember
DataSource
EditMode
Fields (Collection)
Filter
Index
LockType
MarshalOptions
MaxRecords
PageCount
PageSize

(Collection)
RecordCount
Sort
Source
State
Status
StayInSync


,
Recordset
Command, Recordset
, Connection , Recordset,
BOF , -
Recordset.
EOF , -
,
Recordset Recordset
, Bookmark
Recordset,


, Recordset
, , DataSource
, , Recordset

Recordset
Recordset.
, Recordset

,
,
Recordset
Recordset
Recordset.

Recordset

Recordset
Recordset
: , ; , ,

, Recordset,
,

34

AddNew
Cancel
CancelBatch
CancelUpdate
Clone
Close
CompareBookmarks
Delete
Find
GetRows
GetString
Move
MoveFirst, MoveLast, MoveNext,
and MovePrevious
NextRecordset
Open
Requery
Resync
Save
Seek
Supports
Update
UpdateBatch


Recordset.


Recordset Record Update
Recordset,



(CompareEnum)

Recordset
Recordset
Recordset
Recordset
Recordset
, ,
Recordset
Recordset

Recordset ,

Recordset,

Recordset , Stream
Recordset, , ,
Recordset
, Recordset
,
Recordset, Record

(events)

EndOfRecordset
FetchComplete
FetchProgress
WillChangeField and
FieldChangeComplete


, Recordset
, Recordset

, ,

WillChangeField , c Recordset. FieldChangeComplete ,

35

WillChangeRecord and
RecordChangeComplete

WillChangeRecord
Recordset. RecordChangeComplete
WillChangeRecordset , Recordset. RecordsetChangeComplete
, Recordset

WillChangeRecordset and
RecordsetChangeComplete
WillMove , WillMove and
Recordset. MoveComplete MoveComplete
WillMove and
MoveComplete

Recordset
WillMove , Recordset. MoveComplete Recordset

1) . . : ,
. . . -, 2010. 470 .
2) . . Microsoft Visual Basic
Scripting Edition: .. .
: , 2009. 82 .
3) , . Excel 2010:
VBA.: . . . : .. , 2012. 944 .

36

Оценить