This is an old revision of the document!
Eine Funktion die anhand der VarTypes versucht ein Wert zu casten.
Diese Funktion ist nicht für Objekte geeignet.
boolean = cast(vbVarType, value [,Strong])
Public Function cast( _ ByVal iType As VbVarType, _ ByVal iVar As Variant, _ Optional ByVal iStrong As Boolean = False _ ) As Variant
Für die Ausgabe der Resultate verwendete ich die Funktion [VBA] print_r()
d cast(vbInteger, "123.45") <Integer> 123 'Versuch misslungen. Der Originalwert wird zurückgehen d cast(vbInteger, "ABC") <String> 'ABC' 'Dasselbe aber mit Strong d cast(vbInteger, "ABC", true) --> Verursacht einen Error 13 Type mismatch '0, leerer String, Empty und Null können zu Null oder Empty konvertiert werden d cast(vbNull, 0) <Null> d cast(vbEmpty, NULL) <Empty> 'Boolean sind ebenfalls möglich d cast(vbBoolean, 1) <Boolean> True 'Ein einzelner Wert in ein Array wandeln d cast(vbArray, 12) <Variant()> ( [0] => <Integer> 12 ) 'Ein Array in ein Array wandeln d cast(vbArray, array(11, 12)) <Variant()> ( [0] => <Integer> 11 [1] => <Integer> 12 ) 'cast() führt auch zusätzlich ein NZ() aus d cast(vbInteger, Null) <Integer> 0
Attribute VB_Name = "cast_cast" '------------------------------------------------------------------------------- 'File : cast_cast.bas ' Copyright mpl by ERB software ' All rights reserved ' http://wiki.yaslaw.info/dokuwiki/doku.php/vba/cast/cast 'Environment : VBA 2010 + 'Version : 1.0.0 'Name : cast 'Author : Stefan Erb (ERS) 'History : 15.09.2014 - ERS - Creation '------------------------------------------------------------------------------- Option Explicit '/** ' * Wandelt einen String wenn möglich in das angegebene Format um ' * @param VbVarType ' * @param Variant ' * @param Boolean : Bei True wird ein Fehler greworfen, wenn der cast1() nichtr durchfürbar ist. Ansonsten wir der Eingabewert zurückgegeben ' * @return Variant ' */ Public Function cast(ByVal iType As VbVarType, ByVal iVar As Variant, Optional ByVal iStrong As Boolean = False) As Variant On Error GoTo Err_Handler cast = iVar Select Case iType Case vbNull, vbEmpty If Not (iVar = Empty Or IsNull(iVar)) Then Err.Raise 13 'Type mismatch cast = Choose(iType + 1, Empty, Null) Case vbArray: cast = IIf(IsArray(iVar), iVar, Array(iVar)) Case vbBoolean: cast = CBool(Nz(iVar)) Case vbDate: cast = CDate(Nz(iVar)) Case vbInteger: cast = CInt(Nz(iVar)) Case vbLong: cast = CLng(Nz(iVar)) Case vbDouble: cast = CDbl(Nz(iVar)) Case vbDecimal: cast = CDec(Nz(iVar)) Case vbByte: cast = CByte(Nz(iVar)) Case vbSingle: cast = CSng(Nz(iVar)) Case vbCurrency: cast = CCur(Nz(iVar)) Case Else: cast = CVar(Nz(iVar)) End Select Exit_Hanlder: Exit Function Err_Handler: If iStrong Then Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext cast = iVar End Function