Len 函數

套用到
Microsoft 365 Access Access 2024 Access 2021 Access 2019 Access 2016

會傳回一個 Long,其中包含一個字串中的字元數或儲存一個變數所需的位元組數。

語法

倫 (弦* |*變名)

Len 函數語法包含以下參數:

引數 描述
string 任何有效的字串表達式。 若 字串 包含 Null,則回傳 Null。
瓦爾納姆 任何有效的變數名稱。 若 varname 包含 Null,則回傳 Null。 若 varname 是變體, Len 將其視為字 ,且總是回傳其包含的字元數。

註解

必須指定兩個可能論點中的一個 (,且僅) 一個。 使用使用者定義型別時, Len 會回傳將寫入檔案的大小。

注意

使用 LenB 函式,並使用包含字串中的位元組資料,如 DBCS) 語言 (雙位元組字元集。 LenB 不會回傳字串中的字元數,而是回傳用來表示該字串的位元組數。 使用使用者定義型別時, LenB 會回傳記憶體大小,包括元素間的任何填充。 關於使用 LenB 的範例程式碼,請參考範例主題中的第二個範例。

注意

Len 可能無法確定在使用者定義資料型別中,使用變長字串時所需的實際儲存位元組數。

查詢範例

運算式 結果
SELECT ProductID,Len (ProductID) ProductLen 來自 ProductSales; 回傳「ProductID」欄位的值及欄位 ProductLen 中這些值的長度。

VBA 範例

注意

下列範例示範如何在 Visual Basic for Applications (VBA) 模組中使用此函數。 如需使用 VBA 的詳細資訊,請在 [搜尋] 旁的下拉式清單中選取 [開發人員參考],並在 [搜尋] 方塊中輸入一個或多個字詞。

第一個範例使用 Len 來回傳字串中的字元數或儲存變數所需的位元組數。 那 種......如果 End Type 區塊 CustomerRecord 在類別模組中出現,定義前必須加上關鍵字 Private 。 在標準模組中, 型態 陳述式可以是 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.

第二個範例使用 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.

字串函數及其使用方法