文字列の文字数や変数を記憶するために必要なバイト数を、長整数型 (Long) で返します。
構文
Len(string* | *varname)
Len 関数の引数は次のとおりです。
| 引数 | 説明 |
|---|---|
| string | 任意の有効な文字列式。 string に Null が含まれている場合は、Null が返されます。 |
| varname | 任意の有効な変数名。 varname に Null が含まれている場合、Null が返されます。 varname が Variant の場合、Len は文字列と同じように扱い、含まれる文字数を常に返します。 |
解説
使用できる 2 つの引数のうちどちらか 1 つだけを常に、指定する必要があります。 ユーザー定義型では、Len はファイルに書き込まれるサイズを返します。
注
文字列に含まれるバイト データでは、2 バイト文字セット (DBCS) 言語のように、LenB 関数を使います。 LenB は、文字列の文字数を返すのではなく、その文字列を表すために使われるバイト数を返します。 ユーザー定義型では、LenB はメモリ内でのサイズを返し、要素間のスペースを含みます。 LenB を使うサンプル コードについては、例の 2 番目の例を参照してください。
注
Len は、ユーザー定義データ型の可変長文字列で使うと、実際に必要な記憶域バイト数を決定できないことがあります。
クエリの例
| Expression | 結果 |
|---|---|
| SELECT ProductID, Len(ProductID) AS ProductLen FROM ProductSales; | フィールド "ProductID" から値を返し、列 ProductLen 内の値の長さを返します。 |
VBA の例
注
次の例は、Visual Basic for Applications (VBA) モジュールでのこの関数の使用方法を示しています。 VBA の使用方法の詳細については、[検索] の横にあるドロップダウン リストで [開発者用リファレンス] を選び、検索ボックスに検索する用語を入力します。
1 番目の例では、Len を使って、変数の格納に必要な、文字列の文字数またはバイト数を返します。
Type...クラス モジュールに表示される場合は、CustomerRecordを定義する End Type ブロックの前に キーワード (keyword) Private を指定する必要があります。 標準モジュールでは、Type ステートメントは Public でもかまいません。
Type CustomerRecord ' Define user-defined type.
ID As Integer ' Place this definition in a
Name As String * 10 ' standard module.
Address As String * 30
End Type
Dim Customer As CustomerRecord ' Declare variables.
Dim MyInt As Integer, MyCur As Currency
Dim MyString, MyLen
MyString = "Hello World" ' Initialize variable.
MyLen = Len(MyInt) ' Returns 2.
MyLen = Len(Customer) ' Returns 42.
MyLen = Len(MyString) ' Returns 11.
MyLen = Len(MyCur) ' Returns 8.
2 番目の例では、LenB とユーザー定義関数 LenMbcs を使って、文字列の表現に ANSI が使われている場合に、文字列のバイト文字数を返します。
Function LenMbcs (ByVal str as String)
LenMbcs = LenB(StrConv(str, vbFromUnicode))
End Function
Dim MyString, MyLen
MyString = "ABc"
' Where "A" and "B" are DBCS and "c" is SBCS.
MyLen = Len(MyString)
' Returns 3 - 3 characters in the string.
MyLen = LenB(MyString)
' Returns 6 - 6 bytes used for Unicode.
MyLen = LenMbcs(MyString)
' Returns 5 - 5 bytes used for ANSI.