Download as pdf
Download as pdf
You are on page 1of 9
erszois begin - Balding an OPC cllert in Excel - Code Review Stack Exchange Code Review Stack Exchange is @ question and answer ee fr peer programmer code reviews. I's 100% fee, no registration required Building an OPC client in Excel | am pretty deep into bulng avery multfaceted lite ap in Excel with VBA. It does a numberof task, all centered around using OPC to gel tag values fram several PLC's and doing various things with the info, Ike pushing @ webpage (using a module | found, not mine) reaing log fles and tables and sounding some audible alarms fr the ofce ‘What fm doing now is, upon a button push, connecting tothe server (RSLirx), then entering alop that fist reads the tag values, then does, each ofthe aove tasks f the associated checkbox is checked. Ths will fine indefintely so lng as the user doesnt screw witht or Lio et the computer lock | ama beginner coder so, please give me some feedback on the code tse, bu what Im realy trying to do is make this bulletproof, that, itwilrun witout fal. ve added some things ike on a selectionchange event, if youre connected, give a messagebox that says not lo make changes wile running. But, know tis can be mach beter. ‘Also, | aeady know thi might be done beter in various other ways, but this is aie beginner pet project forme and tm going to see it through before | move on, Allens is welcome. option explictt "vartonLes uct be declares fption gave 1. aeray start ot inden 3 Thonerens() as wetten Din Renintveal as Oke. sth 2c. comet febagevent "ORC = 0% Connect)" Statusnuate (conmecting =") (ntrvorcofo Error. OpCannectionfaiture Din tas Interer bis a8 Ince odulet Siveethsetine() = Falee Gephiane = cei15(5, 2) ‘esta ipeste (eng Tape Te hor Tstmpty(olls(4 6 p &).valve) Than neste 6,2) 16 Hot Thlshorkbok.cecServert te Nothing Then ‘sofety Extn Tnwortbooc OCServertconect(CeTs(4, 2) ‘Soe ecaroupt = Tistorkbok.PCServerd.oPCérovps. adit) “odd the grove cain morcitone(nterofags) For 1 = 1.79 naberorvaes (trv cote Feros faghatFoune 1 celistt + 4, 8) 2 Then ou tagrave > Cells(4'¢ 4) & 7 COLDS = 4, 5) 812,00" Set hyberters(S) = OFCiraisoPcteens aditen(Ceis(@ + £2) 4°." 8 Celis(e se genid's row trate = cetle(e + 4, 8) a *Uyer Sev oervna(i) = Orcaraiptopcttees Adtten(Cels(4 + 4, 4) & 48.08%, 4) ipuicaereview stackexchange comiquestons/7S348buling-an-ope-clent-n-excal 1 erszois begin - Balding an OPC cllert in Excel - Code Review Stack Exchange eat apeate ("eanectes") thecbeay (3) ero, Opctanneconfat le! send of Connect su ogden (comecsion Fate ensure atine it Rnring =) rror_Taghstfean fo (otrecton Fated, Cec tgs“ viking & vii ron ta rate) sup o2e.ossconecet) ebugevert "09 02 Disconnect)” (El Tssaorcbon.omcservert.oPcereup.Rerovehl “free all the teens ond groupe nL Tsnorsneat.opeservrd.aeeeannes ‘escomect fron the BC Server Set Toeaorbbookfeserverl = hathing Thtshorsoook. OP StopReadoo = Troe Statuswosate ("ot Conectes") Sub 02 petrasnserver() deren aR = OF etree)” fsestel5y sib 2€, nese) sebugevet “OFC - 02¢_Reae()™ Status peste (easing tage") Bin Serartandies) As Lone Iadin servertandes(QunberofTags) “Stew 1D (cerver sae) Dis Values() As variant retue wots, Din Erors(} A Lone hese next te ore different. They are vertané arrays, not arrays of type varkant. Bin a A rant eo uneg but mnt prove for function elt 1 Tisortbooko%servert Ie Nothing hen ‘sefety Tf Shets("Setua")nutoeconrect-Chevalue = Te Then 1 Not (Thsslorkboe.oPCSerers Servenstate = OPServerstate.oPCRunning) Then ‘se Servananies(s) = yorCiten(4) Serveranale cal ovceraupl Syneteseloncsehe, MumerorTagt, Serventanles, Value, S260, isl, irae) ipuicaereview stackexchange comiquestons/7S348buling-an-ope-clent-n-excal erszois begin - Balding an OPC cllert in Excel - Code Review Stack Exchange For 1 = te muberoftegs eetus(e et 3) = values(4) Eelisfe + £) 2) 2 Mnevatue(s) roe the enory ste valuer) rare Errore Sogion ("Tog Read Cor.” & vBleLine & "Pease recomect to server") sib cesta) seougevent "09C = 2¢ HrtteQ" Dis Servertandies(e) As Long ‘iter 10 (server sie) Din Vatues(6) As Vertont values Dis Eorors() Ae Lone 16 thiorttookcservers i Nothing Thon “safety 1 Not_(ThSslorkbox.OPCSererd Serverstate = OPServerstate.oRCRunning) Then ‘safety Stevertnales(4) = yorcteens(4) Serventnale sch the wotuns fron the ceLls anves(i = felis» 5, 3) se values) = Then values)» 8 cal ovearauph syncurste(e,Servertanales, values, Errors) ne Sb sib Reaoer ctsex() ebugevent "09 Renda see)" sub 2¢,Loapeend() cobugevent “09 07a Feastnerval = sheeis("Setp")-Range("35") Donnie TaLsnirkoeat-oFc stopheed.ocp = False opiicetin. Carson = litousebinter xbefault atsspdete Cheetos) utd (nh Oe) . “0 “ine peay (Besetoteral) 1 sheets('Seop")sodtbe_alarns_eable chbxvalue » eve Then States ante ('souncltg Aras") Sheets audsb2e Alsen") -Leptaeibtetrns Stotus palate Coane Sounding Mares") AV Sheets"setup")ewtogton chtxvale = true Then ese (Seap) onan rr Sf shoess"Setup") bette plssh_enale_CokBxvaie = True Then ‘Seats paate Covblishing") Stet pdate one Pubtishin) Ah Sheets(Setup")Logoata_chdn.value © Tee Then status paste (saving tog ile") egnata ng Rete (Bane Svig ag #8") fed 16 ipuicaereview stackexchange comiquestons/7S348buling-an-ope-clent-n-excal erszois begin - Balding an OPC cllert in Excel - Code Review Stack Exchange Tusorkteok. OP, stopheados = Fase 1 Thstorttookecservers Bs Nothing Then ‘sfety 1 peer(s) astotetrect casi = Tr then Private sub oF, conecttn Aish) ebugevent “OPC = 0>¢ Connctatn cite)" Looptead Sub 2¢_bisconnecben tek() cba re «0 sicomecttn ie” ne 5 1b 0¢_Reae_once_ fer £14CK0) steven HE «OC once tn eaten" sub status_uncate(seatus string) obugvert "Oe = status spate” statue 8 fennsga, 2) = sates Sab 02€,neaeonce(y sebugevet “OFC - 02¢ Resconeet)” Tiseelay (2) Stalus-vouate ("Opated Tag Values Secessfully") Private Sub sorkshect Selectionange(OWal Target As Excel. fangs) User input for tine tntervel for sein Loop 14 (ot dntersect( Target, ange(c5:6008")) Tx Nothing) Or (Got sveersectrargre, ange("A{:bs")) 16 noting) Then 1 rateoriocoeconracted = True Then Msahox (Please disconnect Deron changing any setings.°) etd ee 1214 0 423 eked Dee 014 a 1798 pean 3) 76 8 Ber" migrated from stackovertow.com Dec 1114 at 16:35 “This question came rom our sto frpotessional and enthusiast programmes. Hi Welcome to Coe Reviow Youve spit out ala of acronym at vs. Could you extn what an OPC and Plcis?= RuBbeduck Owe 114 at 1721 Using Googe Fue was abe Prorarimable Logis Cota etemine OPC le OLE for Process Control and PLC appears tobe 3 Phare Dae 14 at 17.98 ‘Seems ike Cody Is bldng@ SCADA system. — Mad Dec 124 32123, ipuicaereview stackexchange comiquestons/7S348buling-an-ope-clent-n-excal erszois begin - Balding an OPC cllert in Excel - Code Review Stack Exchange Basicaly yes. ts eating data tom programmable loge carole thal contd chet. use ths 10 ult epors, istorcal rears, webpages end send them via em peredcaly. ary. took a whl for tho response. Im gorg i part ths to python. Some new les have ust boon wrton hat wil make is ons times easter an mow power. Thanks forthe Palp.~ Cody Lary Dee 301 at 458 3 Answers. ‘There's no such thing as bullet proof code. I's a mythical ogend, a unicorn. We can (and shoul) certainly try though. The fst step to dong tha is writing extremely legible and understandable code, Youve done a petty good joo of tat, bu there's Some room for improvement Readability Use of Whitespace and Comments Itseems tke a sity thing o pick on, butt realy does matter. Consider this snippet fom your ‘code. It does some things right, butt looks messy. Ee ae sty (cele » 6)-vaus) Then 1 Rot TistorabooomCServers Ts Nothing Men “safety ait thiaorthonssoncanevertscnmeet(Cetis(4, 29) connect £9 the O% corps. tte(ertane) ‘284 oho group ebm moPcrtens(MaberorTogs) tn ror cate rar Taphttound BF eeege'e tse) 3 then The indentation e good, but you seem to arbitrary use new ines. Sometimes no emply Ine ‘sometimes one, sometimes two, It makes for hara to read code. Hara to read code is hard to rmainain code. Hard to maintain code will have bugs. “The other thing going on here isthe right algned” comments. Which, 28 you can see, aerit right aligned arymare the second you cony paste them anywhere ese. rm okay with end of ine comments if they're short and helpful, but forge ying to algn them. Its awaste of te. they state the obvous, remove them. Ifthey are more than a word or two, move them tothe Ine before. ge ey cette», reenter (air Thstortnoneocateverssconnees(@11s¢4, 2)) st ecaroupl ~ Thstorebook.ocseevert.OPcéroups. arpa) ebm myorcltens(unberoFrgs) Scoping (kind off ipuicaereview stackexchange comiquestons/7S348buling-an-ope-clent-n-excal erszois begin - Balding an OPC cllert in Excel - Code Review Stack Exchange ‘This nota scoping iesue with your code per se, but stil a readabily issue, Din witntvets crap ne orp Din myonestonst) as ontleen Din Renlotreel ao Owe Dont use oie at the module kvel. Use ersvate. Yes, they both do the same hing, but sing Private 8 vsialndiation that these variables belong to the module scope, You should also explicitly declare the scope of your Subs & Functions. Everything is public by defaut, but find it much nice to say 80. (Particularly since in VE.Net, everything is private by detaul makes fortes confusion When swiching between te languages.) So sub >< comact Should be ute suo oF. omreceQ) or Private Su oP. connest) Probably the latter. As a rue of thumb, declare everyting private unt you prove a need to callit from ouside the eUrtent module or class in { Ae anteper Din g As integer Din bas anteper Here youre declaring 3 diferent counter variables and using them ance, Dont dati. cht. Justre-use the + variable as a counter for each loop. The eye wil instay recognize tas a loop counter. Or even beter, extract some methods s0 you don' have fo stress about re-using variables. (Il come back to that na bit) That was also more ofa readabity issue, but his “scoping” issue isa seriously dangerous thing | can nat think of a single situation where | ever shoua have legitimately called just plain old ‘fetch the values fromthe coz Venues" Cettsee + 4, 3) 1 vauescap values) = 6 cents the way you nave used ithere is equivalent to caling activeshes. cents. Almost never should we be working wit the acve sheet because the user can change i on us while he code is executing. Avoid activate and select by explicitly seling a variable to te range you wart to work vt The same goes for sneets This code 1¥ shoets("Setup) audible alarns_enale_cnbevalue + Tre Than Is equivalent to caling t:siorxtook-shets¢“Setp"). Ifthe user clicks on another workbook, "your code going fo blow up because itcant the Setup” worksheet Naming Names should not have underscores in hem unless they are an event procedure. The Underscore nods this special meaning in VBA. iis not an event procedure, ust dont do's confusing. Paticlary when you're making use of wishEvents (Kudos for that by the way. doit ‘6 many programmers take advantage ofthat) Remove Dead Code ipuicaereview stackexchange comiquestons/7S348buling-an-ope-clent-n-excal erszois begin - Balding an OPC cllert in Excel - Code Review Stack Exchange Dead code schiter. Theres dead commented out code al over the place, Sun iti, I Yyoulte wotled about needing that code agaln | hghYy recommend that you stat using source control | wrote a blog about using Gt with VBA that should get you started, Single Responsiblity You've done an okay job of using subvoutines, but you could do better. Remember those alphabetic counters? Extract them into wel named subroutines and call hem from your *maln* routine, Private sub NothureshatThisActusl yoo) Podulet Sivoethsetine(n) = Falee ‘A.corner stone of "ult proof code is that you can easily grok an entire routine atone tne. Its offen referred to asthe single responsibilty principle. Each rain or function should have one {and only one job. Another way of thinking about iis the "Single Sereen Principle’. I should never have to serallto see more ofa routine. Ihave fo Scrol then the routine is most certainly breaking the SRP ‘Sidenote: Speaking of "caling” routines, dont actually use the cst3. Keyword. Its archaic and ‘only availabe for back wara compatibiry reasons, Here areal good example ofan opportunty to extract a method, The comment's a dead give away (and a good start ona good name) Servestnales(s) = RyOPCItens(s)-Servertndte Other things “ree the svory Ea valueed), rae FrroreO Its nice that you're cleaning up ater yourself, but! seriously don't understand why youire doing this. These arrays are locally scoped. Once they go out of scope the reference count wil decrement to zero and the memory wil be reclame 1 Okay. think thats enoug for naw [eal ecommond an iterate rviw ants one. Ther alo of de, an honesty dirt ge ery dep ino Ise funcional. Tul closn kup 9 mue™ as you en, and then come back to ost a alow up question coring the now cose. — Rbk Dee 12 1 a 590, Options Kudos for option explicit = requing variable declaration i the very fst step toward witing clean VBA code. It shoul need a comment though: comments shoud say why, nol what- any \VBA programmer looking at an option statement wil know what its for. And those wih dori, can Google it option ‘Same thing here, the comment basicaly explains wha the statement does. Be careful with ipuicaereview stackexchange comiquestons/7S348buling-an-ope-clent-n-excal 79 erszois begin - Balding an OPC cllert in Excel - Code Review Stack Exchange optien base though, a5 tends to make things confusing - arrays are known to stat at index 0 and collections at index 1. Using option sase encourages lazy aay declaratons - a better practice sta always speciy Both the lower and the upper bounds of an array, ard to use sound and ussuna when iterating one. Shortly put, lconsider oprion sare 1 a code smell by isl Naming ‘The VBA naming guidelines recommend rascaicase for everything except perhaps constants, which waud be vticase . Regardless of whether or not you follow thase guidelines, what matters the most is consistency. Here are my wn guidlines: + pancalcase for procedures (sub . functor, Praerty ), module names (neluding clas ames), and in general, any publ identifier. + caneicexe fr parameters local varlabes and private les. Now VBA is not case-sensitive, so appropriate and meaningful naming is crucial, otherwise you wil constant be fighting you IDE ‘Speaking of meaningful names: in i as anteger ‘Abettername for + could be currererag. Well. & is indeed commonly used 2s a loop counter, butin & procedure thathas 3 of tem, i's better to give them a meaningful name. Ee Noe Tatopty(Cells(4 +, #).valee) Then A better name for could be cureerthow adsl: suvedthistineth) = False This one i totaly eryple. One cannot infer the meaning of nor wy thas tobe Heated from 1 107. Also, savestnistine(s) looks Ike its a pub field (wel, an array) defined ina standard ‘module -in ater words, 8 global variable that could just as wellbe refered to as Savecrnatiea(n) withoul the roguie: qualfer..and rodsie: ist a use'u name ether Dsmywing That's ight: semvoweling. crane has no eason not tobe called crauskare : about 20% of programming canssis in wnting code. The oer 80% 's spent reading code - might as well make Itwort the whi, Error Handling Error peconneetonfatue Deaion (ecomection Fates" K vNeaLine A vahestine & eRecK Your server mane ane ensure RSLine is Rrne*) rror_fagotfoun sgBon ("Comeccion Faliee, Check tag: * & vohewLine & viedLine & rom tag.nane) ‘The only iference between these two subroutines, is the string theyre passing to the message box. ipuicaereview stackexchange comiquestons/7S348buling-an-ope-clent-n-excal erszois begin - Balding an OPC cllert in Excel - Code Review Stack Exchange ‘A procedure should only have exactly 1 o1 erear cate statement, and exactly 1 eror-handing subroutine Take sub o%comect() catching an err because a connection failed, and another because a fag was not found, sels: there should be a procedure responsible for connecting, and another for finding tags. Instead, on eer 1 Errandlen oF 85 11K to Puli, on foror Gets clesnet ubtte sub Foot) belt ub Now. this omc comect procedure handles both cases by displaying @ message box; believe in this ease, knowing exactly what to do with an eror shouldbe the responsibilty ofthe caltng code ‘what the handler can do, s make that error as informative as possible, by rasing the same eror umber, with new source’ and sescption vals. answer Doe 12°14 a 400 ait. “Tarn on fr alts easback. I's Invaluable My language i python are tm going to iplemer ts poject here since sme new excel leas have st bean developed that willbe prec. (Cody Landry Des 3014 £36 ‘Awesome, his site neds more Pinon reviewers Weleome 1 Cole Review! ~ Mats Mug Ose 90°14 at Its too hard to understand what I galng on without being able to See the ful cade 80 ean ony advise based on what you have shared, Here are some things to consider: ityouwte casts, 2) that means Activesree.celis(4, 2), Solfyouhave more sheets and luser changes the active sheet-> another value > ener. Same with sheets¢) bud not such crea as cells()/Rarget) ‘You can freeze Excel whe a macrois executing; see how You can add an ertor handle to every axtson_cisex (Ul event handler ke ‘0nc_pisconnectai, lick) ).IRWOURY mate” Whats actualy going wrong by ary user action that stats a macro, you have the control over what the user wil ee. cited Dee 19°14 2 16:50 srewered Doe 9°14 1807 3350 Meehow | ipuicaereview stackexchange comiquestons/7S348buling-an-ope-clent-n-excal

You might also like