You are on page 1of 64

Sch Lp trnh Excel bng VBA

MC LC1 1. Ghi v thc hin macro ..................................................................................... 4 1.1. Ghi macro trong trng hp s dng tham chiu a ch tuyt i ........ 5 1.2. Chy macro khi s dng bng iu khin macro (Macro dialog box) ...... 6 1.3. Ghi macro trong trng hp s dng tham chiu a ch tng i ...... 7 1.4. Dng phm tt thc hin mt macro (shortcut key) .............................. 8 2. Cch thc hin mt macro n gin ................................................................. 8 2.1. Thc hin macro t mt i tng ho trong worksheet...................... 9 2.2. Chy macro t nt lnh trn thanh cng c ............................................. 10 2.3. Chy macro t lnh trong menu ca Excel .............................................. 12 2.4. Thay i la chn trong macro ................................................................ 15 3. Sa macro ........................................................................................................ 15 3.1. Dng form chung (General form) ............................................................ 15 3.2. To ra nhng thay i .............................................................................. 17 4. Ng php VB (Visual Basic Grammar) .......................................................... 17 4.1. Cc i tng (Objects) ........................................................................... 17 4.2. Cc phng thc (Methods)..................................................................... 19 4.3. Cc thuc tnh (Properties)....................................................................... 20 4.4. Cc bin (Variables) ................................................................................. 20 4.4.1. Kiu d liu trong VBA ..................................................................... 21 4.4.2. Khai bo kiu d liu ........................................................................ 22 4.5. S dng mng (Array).............................................................................. 24 4.5.1. Mng c chiu di c nh ................................................................ 24 4.6. S dng With - End With ......................................................................... 26 5. S dng gip Help ..................................................................................... 26 5.1. Ti thi im ang vit code .................................................................... 27 5.2. S dng hp thoi gip vi ch c th........................................... 27 5.3. Trnh duyt i tng............................................................................... 28 5.4. Cc file v d ............................................................................................ 32 6. Mt s chc nng iu khin trong VBA ....................................................... 33
1

Daipv78@gmail.com

Sch Lp trnh Excel bng VBA

6.1. S dng Options ....................................................................................... 34 6.2. S dng VBAProject ................................................................................ 35 6.3. S dng chc nng Security..................................................................... 38 7. Vit macro ....................................................................................................... 40 7.1. Vit macro ................................................................................................ 40 7.2. Sa cha li .............................................................................................. 42 8. Tham chiu n v vng .............................................................................. 44 8.1. Tham chiu kiu A1 ................................................................................. 44 8.2. S ch mc (Index numbers) .................................................................... 45 8.3. S hng v s ct (Rows and Columns) .................................................. 45 8.4. t tn cho vng (Named ranges) ............................................................ 46 8.4.1. Tn c to ra ngoi macro............................................................ 46 8.4.2. Tn c to ra trong macro ............................................................ 47 8.5. Nhiu vng (Multiple ranges) .................................................................. 47 8.6. Offset cells................................................................................................ 47 8.7. Kiu tham chiu R1C1 ............................................................................. 49 9. Cu trc iu khin ......................................................................................... 50 9.1. Cu lnh IF ............................................................................................... 50 9.2. S dng Select Case ................................................................................. 52 9.3. Xy dng cc iu kin ............................................................................ 53 9.3.1. S dng And ...................................................................................... 53 9.3.2. S dng Or ........................................................................................ 54 9.3.3. S dng nhiu And v Or .................................................................. 54 10. Hp thoi trong VBA .................................................................................... 55 10.1. Hp thng bo (Message box) ............................................................... 55 10.1.1. Cc loi thng ip trong buttons................................................... 55 10.1.2. M t thng s cc nt .................................................................... 56 10.1.3. Cc biu tng thng ip .............................................................. 56 10.1.4. Xy dng tham s cho MsgBox ....................................................... 56 10.2. Phng thc InputBox (Inputbox Method) ........................................... 57 11. Hnh ng lp (Loop) ................................................................................... 59 11.1. Do ... Loop.............................................................................................. 59 2

Sch Lp trnh Excel bng VBA

11.2. Do While ... Loop ................................................................................... 60 11.3. Do ... Loop While ................................................................................... 60 11.4. Do Until ... Loop .................................................................................... 61 11.5. For ... Next.............................................................................................. 61 11.6. For Each ... Next..................................................................................... 62 11.7. Lnh thot (Exit) .................................................................................... 63 11.8. Vng lp lng ......................................................................................... 63

Sch Lp trnh Excel bng VBA

1. Ghi v thc hin macro Macro l g? Macro l tp hp mt s cc dng lnh. Bn s dng chc nng Macro Recorder l mt tng hay tng bc thc hin cc cng vic, nht l lc u tm hiu v macro. Excel h tr ghi li (recorder) cc cng vic bn thc hin v ch khng ghi li khi bn dng ghi. V d, mt (cell) c chn (selected) hin ti s khng c ghi cho n khi bn thc hin cng vic trong . Ngoi ra, Excel cng khng ghi li cc cng vic khi ang s dng bng iu khin (dialog box) cho n khi bn n nt OK trn bng iu khin .

Hnh 1: Thc hin ghi macro

Hnh 2: Ca s Record Macro

Trong sut thi gian ghi, macro c lu li vi tn xc nh trong module, module c to ra trong qu trnh ghi v l mt phn ca Workbook. Marco c ghi li c th c lu trong This Workbook (Workbook hin hnh), New Workbook (Workbook mi) hoc trong Personal Macro Workbook (nhng macro s hu ring). Nhng lnh (code) c lu trong Personal.xls, nhng macro s hu ring u s dng c khi bn m Excel ra. Cc macro trong cc Workbook khc nhau c th s dng bt c lc no khi cc Workbook ang m (k c s dng chng t Workbook khc). 4

Sch Lp trnh Excel bng VBA

iu kin c th tin hnh ghi macro: 1. Bng tnh Excel hin hnh (Activate Excel). 2. S dng Workbook mi. 1.1. Ghi macro trong trng hp s dng tham chiu a ch tuyt i Bn hy ghi li macro trnh by tn bn v a ch nh sau:
1. Trong Tools/Macro, chn Record New Macro (hnh 1). 2.Trong Macro name: g Address_abs t tn macro (hnh 2).

c im l k t u tin l ca tn macro phi l ch. Cn cc k t khc c th l ch, s hoc k t gch di (k t _). Cc k t c bit nh khong trng (Space), @, %, $, #, &, ... khng c chp nhn, bn c th dng k t _ tch tn trong macro.

Hnh 3: Qu trnh ghi

Sch Lp trnh Excel bng VBA

3. Chuyn sang Shortcut key: trng (s thc hin sau). 4. Trong Store macro in: mc nh l This Workbook. 5. Trong Description: bn g ni dung sau Enter address starting in cell B3 6. Bm OK. 7. Thanh Stop Recording s xut hin. Bn c th di chuyn n n v tr khc nu thy cn thit. 8. Trong thanh Stop Recording, n vo nt Relative Reference cho m i (khng tc dng- hnh 3). 9. Trong Sheet1, bm vo B3 v g tn bn. di g tn lp, tip theo l tn trng. 10. Cho ton b cc ch m v nghing. 11. Bm vo B6. 12. Trong Stop Recording, bm vo nt Stop Recording.

Nh vy, macro c tn Address_abs c ghi li. Nhng m bn s dng trong qu trnh ghi c th hin di dng a ch tuyt i. V vy, nhng trong Worksheet s thc hin khi bn cho chy macro, tn, lp v tn trng s c to ra ng v tr trong Worksheet. Ghi ch: Bn c th la chn tham chiu tng i trong sut qu trnh ghi macro. Vn ny s c cp mc 1.3. 1.2. Chy macro khi s dng bng iu khin macro (Macro dialog box) Bn cho chy macro trn t Sheet2 nh sau:
1. Chn sang Sheet2 v bm vo no ngoi B3. 2. Trong menu Tools/Macro, chn Macros (hnh 1). 3. Bm vo macro c tn Address_abs trong danh sch macro (hnh 4). 4. Bm vo nt Run.

Sau bn s thy ni dung Sheet2 ging nh Sheet1.

Sch Lp trnh Excel bng VBA

Hnh 4: Chy macro Sheet2 Ghi ch: Nu bn mun hu qu trnh chy macro trc khi kt thc, n vo nt Esc. 1.3. Ghi macro trong trng hp s dng tham chiu a ch tng i Macro Address_abs s dng a ch tuyt i. Tip theo bn s to mt macro cng ging nh trn. Macro trc chn cc (select cells) c quan h vi v tr ca hot ng (active) trong qu trnh chy, macro s ghi li quan h tham chiu tng i.
1. Chn Sheet1. 2. Bm vo B11. 3. Trong menu Tools/Macro, chn Record New Macros (hnh 1). 4. Trong Macro name: g Address_Ref t tn macro (hnh 2). 5. Trong Shortcut key: G ch A, nh vy phm tt s l Ctrl+Shift+A (Nu phm tt b trng vi phm c sn th Excel t ng b sung thm phm Shift nh trng hp ny). 6. Trong Store macro in: mc nh l This Workbook. 7. Trong Description: bn g ni dung sau

Enter address starting in activate cell position


8. Bm OK.

Sch Lp trnh Excel bng VBA

9. Thanh Stop Recording s xut hin. Bn c th di chuyn n n v tr khc nu thy cn thit. 10. Trong thanh Stop Recording, n vo nt Relative Reference cho m i (khng tc dng).

Microsoft Excel s tip tc ghi macro vi quan h tng i cho n khi no thot khi Microsoft Excel hoc bn n li vo nt Relative Reference.
11. G tn bn, lp, tn trng v a ch trong cc B11, B12, B13 v B14. Ni dung th hin nh sau: Nguyen Van Hung Lop DCCT-DKT K48 Truong DH Mo Dia chat xa Dong Ngac, Tu Liem, Ha Noi 12. Cho ton b cc ch m. 13. Bm vo B15. 14. Trong Stop Recording, bm vo nt Stop Recording.

Ghi ch: Nu bn mun macro chn c bit, u tin chn u (active cell), sau chn c quan h vi u, bn c th la chn hn hp a ch tuyt i v tng i trong qu trnh ghi macro. s dng tham chiu tng i trong sut qu trnh ghi macro, nt Relative Reference lun sng (c tc dng). s dng tham chiu tuyt i trong sut qu trnh ghi macro, nt Relative Reference lun ti (khng tc dng). 1.4. Dng phm tt thc hin mt macro (shortcut key) Macro Address_Ref c th thc hin nh m t trong mc 2.2. Lc trc phm tt c n nh thc hin cng vic , hy s dng phng php thay th ny:
1. Ti Sheet2 bn chn vo 1 (v d H14). 2. n t hp phm Ctrl+Shift+A. Khi tn v a ch s xut hin di . 3. Bn hy th thc hin li macro ti cc v tr khc trong Sheet2.

2. Cch thc hin mt macro n gin Di y l cc phng thc thc hin macro, bn c th cho thc hin macro t cc i tng sau:
i tng ho trong worksheet hoc biu Nt (button) trong thanh cng c (Toolbar) Dng lnh (command) trong menu ca Excel

Sch Lp trnh Excel bng VBA

2.1. Thc hin macro t mt i tng ho trong worksheet Bn c th dng i tng ho trong worksheet thc hin mt macro.
1. Chn Sheet3, ni m cn trng. 2. Vo menu View/Toolbars v bn chn Drawing (tr trng hp thanh cng c Toolbar c trn mn hnh). 3. Chn i tng ho nh hnh Oval v v hnh oval . 4. G ch vo hnh oval bng cch n phi chut vo ri chn Add Text t thc n tt (hnh 5). 5. G ni dung Address ri bm ra ngoi thot. 6. Bn c th thay i kch thc hnh oval cho ph hp th hin ni dung ch trong v tnh m thut. 7. n phi chut vo hnh oval , chn Assign Macro. 8. Trong bng Assign Macro, chn macro c tn Address_Ref. 9. Sau n OK.

Sau , bn cho thc hin th macro:


1. Chn 1 no (v d nh J13). 2. Bm vo hnh oval trn, macro s thc hin.

Ghi ch: Nu bn mun di chuyn i tng ho (c macro) ra khi ch khc trong worksheet, s dng phi chut di chuyn (v bm tri chut th macro s chy). Cn nu bn mun thay i macro khc th bn bm phi chut trn i tng, chn Assign Macro v la chn macro no bn mun.

Hnh 5: Gn macro vo hnh oval

Sch Lp trnh Excel bng VBA

2.2. Chy macro t nt lnh trn thanh cng c Ngoi ra, c th chy macro t nt lnh (button) trong cc cc thanh cng c t to (custom toolbar). V d nh c th n nh macro Address_abs trong nt hnh mt ci (Smiley Face) nh sau:
1. Di chuyn chut n mt im no trong cc thanh toolbar. 2. n phi chut, trong thc n tt chn Customize. 3. Trong bng Customize, chn tab Toolbars (hnh 6). 4. Chn nt New. 5. Sau bng New Toolbar xut hin v bn g tn vo (Macro1) ri OK. 6. Trong bng Customize, chn tab Commands (hnh 7). 7. Trong hp Categories, chn AutoShapes. 8. Trong Commands, cun xung cho n khi bn chn c hnh ng (Smiley Face). 9. Ti hnh Smiley Face, gi tri v ko chut vo trong thanh cng c Macro1 (hnh 8). Bn c th chn thm cc biu tng khc nu cn. 10. Bm phi chut vo nt Smiley Face, thc n tt s hin ra. Bn c th sa hay xo hnh v thay bng cc hnh khc. 11. Chn Assign Macro trong thc n tt, chn macro Address_abs v n OK. 12. ng bng Customize vo.

Hnh 6: To thanh cng c mi

10

Sch Lp trnh Excel bng VBA

Hnh 7: Gn hnh vo nt lnh mi

Hnh 8: To cc nt lnh trong thanh Macro1 v gn Assign Macro vo. Ghi ch: Thanh cng c t to thuc s hu ca workbook m n c to ra. Bn hy th s dng nt lnh va to ra thc hin cng vic nh sau: 11

Sch Lp trnh Excel bng VBA

Code:
1. Xo sch ni dung ca Sheet2. 2. Bm chut vo nt Smiley Face trong thanh cng c Macro1.

Kt qu s th hin trn Sheet2. 2.3. Chy macro t lnh trong menu ca Excel T menu ca Excel bn c th thm cc menu mi m khi la chn chng th macro s chy. V d: To menu mi c tn l Work Address c th cha menu con Macro2 trn thanh tiu chun nh sau:
1. Phi m bo rng workbook ang cha macro ca bn ang hot ng. 2. Thm mt worksheet mi bng cch vo menu Insert/Worksheet (t l Sheet4) 3. Trong menu Tools/Customize, chn tab Commands trong bng Customize. 4. Cun xung dng cui cng v chn New Menu trong Categories (hnh 9). 5. Gi tri chut New Menu trong Commands v ko vo dng menu cnh Help. 6. n phi chut vo New Menu trong menu ca Excel, thc n tt hin ra. 7. Thay tn mi trong Name l &Macro2. Nu ch cn 1 menu ny th bm vo Assign Macro chn (hnh 10). Cn nu cn thm cc menu con (menu item) th khng cn.

12

Sch Lp trnh Excel bng VBA

Hnh 9: To New Menu trong menu ca Excel

13

Sch Lp trnh Excel bng VBA

Hnh 10: To menu Maro2 trong menu ca Excel K t v (&) trc M s gch chn ch M trong menu Macro2 (tr thnh Macro2), chnh l phm tt chy macro Macro2 (ch cn n Alt+M). Tip theo ta tin hnh to menu con trong Macro2:
1. Trong Categories (trong trng hp bng Customize vn ang m), chn Macros. 2. Ti Commands, chn Custom Menu Item (hnh 11), gi tri v ko chut n phn trng di Macro2 (vng c khoanh ). 3. Bm phi chut vo Custom Menu Item trong menu m Macro2. 4. Ti thc n tt, i tn trong Name thnh &Work Address (hnh 12). 5. Sau vo Assign Macro chn macro chy. 6. Cui cng l ng bng Customize.

Hnh 11: To cc menu con

14

Sch Lp trnh Excel bng VBA

Hnh 12: i tn menu con v gn Assign Macro cho n. Menu mi to c lu gi trong workbook . K c bn ng workbook nhng khi bn bm vo menu th workbook cha menu t ng m ra v thc hin lnh lun. 2.4. Thay i la chn trong macro Nu bn mun thay i cc lc chn chi tit trong macro, bc u tin bn vo menu Tools/Macro v chn Macros. Sau chn tn macro m bn mun thay i v bm vo nt Option. Bn c th thay i phm tt v m t li cng vic macro trong Description. 3. Sa macro Khi bn ghi macro u tin, Excel to ra molule trong workbook . Module cha cc lnh (code) c vit trong VBA. Cc bc thc hin nhn thy module:
[code/1. T menu Tools/Macro chn Macros. 2. Chn macro Address_abs v bm vo nt Edit.[/code]

Ca s Microsoft Visual Basic hin ra nh hnh 13. Bn c th thy r c cc dng code tng macro khi cun xung. 3.1. Dng form chung (General form) T kho (keywords) l s hng c bit trong VB, c th hin bng mu xanh l cy. Tt c cc macro u bt u vi Sub v kt thc bi End Sub (cn gi l th tc). 15

Sch Lp trnh Excel bng VBA

Dng mu xanh vi du u dng c gi l ch thch (comments). Li ch thch khng anh hng n macro v bn c th thay i ni dung ca n. Tn ca macro v li m t s dng (description) trong qu trnh ghi macro xut hin di dng ch thch. Bn c th dng comments ch thch trong qu trnh xy dng macro. Khi bn s d dng hiu c cc bc cng nh ni dung thc hin macro. ng en lin c ngha phn chia cc macro, function (hm) trong module. ng gch di (_) thnh thong gp cui dng code. Khi code qu di th dng (_) xung dng, nhng c hiu l code vn lin tc. Khi bn ghi macro phc tp hn, bn c th gp mt s code khng phi l bn cht ca n (essential). Excel ghi li tt c nhng g bn thc hin mt cch c th nht, k c nhng i s (arguments) ci t mc nh trong Excel s dng. Khi bn di chuyn chut n macro no th tn ca macro hin phn khoanh nh hnh 13 (Addres_Ref).

Hnh 13: Ca s Microsoft Visual Basic.

16

Sch Lp trnh Excel bng VBA

3.2. To ra nhng thay i Trong ca s Visual Basic Editor(VBE) (hnh 13) c cc module. C th coi module l ni lu tr cc th tc (sub) v hm (function). y cng l ni khai bo cc hng s, bin s, kiu d liu ngi dng. Mi module c th cha mt hay nhiu Sub hoc Function. Phn ca s chnh hin ni dung code trng gn ging nh Word, bn c th d dng to nhng thay i trong , nh b sung hay bt i ni dung nu thy cn thit. V d, bn c th thay i tn macro Address_abs thnh Dia_chi chng hn, ch cn g ni dung Dia_chi thay th Address_abs trong Sub Address_abs(). Khi con chut nm trong macro Dia_chi, bn vo Run v chn Run Sub/UserForm (phm tt F5). xem kt qu nh th no th bn vo View/Microsoft Excel (phm tt Alt+F11). Lc ca s VBE vn hin hu trong Task bar. ng ca s VBE v tr v Excel, bn vo menu File, sau chn Close and Return to Microsoft Excel (phm tt Alt + Q). Ghi macro v xem li nhng g n thc hin l cch hc rt hay, gip cc bn c th hc hi thm nhiu lnh, nhiu i tng v cc thuc tnh ca n, hiu r trnh t cc bc thc hin. Nhng n mt lc no , bn mun vit mt macro cho ring mnh hoc b sung thm mt vi code trong macro hin ti thc hin cc bi ton phc tp hn. Khi vic s dng ghi macro tr nn khng hu dng na. Macro khng th thc hin c cc tc v sau: _Cc kiu vng lp. _Cc kiu hnh ng theo iu kin (s dng If-Then) _Gn gi tr cho bin. _Cc kiu d liu c bit. _Hin cc thng bo (pop-up messages) _Hin cc hp thoi (dialog boxes) Trong chng di y, bn c th tm c nhiu thng tin v VBA. thay i ni dung bi: PhanTuHuong, 14-04-07 lc 10:12 PM 4. Ng php VB (Visual Basic Grammar) 4.1. Cc i tng (Objects) Visual Basic l ngn ng lp trnh hng i tng (object-oriented). iu c ngha l cc thnh phn trong Excel c th coi l cc i tng. Excel c hn 100 i tng. cho cc bn d hnh dung chng ta c th ly mt v d nh sau: Ta c mt chic xe my ca Honda, c th xem l mt i tng. Honda c nhiu chng loi xe my nh Future, Future II, Future neo; 17

Sch Lp trnh Excel bng VBA

Super Dream; Wave anh-pha... Vy ta c th xem Xe my ca hng Honda l mt tp hp, trong tp hp ny c cc i tng cng nm trong mt nhm nh Future, Future II, Future neo. V d di y l nhng i tng trong Excel: Code: the Excel application (l ng dng trong Exceli tng ln nht- hnh 14) a workbook (chnh l file excel) a worksheet (l cc sheet trong workbook) a range (l vng) a chart (l biu )

Hnh 14: Cc i tng trong Excel Bn c th coi nhng i tng trn nh l danh t (v d: ci bnh l danh t). Trong macro bn lp, m Range(B3) chnh l i tng. i tng ny c th cha cc i tng khc trong n. i tng Application bc cao nht (i tng m), bao gm ton b i tng trong Excel. Nhng thay i xy ra trong i tng Application nh hng n ton b ni dung trong n. i tng Application c cha i tng cng ln nh Workbooks. V d nh sau: Application.Workbooks cp (refer) n tt c workbook ang m trong Excel. 18

Sch Lp trnh Excel bng VBA

Workbooks.Item(1) cp n workbook u tin v thng c gi tt l Workbooks(1). Workbooks(Seles.xls) s cp n workbook tn . Trong workbook thng cha cc worksheet, trong mi worksheet cha nhiu (cell). Bn c th cp n B3 nh sau Workbooks(Seles.xls).Worksheets(Sheet1 ).Range(B3) Trong lc workbook ang lm vic th n c gi l active workbook (workbook hin hnh), worksheet no ang hin th th c gi l active worksheet. Nu bn c vi worksheet ang hin th, worksheet no ang c tr (cursor) trong n th c gi l avtive. Nu bn c vi workbook ang hin th, workbook no ang cha active worksheet trong n th c gi l avtive workbook. Nu bn khng mun thc hin ring trn workbook hay worksheet no, VBA s thc hin trn active workbook hay active worksheet (mc nh). Cn nu bn thc hin theo mun, th cn thc hin nh trn (Range(B3)). Cn Sheets la chn ton b sheet trong workbook, k c chart sheets (biu ) v worksheets. Sheet(Year2006) s tham chiu n sheet c tn l Year2006. Chart(1) s tham chiu n chart sheet theo th t tab. 4.2. Cc phng thc (Methods) Cc i tng c cc phng thc m c th thc hin cc hnh ng trong n. Nu ta xt n i tng l Range, v d di y l cc phng thc c th thc hin: Code: Activate (Hot ng hay hin hnh) Clear (Xo) Copy (Sao chp) Cut (Ct b i) Delete (Xo ni dung trong Range) Select (La chn) Cc phng thc c th c coi l ng t (v d: bake l ng t). C php ca cu lnh trong VB nh sau: Object.Method (Cake.Bake) Trong macro bn lp nh sau: 19

Sch Lp trnh Excel bng VBA

Range(B3).Select 4.3. Cc thuc tnh (Properties) Mi i tng u c cc c im ring. Thng thng thuc tnh iu khin hnh dng xut hin ca i tng. i vi i tng Range, cc thuc tnh c trng nh sau: Code: ColumnWidth Font Formula Text Value Thuc tnh c th c coi gn nh l tnh t. N c thit lp s dng trong cu lnh nh sau: Object.Property = Value hay Noun.Adjective = Value Vi macro trn: ActiveCell.FormulaR1C1 = Nguyen Van Hung Tt c cc i tng u c thit lp cc phng php (methods) v nhng thuc tnh (Properties) trong chng. Cu lnh nh Range(C3).ColumnWidth = 14 s thit lp chiu rng ca ct cha C3 rng 14. Excel mc nh chiu rng ca ct l 8.43 im (point). 4.4. Cc bin (Variables) Cng nh cc ngn ng lp trnh khc, bn c th s dng cc bin trong vic tnh ton. Bnh thng, VBA khng yu cu khai bo (declare) nhng bin. VBA lun t ng lu gi i vi nhng bin vo ln u tin bn s dng. Nhng bin c to ra t ng l cc dng ca bin th (Variant) v c th l nhng kiu d liu nh cc chui (strings), s (numbers), gi tr Boolean, cc li (errors), cc mng (arrays) hoc nhng i tng (objects). V d di y l khai bo n nh l s 34 i vi bin X. X = 34 Trong v d di y, bin s Number1 v Number2 c a ra gi tr ban u v s dng chng trong tnh ton (v chng l s). Number1 = 3 20

Sch Lp trnh Excel bng VBA

Number2 = 9 Mynumber = Number*Number2 4.4.1. Kiu d liu trong VBA Mi ng dng thng x l nhiu d liu, ta dng khi nim bin lu tr d liu trong b nh my tnh, mi bin lu tr 1 d liu ca chng trnh. Mc d VBA khng i hi, nhng ta nn nh ngha r rng tng bin trc khi truy xut n code ca chng trnh c trong sng, d hiu, d bo tr v pht trin. Nu bn cn nhng s liu c c trng ring (nh s nguyn, thp phn, chui, mng,...) s dng trong macro, bn c th khai bo bin . Cng nh quy nh t tn ca macro, cch t tn cho bin nh sau: Tn bin c th di n 255 k t. K t u tin phi l mt k t ch (letter), cc k t tip theo c th l cc k t ch (letter), k s (digit), du gch di (_). Tn bin khng c cha cc k t c bit nh cc k t : ^, &, ),(,%, $, #, @, !, ~, +, -, *, VBA khng phn bit ch HOA hay ch thng trong tn bin. Nn chn tn bin ngn gn nhng th hin r ngha. Khi vit tn bin ta nn vit hoa ch u tin ca mt t c ngha. Khng c dng tn bin trng vi cc t kho nh : Print, Sub, End(t kha l nhng t m ngn ng VBA dng cho nhng thnh phn xc nh ca ngn ng

21

Sch Lp trnh Excel bng VBA

4.4.2. Khai bo kiu d liu Cch khai bo bin s: Dim variable_name As data_type C cc kiu d liu (data_type) c trnh by nh sau:

Khai bo bin s l th tc tc ng n quy trnh x l v khng b thay i bi th tc khc. Nhng bin s m vt qu vng ca loi d liu quy nh (trong bng trn) th bin s b li Overflow (trn b nh). V d v s dng Dim trong khai bo bin s: Sub Kieudulieu() Dim Tuoi As Integer Tui l s nguyn Dim Caodo As Single Cao l s Dim Ten As String Tn ngi l chui Tuoi = 22 Khai bo tng gi tr Tuoi, Caodo, Ten Caodo = 6.75 Ten = "Nguyen Van Hung" MsgBox "Ho va ten: " & Ten & vbTab & vbTab & "Tuoi la " & Tuoi MsgBox "Cao do ho khoan la + " & Caodo & " (m)" 22

Sch Lp trnh Excel bng VBA

End Sub Kt qu th hin hnh v di y:

Hnh v 15: Kt qu th hin kiu d liu

Vi nhng gi tr khng thay i th nn thit lp nh nhng hng s (constant). iu ngn cn chng b bin i do nhm ln. V d: Const Pi = 3.14159 Dientich = Pi*2 Nu bn mun th tc (Sub) khc truy cp nhng bin s , hy khai bo chng dng u tin ca Module, trn c cu lnh Sub (hnh 16). Trng hp ny hay s dng khi bn c mt bin s dng chung cho chng trnh. Ngoi ra, bn c th yu cu phi khai bo ton b bin s bng cch s dng Option Explicit. Nu c bin no cha c khai bo, VBA s bo li ngay (hnh 16)

Hnh v 16: Khai bo Option Explicit v bin dng chung trn cng

23

Sch Lp trnh Excel bng VBA

Trong v d tip theo, bin s khai bo gi tr ban u (bng 0) v sau khi s dng phng php m cc trong vng B1:B10 tho mn iu kin gi tr (value) trong nh hn 40. Bin s D s b thay i. Sub VD_Bienso() Dim Marks As Range Dim C, D As Integer Set Marks = Range(B1:B10) D=0 For Each C in Marks If C.value < 40 then D=D+1 End If Next C MsgBox Gia tri moi cua bien so D la & D End Sub thay i ni dung bi: PhanTuHuong, 24-11-06 lc 10:28 AM L do: sa li 4.5. S dng mng (Array) Mng l kiu d liu c bit v hay c ng dng trong vic thng k, tnh ton,... nn c trnh by mc ring. Cc mng (Arrays) cha cc bin s c sp xp theo trnh t quy nh. Mi bin s c gi l phn t ca mng. Mng c bin trn v bin di, cc phn t trong mng l lin tc. V d nh danh sch hc sinh trong mt lp, gi tr ch tiu n l trong i vi mt ch tiu trong mu. C hai loi bin mng: mng c chiu di c nh v mng ng. 4.5.1. Mng c chiu di c nh Th tc Dim c th s dng khai bo trong mng c chiu di c nh m khng cn a gi tr no vo. V d: Code: Dim Arr(4) Dim Myfriends(1 to 30) As String Dim Noisuy(1 to 20, 1 to 30) As Single

24

Sch Lp trnh Excel bng VBA

Mng Arr(4) to ra mng 1 chiu cha 5 phn t. Vi kiu khai bo ny (4), phn t u tin (bin di) l Arr(0). phn t u tin bt u t 1 th bn phi khai bo Option Base 1 trn u ca th tc (Sub). Mng Myfriends to ra mng 1 chiu cha c 30 chui (l tn ngi). Mng Noisuy to ra mng 2 chiu vi kch thc cnh 20 x 30 (tng ng 600 gi tr l s). Hm s c tn l Array c th to nn mng t cc bin s trong n. Dim Array(Michael, David, Peter, Jackson) Khi s dng hm Array, nhng bin s mc nh l kiu bin Variant. xc nh thng s ca hm Array, ph bin dng 2 hm sau: Hm UBound tr v phn t cui cng ca mng. Hm LBound tr v phn t u tin ca mng. V d: Hnh 17 l kt qu ca Sub di y Option Base 1 Sub assignArray() Dim Arr(4) As String Arr(1) = "Thang 1" Arr(2) = "Thang 2" Arr(3) = "Thang 3" Arr(4) = "Thang 4" MsgBox Arr(1) & Chr(13) & Arr(2) & vbNewLine & Arr(3) & vbCrLf & Arr(4) End Sub

Hnh 17: Cc phn t trong mng

Hm Msgbox s cho hin hp thng bo nh bn cnh, cc bn s hc mc 11.1. 25

Sch Lp trnh Excel bng VBA

Ngoi ra cc bn cn thy hm Chr(13), vbNewLine, vbCrLf c cng tc dng l ngt dng trong hp thoi (ging nh phm Enter ngt dng trong Word). 4.6. S dng With - End With With - End With dng thc hin nhiu thao tc i vi i tng n l. Phng php ny c s dng i vi i tng no c nhiu thuc tnh. hiu c cch s dng With - End With trong cng vic, v d di y th hin quy trnh thc hin. Chng trnh con ny s lm thay i 5 thuc tnh ca vng nh dng. Code:
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

Trong th tc trn, bn thy on Selection.Font. c lp li nhiu ln v bn c th vit li khi s dng With - End With. Di y l th tc sa li: Code: Sub ChangeFont2() With Selection.Font .Name = Times New Roman .FontStyle = Bold Italic .Size = 12 .Underline = xlUnderlineStyleSingle .ColorIndex = 5 End With End Sub Bn s thy khi s dng With- End With, vic qun l cc i tng v thuc tnh ca chng d dng hn. 5. S dng gip Help Trong qu trnh vit macro, chc chn bn phi cn n tr gip. Khng c sch no c th vit c ht v VBA ni ring v cc ngn ng lp trnh ni chung, v nhng kin thc trong rt rng ln. V vy bn nn s dng tnh 26

Sch Lp trnh Excel bng VBA

nng Help ca VBA. iu c bn nht s dng Help l bn phi bit ting Anh c v hiu c cc hng dn . Nhng ngi c trnh v lp trnh cao nh ti bit u ch yu s dng sch ting Anh v c trong Help. Ni dung trnh by di y s cho cc bn hiu c mc tin dng ca Help nh th no. 5.1. Ti thi im ang vit code Trong qu trnh vit macro ti ca s Microsoft Visual Basic, bn c th truy cp vo help ti nhng mc chn chi tit (v d nh Select) nh sau: - Chn mc c th (di chuyn chut vo ch Select). - Sau n phm F1. Khi hin ca s Microsoft Visual Basic Help nh hnh 19. 5.2. S dng hp thoi gip vi ch c th s dng hp thoi gip vi ch (topic) c th, bn thc hin cc bc sau: - Vo ca s Microsoft Visual Basic ang m (nu cha m th bn vo menu Tools/Maros/Visual Basic Editer hoc phm tt Alt + F11). - T menu Help, bn chn Microsoft Visual Basic Help. - Bn c th thc hin bng cch s dng chc nng Search (v d g ni dung commandbar, ri Enter) hoc c th chn ch m bn ang cn tm trong danh mc.

27

Sch Lp trnh Excel bng VBA

Hnh 19: Ca s Microsoft Visual Basic Help

Hnh 20: S dng Visual Basic Help

5.3. Trnh duyt i tng Phng thc trnh duyt i tng (Object Browser) c s dng xem cc i tng, cc phng php v nhng thuc tnh trong vic b sung thm cc hm s (functions) v cc lnh (statements) c xy dng trong Visual Basic for Excel. Code: 1. Vo ca s Microsoft Visual Basic ang m. 2. T menu View, bn chn Object Browser (hoc n phm F2).

28

Sch Lp trnh Excel bng VBA

Hnh 21: Chn ch c th bng search hoc trong Table of contents

Sau ca s hin ra gia cha danh mc cc nhm - lp (classes) khc nhau ca i tng. Nhm (class) chnh l phn m t cc dng ca i tng (v d nh particular chart thuc v nhm Chart) . Nhm thuc d n (project) hay th vin (library). Code:
3. Bm vo hnh tam gic i xung bn cnh <All Libraries> v chn Excel (hnh 19). Khi cc nhm thuc Excel s xut hin. 4. Trong vng Classes, ban cun xung v chn Range. 5. Trong Members of Range bn bm vo ClearContents. 6. Ch dn bn cnh ClearContents m c k hiu mu xanh cho bit i tng l phng php (method).

29

Sch Lp trnh Excel bng VBA

7. Nu mun bit thm thng tin v ClearContents, bn bm vo nt Help (hnh du ? mu vng). 8. xem v d, bn n vo Example mu xanh (hnh 20). 9. ng ca s hng dn s dng ClearContents v tip tc cun tm cc thnh phn khc trong Members of Range. 10. Ch dn m c biu tng khc bn cnh (hnh bn tay ch) cho bit hm l thuc tnh (property). 11. ng ca s Visual Basic Object Browser vo.

Hnh 22: Ca s Object Browser

30

Sch Lp trnh Excel bng VBA

Hnh 23: Cc nhm thuc i tng Excel

Hnh 24: Ca s Help i vi cc i tng trong Excel.

31

Sch Lp trnh Excel bng VBA

5.4. Cc file v d Excel a ra mt s file v d c tn l Samples.xls. Hu ht i vi mi phin bn Excel khc nhau th ng dn n file ny cng khc nhau. Trong Excel 2003, bn c th tm thy file ny ti ng dn sau: C:\Program Files\Microsoft Office\Office10\Samples.xls ??? Samples.xls cp nhiu ng dng ca Excel. Mi sheet hng dn mt phn cng vic. Ni dung c lin quan n VBA l Chart Labeling, Repeating Tasks, Arrays, API examples, Events, Automation, ADO,... Hnh nh v file Samples. xls trong Excel 2000.

Hnh 25: Ni dung File v d Samples. xls

32

Sch Lp trnh Excel bng VBA

6. Mt s chc nng iu khin trong VBA Cng nh VB, VBA c nhng tnh nng iu khin trong qu trnh vit code rt thun li. Bn c th tu bin thay i nhng thng bo hoc giao din ca ca s son code Microsoft Visual Basic (MSB).

Hnh 26: S dng Options trong menu Tools ca MVS

33

Sch Lp trnh Excel bng VBA

Hnh v 27: Ca s Editor v Editor Format trong Options

6.1. S dng Options Bn vo menu Tools, chn Option (hnh 26), ca s Options hin ra nh hnh 27. Trong Editor c cc la chn chnh sau: Auto Syntax Check: Trong trng hp khng chn, m khi bn thc hin sai th dng c mu , khng xut hin hp thng bo nh hnh 37. Require Variable Declaration: Khi c chn, dng Option Explicit lun xut hin u Module.

Hnh 28: Ca s Auto List Members

Auto List Members: Khi c chn, VBA s t ng cho hin danh sch cc thuc tnh v phng thc ca mt iu khin hay mt lp, khi ta g vo tn ca iu khin (hnh 28). 34

Sch Lp trnh Excel bng VBA

Auto Quick Info: Tng t nh trn, nhng n hin th c php ca 1 hm hay th tc, tham s u tin c in m.

Hnh 29: Ca s Auto Quick Info

Auto Data Tip: Hin th danh sch cc d liu khi khai bo bin.

Hnh 30: Ca s Auto Data Tip

Trong ca s Editor Format c cc la chn chnh sau: Code Color: Bn c th la chn mu ch, mu nn ca tng loi code, mc nh l Auto. Font: Chn loi font ch tu thch, mc nh l font Courier New. Size: Chn kch c font ch, ph hp vi ngi mt km Ngoi ra cn mt s la chn khc, cc bn t tm hiu. Ghi ch: VBA c rt nhiu i tng, phng thc v thuc tnh. Bn khng th no bit c ht hoc s b qun. VBA cung cp cho bn nhng tnh nng gi nh trn gip cc bn c th khai thc tt hn VBA. 6.2. S dng VBAProject Trong menu Tools, chn VBAProject Properties, ca s VBAProject hin ra nh hnh 31. VBProject: nhn dng d n ca bn trong Window Registry (khai bo trong Window) v trong Object Browser. iu quan trng l n c tn duy nht. .

35

Sch Lp trnh Excel bng VBA

Project Description: M t tn ca d n ca bn trong Type Library. Th vin Type Library cha ton b nhng m t v i tng v giao din ca d n ca bn.

Hnh 31: S dng VBAProject Properties

36

Sch Lp trnh Excel bng VBA

Hnh 32: D n Su_dung_VBA trong <All Librairies> v bo v code trong Protection

C nhng d n (project) ca bn lp ra m khng mun ngi khc xem code, bn c th kho li. thc hin cng vic ny, trong tab Protection bn la chn nh sau: Lock project: Kho code trong module, khng cho nhn thy v khng cho sa cha. Bn phi chn mc Lock project for viewing. Password to view project properties: Bn phi g ni dung m kho trong hp Password, ni dung m kho bin thnh du sao *. Sau , bn phi xc nhn ni dung m kho trong Confirm password bng cch g li ni dung m kho va vo. Nu bn g khng ng ni dung, VBA s bo li v bn phi g li cho ng. S k t ti a l 24 k t, c th l s, ch v cc k t c bit. Sau , mi khi m file trn, c th xem c code, bn vo menu Tools/Macro, chn Visual Basic Editer (hoc n Alt + F11). Ca s Microsoft Visual Basic hin ra, tuy nhin ton b ni dung code u khng hin ra (hnh v 33). xem c ni dung code, bn nhy kp vo Su_dung_VBA Project, ca s Su_dung_VBA Password hin ra. Bn phi khai bo ng Password th ni dung code mi hin ra.

37

Sch Lp trnh Excel bng VBA

Hnh 33: Hp thoi hi m kho khi bn m Project b kho.

Ghi ch: Lu khi s dng m kho, nu bn qun th s khng th m c project. V vy, bn phi nh ni dung m kho v nn chn ni dung no d nh. Nu mun i m kho th bn vo ca s Password thay i. 6.3. S dng chc nng Security My nm gn y, do virus macro pht trin nn Microsoft b sung thm ch an ton trong cc ng dng. Chc nng Security iu khin s lm vic ca macro, tc l c th cho hot ng hoc khng. 1. Bn vo menu Tools/Macro v chn Security (hnh 34), ca s Security hin ra. 2. Trong Security, ti tab Security Level c 4 trng hp chn nh sau: - Very High: t ch an ton rt cao, cc macro khng th chy c, ch tr macro ca Office. - High: Ch nhng macro c xc nhn mi c th chy, cc macro khc cng b v hiu ha. c macro c xc nhn, bn phi ng k trong menu Tools\Option\Securitry\More Macro\Trusted Publisher. - Medium: t ch an ton trung bnh. Khi chn trng hp ny, nu bn m file c cha macro th n s cnh bo nh hnh 35. Bn c th la chn Enable Macros cho macro hot ng hoc Disable Macros macro khng hot ng. Trong trng hp file ca bn khng s dng macro (th tc hay hm t to) m khi m Excel cnh bo nh hnh 31 th file ca bn b nhim virus macro. - Low: Khng t ch an ton, tc l Excel khng cnh bo bt c vn g c. 3. Nh vy, khi bn s dng VBA th nn t Security Level mc Medium hoc Low. Khi cc th tc, hoc hm mi hot ng c.

38

Sch Lp trnh Excel bng VBA

Hnh 34: Vo menu Security v ca s Security

Hnh 35: Cnh bo macro cha trong file

39

Sch Lp trnh Excel bng VBA

7. Vit macro Khi bn tin hnh ghi (record) macro, Excel s t ng to module v b sung n vo trong workbook v vit li nhng hnh ng bn ghi thuc v module . Khi bn mun vit m (code) trong workbook, bn c th b sung module trong workbook . S ghp ni cho pht trin macro c gi l Visual Basic Integrated Development Evironment (IDE). Macro c trong module c hin ra trong IDE thay th cho bng tnh trong workbook (nh Excel i trc 97). 7.1. Vit macro Trc tin chuyn sang workbook mi (nhng cho php workbook c vn m) nh sau:
1. Tip theo bm chut vo nt New trong thanh cng c (toolbar), hoc vo menu File ri chn New. 2. Bm chut phi ti tn ca Sheet1 v chn Rename trong menu tt. 3. G ni dung Text ri n Enter. Vit macro: 1. T menu Tools/Macros bn chn Visual Basic Editor. 2. Trong ca s Microsoft Visual Basic bn vo menu Insert v chn Module (hnh 36). 3. Nu cn, bn c th thay i tn ca module theo mun. Trong ca s Properties, bn cnh (Name) bn chn Module1 v sa thnh Chuongtrinh. 4. Bm vo vng trng ca ca s Chuongtrinh (phn code). 5. G Sub MyFirst ri bm Enter. Khi Excel s t ng in () v End Sub, th hin nh hnh 36. 6. G cc lnh tng bc mt theo s m t di. Bn c th c c nhng gip trong Sub Address_abs() ti mc 4 v hnh 13.

Trc , macro ca bn cha cc lnh n gin. - Bc 1: Chn sheet c tn Text (dng Sheets(Text).Select) - Bc 2: G on I can write macros! trong B2 trong sheet . - Bc 3: Bi m ch. Cui cng, bn kim tra (test) li macro Text:
1. Quay tr v sheet Text. 2. T menu Tools/Macros chn Macros. 3. Trong ca s Macros, bn chn macro c tn l MyFirst v chn Run.

Mi vic s tt p, on ch m I can write macros! s c nhp vo B2. 40

Sch Lp trnh Excel bng VBA

Khi code b li th s c bng thng bo li, v d nh hnh 37.

Hnh 36: To Module v Sub trong workbook

Hnh 37: Li gp phi trong vic xy dng macro

41

Sch Lp trnh Excel bng VBA

Hnh 38: Sa li gp phi khi vit code

Khi gp li, bn tin hnh theo cc bc sau y:


1. Bm vo nt Debug v tm kim li sa li. Li ca cu lnh u tin s c bi nn mu vng (hnh 38). 2. Sa nhng cu lnh sai trong phn c bi vng . 3. Mi tn vng l s cho bit rng macro ang ch dng (break mode). 4. Ngoi ra bn c th bm vo Run, sau chn Reset xc lp li (hnh 38) hoc chn Design Mode xc lp ch thit k. Cn nu mun macro chy tip th chn Continue (hoc n phm F5). 5. Quay tr v sheet Text v xem macro lm vic c chnh xc khng.

7.2. Sa cha li Khi bn g mt dng code trong macro v g Enter, Excel s kim tra dng . Nu n tm c s hng m hiu c, v d nh range, th s tr thnh Range (ch r t ng chuyn thnh ch hoa R u). Nu code thiu hoc tm ra li, Excel s bin ni dung thnh mu v hin ra bng thng bo li (hnh 39). C nhiu loi li khc nhau, tu vo li c th m c tng kiu ni dung bng thng bo.

42

Sch Lp trnh Excel bng VBA

Hnh 39: Bo li code

Nu bn mun bit thm thng tin v li th bm vo nt Help. sa cha li , bn bm OK v sa ni dung dng c mu cho ng. C nhng trng hp gp phi nhng li m khng c thng bo cho n khi Visual Basic bin dch n trc khi chy. Trng hp m bn gp l li compile-time. Visual Basic s cho bit v tr ca li v s gi cho bn thng bo v li . Cn cc li khc ch xut hin khi macro chy tht s. c gi l li run-time. sa cha li ny th bn bm vo Goto ri sa on code . Mt s li gp phi khng hn l li, n ch xut hin khi macro chy. V d nh chia mt s cho khng (zero) c th xy ra ngoi mun. Da vo hon cnh m bn c th s dng cu lnh On Error by li (xem mc 13).

43

Sch Lp trnh Excel bng VBA

8. Tham chiu n v vng Bn c th s dng macro tham chiu n cc hoc vng trong worksheet. Nu bn mun gn d liu vo worksheet, bn s phi s dng n i tng Range. i tng Range c s dng vo loi nhiu nht trong Excel tham chiu n ring l (a cell) hoc vng (range). C vi cch cho gi tr i tng Range c m t pha di y. 8.1. Tham chiu kiu A1 Di y l bng v d cc dng tham chiu n , vng ca theo kiu A1 khi s dng phng thc Range.( CP N THAY BNG THAM CHIU N)

V d 1: Range(A1:A3).Select th vng A1:A3 s c chn (bi en) V d 2: Vi workbook c tn Popupmenu, trong worksheet Sheet1, bn gn ni dung Bo mon DCCT vo B3. Sau cho ni dung ch m, nghing, mu v nn mu vng. Code:
Sub Thunghiem() Workbook(Popupmenu).Sheets(Sheet1).Range("B3").Select ActiveCell.FormulaR1C1 = "Bo mon DCCT" Selection.Font.Bold = True Selection.Font.Italic = True Selection.Font.ColorIndex = 3 With Selection.Interior

44

Sch Lp trnh Excel bng VBA

.ColorIndex = 6 .Pattern = xlSolid End With Range("B4").Select End Sub

Hng dn chn vng tt: Bn c th dng ngoc vung [ ] chn vng thay v (). So snh vi v d nh sau: [A1:A3].Select l cch chn vng ging nh Range(A1:A3).Select thay i ni dung bi: PhanTuHuong, 05-12-06 lc 12:49 PM 8.2. S ch mc (Index numbers) Thuc tnh Cells c th s dng tr v i tng mng l n. S ch mc hng v ct ca cung cp cho Cells(row_no,col_no). Nu m khng c s hng v ct th Cells() s tr v i tng l ton b trong sheet (ging nh phm tt Ctr + A). V d 1: Cells(4,1) tr v A4 Cells() tr v ton b trong sheet V d 2: Worksheets(Sheet2).Cells(3,2).Value = 2000 tr v s 2000 trong B3 ti Sheet2, trong workbook hin hnh. Ghi ch: Thuc tnh Cells c ng dng nhiu khi vit cc vng lp gia cc . 8.3. S hng v s ct (Rows and Columns) y l mt cp thuc tnh c gi l Rows v Columns, chng gip bn c th lm vic vi ton b dng hoc ct. Code:
Tham chiu Rows(4) Rows Columns(4) Columns(D) Columns cp n Hng s 4 Ton b dng trong sheet hin hnh Ct D (ct th 4) Ct D Ton b ct trong sheet hin hnh __________________________________________________

45

Sch Lp trnh Excel bng VBA

V d: Worksheets(Week4).Rows(2).Font.Bold = True cho kt qu l ton b hng 2 trong sheet Week4 ch m ca workbook hin hnh. Ghi ch: Bn c th thc hin i vi nhiu hng v ct khi s dng phng thc Union. V d v s hp nht gia hai vng Range1 v Range2 khi s dng phng thc Union c in y bi cng thc =RAND() Worksheets("Sheet1").Activate Set Vung = Application.Union(Range("Range1"), Range("Range2")) Vung.Formula = "=RAND()" 8.4. t tn cho vng (Named ranges) Vi mt s trng hp bn phn chia vng cc ra vi tn xc nh d truy cp v nghin cu. Cng vic ny gn ging nh khi bn s dng chc nng t tn cho vng trong Excel (xem trong menu Insert/Name/Define...). Khi bn chn tn nhng vng th Excel s truy cp n vng m bn la chn. Bn phi t tn nhng vng trc khi vit macro hay dng chnh macro to tn ca vng. 8.4.1. Tn c to ra ngoi macro t tn cho vng, u tin bn chn chn nhng bng cch bi en, sau bn bm vo phn Name Box (phn gc trn bn tri, cng hng vi thanh cng thc). Sau t tn ca vng ri Enter. Gi thit rng bn t tn Congty cho cc C2:C8 trong sheet Danhsach ca workbook Quanly (hnh 40). V d 1: s lm cc trong vng C2:C8 m ln.
Range([Quanly.xls]Danhsach!Congty).Font.Bold = True

V d 2: Nu workbook Quanly v worksheet Danhsach ang hin hnh, th


Range(Congty).Font.Bold = False

s lm cc trong vng C2:C8 mt m (ch bnh thng).

46

Sch Lp trnh Excel bng VBA

Hnh 40: To tn ca vng

8.4.2. Tn c to ra trong macro Tn vng c th c n nh khi s dng macro lp, v d di y:


Workbooks(Congty.xls).Names.Add Name:=Congty, _ RefersTo:==Danhsach!D1:D10 Range(Congty).Font.Italic = True

Kt qu l cc trong vng D1:D10 s b nghing. 8.5. Nhiu vng (Multiple ranges) Trng hp ny hay c s dng tham chiu n nhiu vng trong macro, c th xo sch ni dung trong cc .
Worksheets(Bang).Range(A1:C3,H4:L8,P14:Z3 4).ClearContents

s xo sch ni dung nhng ch nh trong worksheet Bang. Cn i vi nhng tn vng bn t (nh trn), c th thc hin nh sau:
Range(Danhsach1, Danhsach2, Danhsach3).ClearContents

Ghi ch: Trong macro, cc vng c th c xc nh, t tn v c phi hp khi s dng phng thc Union. Xem mc 9.3. 8.6. Offset cells Thuc tnh Offset thng c s dng tham chiu n khc m c quan h vi ang hot ng. 47

Sch Lp trnh Excel bng VBA

Cng thc dng tng qut: Offset(no_rows_down, no_cols_to_right) no_rows_down l s nguyn v c hiu l xung di bao nhiu dng. no_cols_to_right l s nguyn v c hiu chuyn sang phi bao nhiu ct. V d 1: Nh hnh 41, gi thit B1 l hin hnh. By gi bn dng Offset ch trong C2 c mu , C5 m, C8 nghing, C9 c ni dung X nghip kho st a k thut.
Sub Offset() Range("B1").Activate ActiveCell.Offset(1, 1).Font.ColorIndex = 3 ActiveCell.Offset(4, 1).Font.Bold = True ActiveCell.Offset(8, 1).Value = "X nghip kho st a k thut" ActiveCell.Offset(8, 1).Font.Size = 12 Range("E9").Activate ActiveCell.Offset(-1, -2).Font.Italic = True End Sub

Kt qu th hin hnh 41.

48

Sch Lp trnh Excel bng VBA

Hnh 41: S dng Offset tham chiu n cc

Ghi ch: Khi gi tr no_rows_down hoc no_cols_to_right c gi tr m th s c hng ngc li. 8.7. Kiu tham chiu R1C1 Khi s dng kiu R1C1, Excel s tham chiu n m c xc nh bi s hng v ct. V d tham chiu R4C2 s truy cp n B4. Khi s dng kiu tham chiu ny, mi quan h gia cc trong tnh ton s c th hin trong cng thc. R[m]C[n] s tham chiu n (truy cp n) c m dng pha di v n ct pha bn phi so vi hot ng (hin hnh). Gi tr m,n c th l s m, khi hng s ngc li, ln trn v sang bn tri. V d 1: Nhp vo cng thc Sum(B2:B4) trong B5. B5 c a ch hng 5 v ct B v c gi tr l tng cc ca 3 hng trc , gm dng th 2 n dng th t nhng cng ct. T xy dng macro nh sau:
Range(B5).Select ActiveCell.FormulaR1C1 = =Sum(R[-3]C:R[-1]C)

V d 2: Nhp vo cng thc = F2-F4 trong D5. Ni dung R1C1 trong FormulaR1C1 c th khng cn dng n v nu bn mun, 2 dng trn c th ghp thnh 1 nh sau: 49

Sch Lp trnh Excel bng VBA

Range(B5).Formula = =R[-3]C[2]-R[-1]C[2]

V d 3: Thay i cng thc thnh gi tr kt qu. G6 c cng thc l =G5*G4. V d G5 c gi tr l 2, G4 c gi tr l 3, nh vy gi tr nhn c ca G6 l 6. Ta s thay ni dung hm thnh gi tr l 6.
Range(G6).Select ActiveCell.FormulaR1C1 = =R[-1]C:R[-2]C Selection.Copy Selection.PasteSpecial Paste:=xlValues Application.CutCopyMode = False

Dng lnh cui cng l lnh hu b ch trng thi Cut/Copy (ng gch nhp nhy bao quanh chn). 9. Cu trc iu khin Mt s trng hp, bn phi s dng macro kim tra nhng iu kin c bit trong worksheet v iu khin chng p ng c yu cu ra. Vi mi iu kin khc nhau th macro s thc hin cng vic khc nhau. Vi cu trc iu khin nh vy khng th t ng ghi c, bn phi vit chng trong Visual Basic. 9.1. Cu lnh IF y l kiu n gin nht, mu ca cu lnh IF nh sau: If <iu kin> Then <dng lnh 1> [Else <dng lnh 2>] Trong ch dn trn, cc thng s trong [ ] l tu chn, c th b qua nu thy khng cn thit. Nu <iu kin> c toi nguyn (ng - True) th <dng lnh 1> c thc hin, cn nu khng c toi nguyn (sai - False) th <dng lnh 2> c thc hin. Thng thng, bn hay s dng cu lnh If ... then ... Else m khng cn phi gii hn s dng lnh. Mu nh sau:
If <iu kin1> Then <Khi lnh 1 thc hin> [ElseIf <iu kin2> <Khi lnh 2 thc hin>] [ElseIf <iu kin3> <Khi lnh 3 thc hin>]

50

Sch Lp trnh Excel bng VBA

[Else <Khi lnh 4 thc hin>] End If

Trong mu tng qut trn, t kho ElseIf v Else l tu chn (nh biu th trong du ngoc vung). u tin VB kim tra iu kin th nht, nu sai th s chuyn sang iu kin th 2,... cho n khi iu kin ng. VB thi hnh khi lnh tng ng v sau , thi hnh dng chng trnh ngay sau End If. V d: Macro di y tm kim gi tr ti A1 (l im trung bnh mn hc).
Nu 10 > A1 8.0 : Hc lc gii; Nu 8 > A1 6.5 : Hc lc kh; Nu 6.5 > A1 5.0 : Hc lc trung bnh; Nu 5 > A1 0 : Hc lc km.

B2 th hin kt qu hc lc.
Sub Hocluc() Sheets(Sheet1).Select Range(A1).Select If ActiveCell >= 8 Then Range(B2).Value = Hc lc gii ElseIf ActiveCell >= 6.5 Then Range(B2).Value = Hc lc kh ElseIf ActiveCell >= 5 Then Range(B2).Value = Hc lc trung bnh Else Range(B2).Value = Hc lc km End If End Sub

Ghi ch: Bn c th b qua dng Range(A1).Select v thay bng If Range(A1).Value >= 8 Then. Ngoi ra, bn cng c th s dng If kt thc macro, cu lnh nh sau c th s dng kt thc macro. If ActiveCell = Then End Sub (nu hin hnh m trng th s kt thc Sub, khng cn phi c End If)

51

Sch Lp trnh Excel bng VBA

V d: Gi s bn tm kim gi tr ca mt v bn mun kt qu nh sau Dng macro khi trng. Nhp gi tr Tt vo ngay bn phi nu c gi tr ln hn 40. Nhp gi tr Km vo ngay bn phi nu c gi tr nh hn 40.
Sub user_If() If ActiveCell.Value = "" Then Exit Sub If ActiveCell.Value >= 40 Then ActiveCell.Offset(0, 1).Value = "Tt" Else ActiveCell.Offset(0, 1).Value = "Xu" End If End Sub

9.2. S dng Select Case Select Case l mt dng ca If ... Then ... Else, c s dng khi c nhiu iu kin chn lc gi tr. Cu lnh nh sau: Select Case <biu thc kim tra> [Case <biu thc 1> <khi lnh 1>] [Case <biu thc 2> <khi lnh 2>] [Case <biu thc 3> <khi lnh 3>] .... [Case Else <biu thc n> <khi lnh n>] End Select Mi danh sch biu thc c 1 hay nhiu gi tr. Cc gi tr cch nhau bng du phy (,). Cn gi tr bin i trong vng th bn s dng t kho To. Mi khi lnh c th cha 0 hay nhiu dng lnh. Nu biu thc no tho mn iu kin th khi lnh tng ng s thc hin. Case Else khng nht thit phi c, dng trong trng hp cn li ca cc Case trc.

52

Sch Lp trnh Excel bng VBA

V d: B2 cha gi tr st ca t, C2 s th hin trng thi ca n.


Sub Trangthai() Sheets(Sheet1).Select Doset = Cells(2,2).Value Select Case Doset Case 1, 1 to 10 Cells(2,3).Value= Chy Case 0.75 to 1 Cells(2,3).Value= Do chy Case 0.5 to 0.75 Cells(2,3).Value= Do mm Case 0.25 to 0.5 Cells(2,3).Value= Do cng Case 0 to 0.25 Cells(2,3).Value= Na cng Case < 0 Cells(2,3).Value= Cng End Select End Sub

9.3. Xy dng cc iu kin Trong nhiu trng hp, iu kin lc d liu tr nn kh phc tp. Nu ch s dng If hay Select Case th cng vic s rt cng knh, rc ri. Trong hon cnh , And v Or gip bn thc hin cng vic , gip chng trnh sng sa v d c. 9.3.1. S dng And Cu lnh nh sau: If <iu kin 1> And <iu kin 2> Then <khi lnh 1> Else <khi lnh 2> End If
`

53

Sch Lp trnh Excel bng VBA

<khi lnh 1> ch thc hin khi c hai iu kin 1 v 2 u ng. Ch 1 trong 2 iu kin sai th <khi lnh 2> s thc hin. 9.3.2. S dng Or Cu lnh nh sau: If <iu kin 1> Or <iu kin 2> Then <khi lnh 1> Else <khi lnh 2> End If <khi lnh 1> thc hin khi mt trong hai iu kin 1 v 2 ng. C 2 iu kin sai th <khi lnh 2> s thc hin. 9.3.3. S dng nhiu And v Or Cu lnh nh di y: If <iu kin 1> And <iu kin 2> And <iu kin 3> Then <khi lnh 1> Else <khi lnh 2> End If <khi lnh 1> ch thc hin khi c ba iu kin u ng. Ch 1 trong 3 iu kin sai th <khi lnh 2> s thc hin. Tng t i vi Or. V d: Bn c th xc nh tn t da vo h s rng t nhin, ch s do, st.
Sub Ten_dat() Dim Hsr, Chisodeo, Doset As Single Hsr = InputBox("Vao gia tri he so rong:") Chisodeo = InputBox("Vao gia tri chi so deo:") Doset = InputBox("Vao gia tri do set:") If Hsr > 1.5 And Chisodeo >= 17 And Doset > 1 Then MsgBox "Day la dat BUN SET!" ElseIf Hsr > 1.0 And Chisodeo >= 7 And Doset > 1 Then MsgBox "Day la dat BUN SET PHA!"

54

Sch Lp trnh Excel bng VBA

ElseIf Hsr > 0.9 And Chisodeo >= 1 And Doset > 1 Then MsgBox "Day la dat BUN CAT PHA!" Else MsgBox "Chua ro ten dat!!!!" End If End Sub

10. Hp thoi trong VBA Hp thoi (Dialog) l mt trong nhng cch thc Windows giao tip vi ngi s dng. Di y l 2 loi hp thoi m bn d dng to ra iu khin trong sut qu trnh chy macro (MsgBox v InputBox). 10.1. Hp thng bo (Message box) Cu lnh MsgBox s cho hin ln trn mn hnh mt hp thng bo, gi tr nhn c l bin s (variable) trong macro (nh hnh 18). S dng MsgBox gip bn rt hiu qu trong vic g ri (hoc tm ch sai, gi tr trung gian,...) khi xy dng chng trnh. Hm MsgBox dng tng qut MsgBox (prompt [, buttons] [, title] [, helpfile, context]) Trn mn hnh s hin hp thng bo v i bn bm chut vo nt chn v tr v gi tr nguyn no khi bn chn loi nt. prompt l ni dung li nhc ca hp thng bo. buttons l tu chn loi nt iu khin (nh Yes, No, OK) title l tu chn ni dung ch trn u hp thng bo helpfile l tu chn v iu khin file tr gip no s dng. context l tu chn v l s th t tnh hung trong helpfile. Nu helpfile c th mc context cng phi c. 10.1.1. Cc loi thng ip trong buttons

55

Sch Lp trnh Excel bng VBA

10.1.2. M t thng s cc nt

10.1.3. Cc biu tng thng ip

Ghi ch: Ti mi kiu thng ip, m thanh bo khi hin th thng ip i km theo s khc nhau. 10.1.4. Xy dng tham s cho MsgBox s dng tu bin hp thng bo, bn phi bit phi hp cc thng s v nt lnh. Vic s dng hp MsgBox c ngha rt quan trng trong vic iu khin chng trnh. hiu chi tit, cc bn xem v d di y.
Sub Nhangui() Dim Truonghop As Integer Truonghop = MsgBox("Ban co muon thoat khoi chuong trinh khong", vbYesNoCancel + vbQuestion + vbDefaultButton1,Chuong trinh tinh lun)

56

Sch Lp trnh Excel bng VBA

If Truonghop = vbYes Then MsgBox "Ban vua chon nut Yes.", vbInformation ElseIf Truonghop = vbNo Then MsgBox "Ban vua chon nut No.", vbCritical ElseIf Truonghop = vbCancel Then MsgBox "Ban vua bam nut Cancel.", vbExclamation End If End Sub

Hnh v di th hin kt qu chy Sub trn v hp thng bo khi bn chn nt No. Trong Sub trn, bn c th thay ElseIf Truonghop = vbNo Then bng ElseIf Truonghop = 7 Then

Hnh 42: V d v cch to MsgBox trong VB v khi chn nt No

10.2. Phng thc InputBox (Inputbox Method) Nhm th hin hp thoi ngi s dng nhp d liu vo. Khi s dng phng thc ny, mt hp thoi s cho hin ra bn vo d liu, ch cho ngi dng nhp d liu vo hoc l bm vo nt OK hoc Cancel, gi tr nhn c c coi l chui (string). y l mt cch vo gi tr n l hoc a ch ca cc trong qu trnh chy macro. Bn khng th gn c 57

Sch Lp trnh Excel bng VBA

lnh khi chn nt OK hay Cancel nh trong MsgBox. chnh l hn ch ca hm ny nn t c ng dng khi u vo nhiu s liu. Phng thc InputBox dng tng qut expression.InputBox (prompt [, title] [, default], [, left], [, top] [helpfile, context] [, type]) Expression: mt biu thc tr v i tng Application. Trong : prompt l ni dung li nhc ca hp vo d liu. title l tu chn ni dung ch trn u hp vo d liu. left l tu chn khong cch t gc bn tri hp thoi n gc bn tri mn hnh (mc nh l hp thoi nm gia mn hnh). n v tnh l l im (point), mt im bng 1/72 inch hay khong 1/28 cm. Chc nng ny t s dng. top l tu chn khong cch t nh hp thoi n nh mn hnh (mc nh l hp thoi nm gia mn hnh). n v tnh l l im. helpfile l tu chn v iu khin file tr gip no s dng. context l tu chn v l s th t tnh hung trong helpfile. Nu helpfile c th mc context cng phi c. type l tu chn bin s u vo. Trong trng hp b qua, gi tr u vo coi nh l chui.

V d:
Sub VD_Input() Dim Dangmang Dim Cot, Hang As Integer

58

Sch Lp trnh Excel bng VBA

Set Mang = Application.InputBox("Vao mang:", "Linh tinh", Type:=8) Cot = Dangmang.Columns.Count Tnh s ct chn Hng = Dangmang.Rows.Count Tnh s hng chn MsgBox "So cot la: " & Cot MsgBox "So hang la: " & Hang MsgBox "Dia chi o dau la: " & Dangmang.Cells(1, 1).Address MsgBox "Dia chi o cuoi la: " & Dangmang.Cells(Cot, Hang).Address Address l thng tin a ch End Sub

Kt qu vo d liu l mng di y. Ngoi ra bn cn thu c mt s thng tin v mng nh s hng, s ct, a ch ,...

11. Hnh ng lp (Loop) Hnh ng lp cho php bn thc hin mt on chng trnh nhiu ln. Chc nng ny ht sc c ngha khi bn x l cc i tng l mng. Bn c th iu khin hnh ng lp theo quy nh t ra. C cc kiu hnh ng lp nh sau: 11.1. Do ... Loop Thc hin mt khi lnh vi s ln lp xc nh. Trong , mt biu thc iu kin dng so snh quyt nh vng lp tip tc hay khng. iu kin phi quy v False (0) hoc True (khc 0). Mu tng qut: Do <khi lnh> Loop

59

Sch Lp trnh Excel bng VBA

V d:
Sub VD_Do() m = 4 m nhn gi tr ban u l 4 Do bt u vng lp m = m + 1 t gi tr m tng (+ 1) MsgBox m hp thng bo gi tr m If m > 10 Then Exit Do nu m > 10 th s thot khi Do Loop Tip tc lp End Sub

11.2. Do While ... Loop Thc hin khi lnh khi iu kin True. Hnh ng s lp vi iu kin True, cho n khi iu kin False th s thot ra. Mu tng qut: Do While <iu kin> <khi lnh> Loop V d:
Sub VD_DoW_Loop() i = 1 t i lc u bng 1 Do While i <= 10 t gii hn cho i, nu False th thot Cells(i,1) = i Gn i vo i = i + 1 Cho gi tr i tng dn MsgBox i Hp thng bo gi tr i Loop Tip tc lp End Sub

11.3. Do ... Loop While Tng t nh Do While ... Loop, thc hin khi lnh khi iu kin True. Hnh ng s lp vi iu kin True, cho n khi iu kin False th s thot ra. Mu tng qut: Do <khi lnh> Loop While <iu kin>

60

Sch Lp trnh Excel bng VBA

V d:
Sub VD_Do_LoopW() i=1 Do Cells(i,3) = i i=i+1 Msgbox i Loop While i <= 10 End Sub

11.4. Do Until ... Loop Bn c th thc hin cc khi lnh t u vng lp cho n khi iu kin vn True. n khi iu kin False th s thot ra. Phng thc ny ging nh vng lp For ... Next. Mu tng qut: Do Until <iu kin> <khi lnh> Loop V d:
Sub VD_DoU_Loop() i=1 Do Until i = 10 Cells(i,5) = i i=i+1 MsgBox i Loop End Sub

Tng t i vi Do ... Loop Until. 11.5. For ... Next Bn c th lp hnh ng vi s ln bit trc. Ta dng bin m tng dn hoc gim dn trong vng lp. For <bin m> = <im u> To <im cui> [Step <bc nhy>] <khi lnh> Next [<bin m>]

61

Sch Lp trnh Excel bng VBA

Bin m, im u, im cui, bc nhy l nhng gi tr s. Bc nhy c th l gi tr dng (tng) hoc m (gim). Nu Step khng c ch nh ra, mc nh bc nhy l 1. V d 1: Khng dng Step
Sub VD_ForNext() For i = 1 To 5 Cells(10, i) = i MsgBox i Next End Sub

V d 2: Dng Step
Sub VD_ForNext_Step() For i = 1 To 7 Step 2 Cells(12, i) = i MsgBox i Next End Sub

Trong v d ny, gi tr i tng tng bc 1, 3, 5, 7. 11.6. For Each ... Next Tng t nh vng lp For ... Next, nhng n lp khi lnh theo s phn t ca mt tp hp i tng hay mt mng, thay v theo s ln lp xc nh. Vng lp ny rt tin li khi ta cha bit chnh xc bao nhiu phn t trong tp hp. For Each <phn t> In <nhm> <khi lnh> Next <phn t> xc nh tn v s lng sheet trong workbook th bn dng th tc sau:
Sub ShowWorkSheets() Dim mySheet As Worksheet Dim i As Integer : i = 1 For Each mySheet In Worksheets MsgBox mySheet.Name i=i+1

62

Sch Lp trnh Excel bng VBA

Next mySheet MsgBox "So sheet trong workbook la " & i End Sub

11.7. Lnh thot (Exit) Trong mt s trng hp, bn c th thot khi cng vic no khi tho mn yu cu cng vic. Bn c th s dng th tc Exit nh Exit Do (thot khi vng lp Do ... Loop), Exit For (thot khi vng For ... Next), Exit Function (thot khi hm), Exit Sub (thot khi chng trnh), Exit Property (thot khi thuc tnh ang lm vic). V d:
Sub ExitStatementDemo() Dim I, MyNum Do ' t vng lp Do Loop For I = 1 To 1000 ' Lp 1000 ln MyNum = Int(Rnd * 1000) ' To s nguyn ngu nhin Select Case MyNum ' Tnh ton vi s nguyn trn Case 7: Exit For ' Nu l 7, thot khi For...Next Case 29: Exit Do ' Nu l 29, thot khi Do...Loop Case 54: Exit Sub ' Nu l 54, thot khi vng Sub End Select Next I Loop End Sub

11.8. Vng lp lng Vng lp c th c lng vo nhau. ng dng ny rt c hiu qu khi bn tnh ton vi mng hay i vi bng tnh nhiu chiu. V d:
SubCellsExample() For i = 1 To 5 For j = 1 To 5 Cells(i, j) = "Row " & i & " Col " & j Next j Next i End Sub

63

Sch Lp trnh Excel bng VBA

Kt qu th hin hnh v di y:

Hnh 44: Sn phm to ra khi dng vng lp lng.

64