TypeOf of TypeName

Status
Niet open voor verdere reacties.

masala09

Gebruiker
Lid geworden
6 aug 2012
Berichten
886
Nu wel een vraag.

Wanneer gebruik je TypeOf en wanneer TypeName

Visueel gezien doen beide hetzelfde.

Code:
For Each ctrl in Me.Controls
If TypeOf ctrl is MSForms.TextBox then

...................
..........

Next ctrl

For Each ctrl in Me.Controls
If TypeName(ctrl) = "TextBox" then

..................
...........

Next ctrl
 
Laatst bewerkt:
- TypeOf can only be used on objects. TypeName can be used on objects and literals.
- TypeOf will return a runtime error if the object variable is nothing. TypeName will return the string "Nothing".
- TypeOf returns a boolean result. TypeName returns a string result.
- TypeOf is faster than TypeName.
- TypeOf returns true for a given type if the object inherits from that given type, as demonstrated in example code below. A common situation in Excel VBA where it's important to understand this feature is when you're using TypeOf to identify MSForms library controls (checkbox, option button, toggle button).

http://www.mrexcel.com/forum/excel-...ations-difference-between-type-type-name.html
 
Laatst bewerkt:
Avond Edmoor,

Dank voor je bericht. Dit stukje ken ik al, maar dan nog snap ik het niet.

Wanneer of in welke situatie gebruik je welke. Ik zie namelijk geen verschil terwijl deze er wel zou moeten zijn.
 
Zoals Edmoor hierboven al aangaf, kleine verschillen.
Typeof gebruik je dus in een If-structuur, Typename kan ook in een select case structuur.
Bij TypeOf kun je op meerdere objecten testen: (voorbeeldje is wat onzinnig)

Code:
For Each ctrl In Me.Controls
    If TypeOf ctrl Is Object  Then MsgBox "object"
    If TypeOf ctrl Is msforms.Control Then MsgBox "control"
    If TypeOf ctrl Is msforms.TextBox Then MsgBox "textbox"
Next

Uiteindelijk gebruik je wat je zelf het prettig vindt, overigens wel de punt tussen ms & forms weghalen;)
 
Status
Niet open voor verdere reacties.
Steun Ons

Nieuwste berichten

Terug
Bovenaan Onderaan