Office.VBA-VB基礎文檔整理

爲了教女票自動化,通讀了vb部分的文檔,下次估計會更新vba excel部分git

1. 準備

如下操做由筆者均在 win10 + ms office excel 2013環境中實踐。數據庫

1.1 配置環境

■開啓Excel宏選項express

文件>選項>自定義功能區>開發工具windows

■更友好的編輯設置數組

  • 開發工具> Visual Basic >工具>選項>緩存

    • 編輯器>取消勾選【自動語法檢測】,勾選【要求變量聲明】
    • 編輯器格式>字體>Consolas(西方)
    • 編輯器格式>字體>>大小>11

■保存時彈出沒法刪除我的信息的警告框app

  • 文件>選項>信任中心>信任中心設置>我的信息選項>less

    • 取消勾選【保存時從文件屬性中刪除我的信息】

■強制聲明全部變量dom

  • 代碼頭部加 Option Explicit

2. VB語言基礎

2.1 數據類型

■ 數據類型速查ssh

縮寫 類型 中文解釋 匈牙利命名示例
Boolean 布爾型 bHidden = True
Byte 字節型 (0~255) byArrIndex=255
% Integer 短整型(-32768~32767) nArrLen=999
& Long 長整型(-2147483648~2147483647) lCounter=0
! Single 單精度浮點型 fStep=1.2
# Double 雙精度浮點型 dScore=3.4
$ String 字符型 sName="sheet1"
@ Currenccy 貨幣型
Decimal 小數型
Date 日期型
Object 對象
Variant 變體
用戶自定義 用戶自定義類型

筆者其餘匈牙利命名推薦

縮寫 類型
src 源對象 
dest 目的對象 
a 數組
objApp 對象
xlApp Excel對象
wbk WorkBook工做簿
ws Worksheet工做表
r Range表範圍

■ 合法變量名

  • 字母開頭
  • 只能是字母|數字|下劃線
  • 不超過255
  • 不區分大小寫

■ 聲明、賦值

  • DimStatic只能在過程(Sub或者Function)內部被訪問
  • Static下次再調用該過程的時候,數據就依然存在
Dim sText As String'聲明變量
Dim sText$ '聲明變量(縮寫)
Const c_nCounter As Integer '常量
Static s_fPi As Single '靜態變量
  • Private 這個模塊才能訪問
  • Public 整個應用程序都能使用
Private m_lCounter As Long '私有變量
Public g_byArrIndex As Byte '公有變量
  • 變量、對象賦值
Let lMax = 3000 '變量賦值
lMax = 3000 '變量賦值,可省略Let
Set wsTest = ActiveSheet '對象賦值

■ 數組 的 聲明、賦值

  • 聲明

    • Dim arr(1 To 100) As Byte 表示 arr=[1,2,...,99,100]
    • Dim arr(99) As Byte 表示 arr=[0,1,...,98,99]
    • Dim arr(1 To 3, 1 To 2) As Integer 形如 [[x,x],[x,x],[x,x]]
  • 賦值

    • arr(1)=1
    • Range("E1:G3").value=arr
    • arr=Range("E1:G3").value
  • 動態長度聲明

    Dim nLen%
    'nLen = A列非空單元格數
    nLen=Application.WorksheetFunction.CountA(Range("A:A"))
    Dim aColA(1 To nLen) As String
  • 動態類型聲明

    Dim aHeader As Variant
    arr = Array("序號",3.14,Date)

2.2 過程、函數

■ 過程

  • Private Sub object
Public Sub xxx()
    Dim title$'縮寫示例
    title="hello word"
    MsgBox(title)
End Sub

■ 函數

Public Function weekCheck(str as String)

End Function
  • 數組操做

    • 分隔字符串到數組 arr=Split("趙,錢,孫,李",",")
    • 合併數組到字符串 txt=Join(arr,",")
    • 獲取數組最小索引 LBound(arr)
    • 獲取數組最大索引 UBound(arr)
  • 類型轉換
  • Chr

2.2運算符

■ 算數運算符

算數運算符 描述 示例
+ A + B
- A - B
* A * B
/ B / A
\ 除商 B A
Mod 除餘 B Mod A
^ 指數 B ^ A

■ 邏輯運算符

邏輯運算符 描述 示例
= 等於 A = B
<> 不等 A <> B
< 小於 A < B
> 大於 B > A
<= 小於等於 B <= A
>= 大於等於 B >= A
Is 指數 Object Is Object
Like 指數 String Like String

■ 邏輯運算符

假設變量A=10,變量B=0

邏輯運算符 示例 結果
AND A<>0 AND B<>0 False
OR A<>0 OR B<>0 True
NOT NOT(a<>0 OR b<>0) False
XOR (a<>0 XOR b<>0) True

■ 鏈接運算符

假設變量A=5,變量B=10

鏈接運算符 描述 示例
+ 鏈接兩個值 A + B
& 鏈接兩個值 A & B

■ 通配符

通配符 描述 示例
* 任意多個字符 "ab4" Like "a*"
? 任意的單個字符 "ab4" Like "a??"
# 任意的單個數字 "ab4" Like "ab#"
[charlist] charlist的任意一個字符 "a" like "[a-z]"
[!charlist] 不在charlist的任意一個字符 "a" like "[!h-x]"

文檔

活動事件

Private Sub object _Activate

激活

Private Sub UserForm_Activate()
    UserForm1.Caption = "Click my client area"
End Sub

Private Sub object _Deactivate

停用

Private Sub UserForm_Deactivate()
    UserForm1.Caption = "I just lost the focus!"
End Sub

Private Sub object _Initialize

在加載對象後、但在其顯示以前出現。

Private Sub UserForm_Initialize()
    Load UserForm2
    UserForm2.Show
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)

在UserForm關閉以前發生。

此事件通常用於確保應用程序所含的用戶窗體中在應用程序關閉前沒有未完成任務。

例如,若是用戶還沒有將新數據保存到任何 UserForm 中,則應用程序可能提示用戶保存數據。

應用程序關閉時,您可以使用 QueryClose 事件過程將 Cancel 屬性設置爲 True,以中止關閉過程。

CloseMode值:

常量 說明
vbFormControlMenu 0 用戶已經從UserForm控制菜單中選擇了關閉命令。
vbFormCode 1 Unload 語句是從代碼調用的。
vbAppWindows 2 當前 Windows 操做環境會話正在關閉。
vbAppTaskManager 3 Windows的任務管理器正在關閉應用程序。

示例

下面的代碼強制用戶單擊UserForm客戶端區域以將其關閉。 若是用戶嘗試使用標題欄中的關閉 框,則Cancel 參數將設置爲非零值,以防終止。 可是, 若是用戶單擊了 客戶端區域, 則CloseMode 的值爲 1且 Unload Me將執行。

Private Sub UserForm_Activate()
Me.Caption = "You must Click me to kill me!"
End Sub

Private Sub UserForm_Click()
Unload Me
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    '使用標題欄中的「關閉」框阻止用戶關閉。
    If CloseMode <> 1 Then Cancel = 1
    Me.Caption = "The Close box won't work! Click me!"
End Sub

Private Sub UserForm_Resize()

調整父窗體 的大小時, 使用Resize事件過程移動控件或調整其大小。 還可使用此事件過程從新計算變量或屬性。

示例
下面的示例使用**Activate**和**Click**事件來講明**UserForm_Resize**事件的觸發。 當用戶單擊窗體的客戶端區域時, 它會增大或縮小, 而且在標題欄中指定新的高度。 請注意, Tag 屬性用於存儲用戶窗體的初始高度。
' Activate event for UserForm1
Private Sub UserForm_Activate()
    UserForm1.Caption = "Click me to make me taller!"
    Tag = Height    ' Save the initial height.
End Sub

' Click event for UserForm1
Private Sub UserForm_Click()
    Dim NewHeight As Single
    NewHeight = Height
    ' If the form is small, make it tall.
    If NewHeight = Val(Tag) Then
        Height = Val(Tag) * 2
    Else
    ' If the form is tall, make it small.
        Height = Val(Tag)
    End If
End Sub

' Resize event for UserForm1
Private Sub UserForm_Resize()
    UserForm1.Caption = "New Height: " & Height & "  " & "Click to resize me!"
End Sub

Private Sub object _Terminate( )
在卸載對象後發生Terminate事件。 若是UserForm 或類的實例從內存中刪除, 則不會觸發Terminate事件, 由於應用程序異常終止。

例如, 若是應用程序在從內存中刪除類或UserForm 的全部現有實例以前調用End 語句, 則不會對該類或UserForm 觸發Terminate事件。

示例
如下事件過程致使UserForm 在用戶點擊客戶端區域以消除該窗體以後發出了幾秒中的嗶嗶聲。
<pre>
Private Sub UserForm_Activate()
UserForm1.Caption = "Click me to kill me!"
End Sub

Private Sub UserForm_Click()
Unload Me
End Sub

Private Sub UserForm_Terminate()

Dim Count As Integer
For Count = 1 To 100
    Beep
Next

End Sub
</pre>

VB函數

■ 轉換函數

Asc( string As String)

返回一個整數值,它表示與字符串中的第一個字母對應的字符代碼。若是 string 不包含任何字符,將會出現運行時錯誤。

示例

Dim MyNumber
MyNumber = Asc("A")    ' Returns 65.
MyNumber = Asc("a")    ' Returns 97.
MyNumber = Asc("Apple")    ' Returns 65.

Chr( charcode As String)

返回一個字符串,其中包含與指定的字符代碼關聯的字符。0–31 之間的數字與標準非打印 ASCII 代碼相同。 例如,Chr(10) 將返回換行符。 charcode 的正常範圍是 0–255。

示例

Dim MyChar
MyChar = Chr(65)    ' Returns A.
MyChar = Chr(97)    ' Returns a.
MyChar = Chr(62)    ' Returns >.
MyChar = Chr(37)    ' Returns %.

▌CVErr


[▌Format( Expression, [ Format ], [ FirstDayOfWeek ], [ FirstWeekOfYear ])](#format)

格式化的對象 具體操做
數字 使用預約義的指定數值格式或建立用戶定義的數值格式。
日期和時間 使用預約義的指定日期/時間格式或建立用戶定義的日期/時間格式。
日期和時間序列號 使用日期和時間格式或數值格式。
字符串 建立您本身的用戶定義的字符串格式。

Format 參數

參數 說明
Expression 必需。 任何有效的表達式。
Format 可選。 一個有效的指定格式表達式或用戶定義的格式表達式。
FirstDayOfWeek 可選。 一個指定一週的第一天的常量。
FirstWeekOfYear 可選。 一個指定一年的第一週的常量。

firstdayofweek 參數

參數 說明
vbSunday 1 週日(默認)
vbMonday 2 星期一
vbTuesday 3 星期二
vbWednesday 4 星期三
vbThursday 5 星期四
vbFriday 6 星期五
vbSaturday 7 星期六

firstweekofyear 參數

參數 說明
vbFirstJan1 1 從 1 月 1 日所在的周開始(默認)。
vbFirstFourDays 2 從一年中至少包含四天的第一週開始。
vbFirstFullWeek 3 從一年的第一個完整週開始。

日期符號

符號 範圍
d 1-31(月份中的某一日,不帶前導零)
dd 01-31(月份中的某一日,帶前導零)
w 1-7(星期幾,從星期日 = 1 開始)
ww 1-53(年份中的某一週,不帶前導零;第 1 周從 1 月 1 日開始)
m 1-12(年份中的某一月,不帶前導零;從 1 月 = 1 開始)
mm 01-12(年份中的某一月,帶前導零;從 1 月 = 01 開始)
mmm 顯示縮寫的月份名稱(Hijri 月份名稱沒有縮寫形式)
mmmm 顯示完整的月份名稱

y 1-366(年份中的某一天)
yy 00-99(年份的最後兩位數)
yyyy 100-9999(三位或四位數年份)

時間符號

符號 範圍
h 0-23(在 1-12 時附加「AM」或「PM」)(一天中的小時數,不帶前導零)
hh 00-23(在 01-12 時附加「AM」或「PM」)(一天中的小時數,帶前導零)
n 0-59(小時內的分鐘數,不帶前導零)
nn 00-59(小時內的分鐘數,帶前導零)
m 0-59(小時內的分鐘數,不帶前導零)。 僅在前面帶有 h 或 hh 時
mm 00-59(小時內的分鐘數,帶前導零)。 僅在前面帶有 h 或 hh 時
s 0-59(分鐘內的秒數,不帶前導零)
ss 00-59(分鐘內的秒數,帶前導零)

示例

Dim MyTime, MyDate, MyStr
MyTime = #17:04:23#
MyDate = #January 27, 1993#

' Returns current system time in the system-defined long time format.
MyStr = Format(Time, "Long Time")

' Returns current system date in the system-defined long date format.
MyStr = Format(Date, "Long Date")

MyStr = Format(MyTime, "h:m:s")    ' Returns "17:4:23".
MyStr = Format(MyTime, "hh:mm:ss am/pm")    ' Returns "05:04:23 pm".
MyStr = Format(MyTime, "hh:mm:ss AM/PM")    ' Returns "05:04:23 PM".
MyStr = Format(MyDate, "dddd, mmm d yyyy")    ' Returns "Wednesday, Jan 27 1993".
' If format is not supplied, a string is returned.
MyStr = Format(23)    ' Returns "23".

' User-defined formats.
MyStr = Format(5459.4, "##,##0.00")    ' Returns "5,459.40".
MyStr = Format(334.9, "###0.00")    ' Returns "334.90".
MyStr = Format(5, "0.00%")    ' Returns "500.00%".
MyStr = Format("HELLO", "<")    ' Returns "hello".
MyStr = Format("This is it", ">")    ' Returns "THIS IS IT".

更多...


Hex( number As Number|String) As String

返回表示數字的十六進制值的字符串。若是 number 不是整數, 則在計算以前將其舍入爲最接近的整數。
對於與十六進制相反的值, 請在十六進制值前面加上 &H。 例如,Hex(255)返回字符串 FF&HFF返回數字255

若是 number 爲 則 Hex 返回
-2,147,483,648 到 2,147,483,647 最多八個十六進制字符
NULL NULL
Empty (空) 零 (0)

示例

Dim MyHex
MyHex = Hex(5)    ' Returns 5.
MyHex = Hex(10)    ' Returns A.
MyHex = Hex(459)    ' Returns 1CB.

Oct( number As Number|String) As String

返回一個表示數字的八進制值的變量(字符串)。

若是 number 是 Oct 返回
NULL NULL
爲空 零 (0)
任何其餘數字 多達 11 個八進制字符

示例

Dim MyOct
MyOct = Oct(4)     ' Returns 4.
MyOct = Oct(8)    ' Returns 10.
MyOct = Oct(459)    ' Returns 713.

Str( number As Number) As String

返回數字的字符串表示。始終爲 number 的符號保留前導空格。

示例

Dim MyString
MyString = Str(459)    ' Returns " 459".
MyString = Str(-459.65)    ' Returns "-459.65".
MyString = Str(459.001)    ' Returns " 459.001".

▌Val( string As String) As Number

以適當類型的數值格式返回字符串中包含的數字。Val函數將在字符串沒法識別爲數字一部分的第一個字符處中止讀取該字符串。 將沒法識別一般被視爲數值的一部分的符號和字符(例如美圓符號和逗號)。可是, 函數識別基數前綴&O (用於八進制) 和&H (對於十六進制)。 空白、製表符和換行符將從參數中剔除。

示例

Val("    1615 198th Street N.E.") ' Returns 1615198
Val("&HFFFF") ' Returns -1
Dim MyValue
MyValue = Val("2457")    ' Returns 2457.
MyValue = Val(" 2 45 7")    ' Returns 2457.
MyValue = Val("24 and 57")    ' Returns 24.

■ 數學函數

▌Abs( number As Number) as Number

返回將傳遞給指定數字的絕對值的相同類型的值。

示例

Dim MyNumber
MyNumber = Abs(50.3)    ' Returns 50.3.
MyNumber = Abs(-50.3)    ' Returns 50.3.

▌Atn( number As Number) as Double
返回指定數字的餘切值的 Double。

示例

Dim IntVar, StrVar, DateVar, MyCheck
' Initialize variables.
IntVar = 459: StrVar = "Hello World": DateVar = #2/12/69# 
MyCheck = VarType(IntVar)    ' Returns 2.
MyCheck = VarType(DateVar)    ' Returns 7.
MyCheck = VarType(StrVar)    ' Returns 8.

▌Cos( number As Number) as Double
返回指定角的餘弦的 Double。

示例

Dim MyAngle, MySecant
MyAngle = 1.3    ' Define angle in radians.
MySecant = 1 / Cos(MyAngle)    ' Calculate secant.

▌派生的數學函數


▌Exp( number as Number) As Double

返回指定進行冪計算的e(天然對數的基)的 Double。

示例

Dim MyAngle, MyHSin
' Define angle in radians.
MyAngle = 1.3    
' Calculate hyperbolic sine.
MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2

**▌Int|Fix( number As Number)** as Integer

IntFix都刪除數字的小數部分,並返回結果整數值。IntFix之間的區別在於,若是number爲負,則Int返回小於或等於number的第一個負整數,而Fix返回大於或等於number的第一個負整數。例如,Int將-8.4轉換爲-9,而Fix將-8.4轉換爲-8。Fix(number)等於Sgn(number)* Int(Abs(number))

示例

Dim MyNumber
MyNumber = Int(99.8)    ' Returns 99.
MyNumber = Fix(99.2)    ' Returns 99.

MyNumber = Int(-99.8)    ' Returns -100.
MyNumber = Fix(-99.8)    ' Returns -99.

MyNumber = Int(-99.2)    ' Returns -100.
MyNumber = Fix(-99.2)    ' Returns -99.

Log(number As Number ) As Double

返回用於指定數字的天然對數的 Double 值。


[▌Rnd([ number As Number])](#rnd) As Single

返回一個包含僞隨機數字的Single 。

若是_Number_爲 則 Rnd 生成
小於 0 使用_number_做爲種子時, 每次使用相同的數字。
大於 0 僞隨機序列中的下一個號碼。
等於 0 最近生成的數字。
未提供 僞隨機序列中的下一個號碼。

示例

Dim MyValue As Integer
MyValue = Int((6 * Rnd) + 1)    ' Generate random value between 1 and 6.

▌Sgn(nubmer As Number) As Integer
返回數字的符號

示例

Dim MyVar1, MyVar2, MyVar3, MySign
MyVar1 = 12: MyVar2 = -2.4: MyVar3 = 0
MySign = Sgn(MyVar1)    ' Returns 1.
MySign = Sgn(MyVar2)    ' Returns -1.
MySign = Sgn(MyVar3)    ' Returns 0.

--

▌Sin(* number as Number) As Double

返回指定角的正弦值的 Double。


▌Sqr(* number as Number) As Double

返回指定一個數的平方根的 Double 。


Tan(* number as Number) As Double
返回一個指定角的正切值的 Double 。


■ 類型轉換函數

▌ CBool(expression):Boolean

將表達式轉換爲 Boolean。 若是該表達式計算結果爲非零值,則 CBool 將返回 True,不然,返回 False。

示例

Dim A, B, Check 
A = 5: B = 5 ' Initialize variables. 
Check = CBool(A = B) ' Check contains True. 
 
A = 0 ' Define variable. 
Check = CBool(A) ' Check contains False.

▌ CByte(expression):Byte

將表達式轉換爲 Byte。

示例

Dim MyDouble, MyByte 
MyDouble = 125.5678 ' MyDouble is a Double. 
MyByte = CByte(MyDouble) ' MyByte contains 126.

▌ CCur(expression):Currency

將表達式轉換爲 Currency。強制實行貨幣運算,根據您的計算機的區域設置恰當地識別不一樣的小數分隔符、不一樣的千位分隔符和不一樣的貨幣選項。一般可能發生單精度、雙精度或整數運算。

示例

Dim MyDouble, MyCurr 
MyDouble = 543.214588 ' MyDouble is a Double. 
MyCurr = CCur(MyDouble * 2) ' Convert result of MyDouble * 2 
 ' (1086.429176) to a 
 ' Currency (1086.4292).

▌ CDate(expression):Date

使用 IsDate 函數來肯定是否能夠將 date 轉換爲日期或時間。 CDate 識別日期文本和時間文本以及一些屬於可接受日期範圍的數字。 當轉換數字爲日期時,整個數字部分都將被轉換爲日期。 數字的任何小數部分都將被轉換爲一天的某個時間(從午夜開始)。

若是日、月和年的正確順序是以已識別日期設置以外的格式提供的,那麼則可能不能肯定日、月和年的正確順序。 此外,若是長日期格式還包含了星期幾字符串,則不能識別該格式。

示例

Dim MyDate, MyShortDate, MyTime, MyShortTime 
MyDate = "February 12, 1969" ' Define date. 
MyShortDate = CDate(MyDate) ' Convert to Date data type. 
 
MyTime = "4:35:47 PM" ' Define time. 
MyShortTime = CDate(MyTime) ' Convert to Date data type.

▌ CDbl(expression):Double

將表達式轉換爲 Double。

示例

Dim MyCurr, MyDouble 
MyCurr = CCur(234.456784) ' MyCurr is a Currency. 
MyDouble = CDbl(MyCurr * 8.2 * 0.01) ' Convert result to a Double.

▌ CDec(expression):Decimal

將數值轉換爲 Decimal。

示例

Dim MyDecimal, MyCurr 
MyCurr = 10000000.0587 ' MyCurr is a Currency. 
MyDecimal = CDec(MyCurr) ' MyDecimal is a Decimal.

▌CInt(expression):Integer

將值轉換爲 Integer。將其四捨五入爲最接近的數

示例

Dim MyDouble, MyInt 
MyDouble = 2345.5678 ' MyDouble is a Double. 
MyInt = CInt(MyDouble) ' MyInt contains 2346.

▌CLng(expression):Long

將值轉換爲 Long。將其四捨五入爲最接近的數

示例

Dim MyVal1, MyVal2, MyLong1, MyLong2 
MyVal1 = 25427.45: MyVal2 = 25427.55 ' MyVal1, MyVal2 are Doubles. 
MyLong1 = CLng(MyVal1) ' MyLong1 contains 25427. 
MyLong2 = CLng(MyVal2) ' MyLong2 contains 25428.

▌CSng(expression):Single

將值轉換爲 Single。

示例

Dim MyDouble1, MyDouble2, MySingle1, MySingle2 
' MyDouble1, MyDouble2 are Doubles. 
MyDouble1 = 75.3421115: MyDouble2 = 75.3421555 
MySingle1 = CSng(MyDouble1) ' MySingle1 contains 75.34211. 
MySingle2 = CSng(MyDouble2) ' MySingle2 contains 75.34216.

▌ CStr(expression):String

將數值轉換爲 String。

示例

Dim MyDouble, MyString 
MyDouble = 437.324 ' MyDouble is a Double. 
MyString = CStr(MyDouble) ' MyString contains "437.324".

▌ CVar(expression):Variant
將表達式轉換爲 Variant。

示例

Dim MyInt, MyVar 
MyInt = 4534 ' MyInt is an Integer. 
MyVar = CVar(MyInt & 000) ' MyVar contains the string 
 ' 4534000.

■ 其餘函數

[▌Array( ...arglist As Variant[] )](#array) as Array<Variant>

返回一個包含數組的 Variant。

示例

Dim MyWeek, MyDay
MyWeek = Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
' Return values assume lower bound set to 1 (using Option Base
' statement).
MyDay = MyWeek(2)    ' MyDay contains "Tue".
MyDay = MyWeek(4)    ' MyDay contains "Thu".

[▌CallByName( object, procname, calltype, [args()] )](#callbyname)
執行對象的方法,或者設置或返回對象的屬性。

參數 說明
object 必需: Object。 將對其執行函數的對象的名稱。
procname 必需: String。 包含對象的屬性或方法的名稱的字符串表達式。
calltype 必需:一個類型爲 vbCallType 的常量,它表示要調用的過程的類型。
args () 可選:Array

示例

CallByName Text1, "MousePointer", vbLet, vbCrosshair
Result = CallByName (Text1, "MousePointer", vbGet)
CallByName Text1, "Move", vbMethod, 100, 100
Option Explicit

Private Sub Form_Load()
    Label1.Caption = "Move"        ' Name of Move method.
End Sub

Private Sub Command1_Click()
    If Command1.Left <> 0 Then
        CallByName Command1, Label1.Caption, vbMethod, 0, 0
    Else
        CallByName Command1, Label1.Caption, vbMethod, 500, 500
    End If

[▌Choose( index, choice-1, [ choice-2, ..., [ choice-n ]] )](#choose) as

從參數列表選擇和返回值。

Part 說明
index 必需。 其值介於1到可用選項的數量之間。
choice 必需。 包含一個可能的選擇的變量表達式。

示例

Function GetChoice(Ind As Integer)
    GetChoice = Choose(Ind, "Speedy", "United", "Federal")
End Function

▌Date( ) as Date

返回包含當前系統日期的 Variant (Date)。

示例

Dim MyDate
MyDate = Date    ' MyDate contains the current system date.

[▌DateDiff( interval, date1, date2, [ firstdayofweek, [ firstweekofyear ]] )](#datediff) as Long

指定兩個指定的日期之間的時間間隔數。

Part 說明
interval 必需。 表示用於計算 date1 和 date2 之間差別的時間間隔的字符串表達式。
date一、date2 必需;Variant (Date)。 要在計算中使用的兩個日期。
firstdayofweek 可選。 一個指定一週的第一天的常量。 若是未指定,則會假定爲星期日。
firstweekofyear 可選。 一個指定一年的第一週的常量。 若是未指定,則會假定 1 月 1 日出現的那一週爲第一週。

interval 參數

Setting 說明
yyyy
q 季度
m
y 每一年的某一日
d
w 工做日
ww
h 小時
n 分鐘
s

firstdayofweek 參數

常量 說明
vbSunday 1 週日(默認)
vbMonday 2 星期一
vbTuesday 3 星期二
vbWednesday 4 星期三
vbThursday 5 星期四
vbFriday 6 星期五
vbSaturday 7 星期六

firstweekofyear 參數

常量 說明
vbUseSystem 0 使用 NLS API 設置。
vbFirstJan1 1 從 1 月 1 日所在的周開始(默認)。
vbFirstFourDays 2 從至少包含新的一年中的四天的那一週開始。
vbFirstFullWeek 3 從每一年的第一個完整的星期開始。

示例

Dim TheDate As Date    ' Declare variables.
Dim Msg
TheDate = InputBox("Enter a date")
Msg = "Days from today: " & DateDiff("d", Now, TheDate)
MsgBox Msg

[▌DatePart( interval、 date、[ firstdayofweek,[ firstweekofyear ]] )](#datepart) as

Format 或 DatePart 函數可能返回一年中的上一個星期一的錯誤週數。

示例

Dim TheDate As Date    ' Declare variables.
Dim Msg    
TheDate = InputBox("Enter a date:")
Msg = "Quarter: " & DatePart("q", TheDate)
MsgBox Msg

▌DateSerial( year, month, day ) as Date

返回指定年月日的 Date 。

Part 說明
year 必需;類型爲 Integer。 介於 100 和 9999 之間(含 100 和 9999)的數字或者數字表達式。
month 必需;類型爲 Integer。 任何數字表達式。
爲期 必需;類型爲 Integer。 任何數字表達式。

示例

Dim MyDate
' MyDate contains the date for February 12, 1969.
MyDate = DateSerial(1969, 2, 12)    ' Return a date.

▌DateValue( date As String|Date) as Date

若是_date_是一個僅包含由有效日期分隔符分隔的數字的字符串, 則DateValue將根據您爲系統指定的短日期格式識別月、日和年的順序。 DateValue 還能清楚地識別包含月名稱(長名稱或簡寫形式)的日期。 例如,除了識別 12/30/1991 和 12/30/91 以外,DateValue 還識別 December 30, 1991 和 Dec 30, 1991。
若是省略 date 的年部分,則 DateValue 將使用計算機系統日期中的當前年。
若是 date 參數包含時間信息,則 DateValue 將不會返回它。 可是,若是 date 包含的時間信息無效(如「89:98」),則將出錯。

示例

Dim MyDate
MyDate = DateValue("February 12, 1969")    ' Return a date.

▌Day( date As Number|String|Null) as Integer

返回一個Integer,它指定一個表示月中的某一天的介於 1 和 31(含 1 和 31)之間的整數。

示例

Dim MyDate, MyDay
MyDate = #February 12, 1969#    ' Assign a date.
MyDay = Day(MyDate)    ' MyDay contains 12.

[▌DDB( cost, salvage, life, period, [ factor ] )](#ddb) as Double

返回一個double , 它使用雙倍餘額遞減法或其餘指定方法來指定特定時間段內資產的折舊值。

參數 說明
cost 必需。 指定資產的初始成本的雙精度型。
salvage 必需。 ** 在其使用壽命結束時指定資產的價值。
life 必需。 指定資產使用年限的長度的double 。
period 必需。 指定計算資產折舊的時段的double 。
factor 可選。 指定餘額降低比率的Variant 。 若省略它,則假定爲 2(雙倍餘額遞減法)。

示例

Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, DepYear, Depr
Const YRMOS = 12    ' Number of months in a year.
Fmt = "###,##0.00"
InitCost = InputBox("What's the initial cost of the asset?")
SalvageVal = InputBox("Enter the asset's value at end of its life.")
MonthLife = InputBox("What's the asset's useful life in months?")
Do While MonthLife < YRMOS    ' Ensure period is >= 1 year.
    MsgBox "Asset life must be a year or more."
    MonthLife = InputBox("What's the asset's useful life in months?")
Loop
LifeTime = MonthLife / YRMOS    ' Convert months to years.
If LifeTime <> Int(MonthLife / YRMOS) Then
    LifeTime = Int(LifeTime + 1)    ' Round up to nearest year.
End If 
DepYear = CInt(InputBox("Enter year for depreciation calculation."))
Do While DepYear < 1 Or DepYear > LifeTime
    MsgBox "You must enter at least 1 but not more than " & LifeTime
    DepYear = InputBox("Enter year for depreciation calculation.")
Loop
Depr = DDB(InitCost, SalvageVal, LifeTime, DepYear)
MsgBox "The depreciation for year " & DepYear & " is " & _
Format(Depr, Fmt) & "."

[▌Dir( pathname, [ attributes ] )](#dir) as String

它表示與指定模式或文件屬性或驅動器的卷標匹配的文件、目錄或文件夾的名稱。

Part 說明
pathname 可選。 指定文件名的字符串表達式,可包括目錄或文件夾和驅動器。 若是未找到 pathname,則返回零長度字符串 ("")。
attributes 可選。 其和指定文件屬性的常量或數值表達式。 若是省略它,則返回與 pathname 匹配但沒有屬性的文件。
attributes 參數 說明
vbNormal 0 (默認)指定沒有屬性的文件。
vbReadOnly 1 指定只讀文件以及不帶屬性的文件。
vbHidden 2 指定隱藏文件以及不帶屬性的文件。
vbSystem 4 指定系統文件以及不帶屬性的文件。 在 Macintosh 上不可用。
vbVolume 8 指定卷標;若是指定任何其餘屬性,則忽略 vbVolume。 在 Macintosh 上不可用。
vbDirectory 16 指定目錄或文件夾以及不帶屬性的文件。
vbAlias 64 指定文件名爲別名。 僅在 Macintosh 上可用。

示例

'返回當前文件夾中的第一個 TEXT 文件的名稱:
Dir("SomePath", MacID("TEXT"))
'若要循環訪問文件夾中的全部文件,請指定一個空字符串
Dir("")

▌DoEvents( ) as Integer

VB中打開的窗體的數目

示例

' Create a variable to hold number of Visual Basic forms loaded 
' and visible.
Dim I, OpenForms
For I = 1 To 150000    ' Start loop.
    If I Mod 1000 = 0 Then     ' If loop has repeated 1000 times.
        OpenForms = DoEvents    ' Yield to operating system.
    End If
Next I    ' Increment loop counter.

▌Environ( { envstring | number } ) as String

返回與操做系統環境變量關聯的 字符串 。在 Macintosh 中不可用。

示例

Dim EnvString, Indx, Msg, PathLen    ' Declare variables.
Indx = 1    ' Initialize index to 1.
Do
    EnvString = Environ(Indx)    ' Get environment 
                ' variable.
    If Left(EnvString, 5) = "PATH=" Then    ' Check PATH entry.
        PathLen = Len(Environ("PATH"))    ' Get length.
        Msg = "PATH entry = " & Indx & " and length = " & PathLen
        Exit Do
    Else
        Indx = Indx + 1    ' Not PATH entry,
    End If    ' so increment.
Loop Until EnvString = ""
If PathLen > 0 Then
    MsgBox Msg    ' Display message.
Else
    MsgBox "No PATH environment variable exists."
End If

▌EOF( filenumber ) as Integer

使用 EOF 可避免在嘗試超出文件的末尾來獲取輸出時產生錯誤。EOF 函數返回 False,直到到達文件的末尾。 對於以隨機或二進制訪問方式打開的文件, EOF將返回False , 直到最後一個執行的 Get 語句沒法讀取整條記錄。

示例

Dim InputData
Open "MYFILE" For Input As #1    ' Open file for input.
Do While Not EOF(1)    ' Check for end of file.
    Line Input #1, InputData    ' Read line of data.
    Debug.Print InputData    ' Print to the Immediate window.
Loop
Close #1    ' Close file.

[▌Error( [errornumber As Interger ] )](#error) as String

返回與給定錯誤代碼相對應的錯誤消息。

示例

Private Sub PrintError()
    Dim ErrorNumber As Long, count As Long
    count = 1: ErrorNumber = 1
    On Error GoTo EOSb
    Do While count < 100
        Do While Error(ErrorNumber) = "Application-defined or object-defined error": ErrorNumber = ErrorNumber + 1: Loop
        Debug.Print count & "-Error(" & ErrorNumber & "): " & Error(ErrorNumber)
        ErrorNumber = ErrorNumber + 1
        count = count + 1
    Loop
EOSb: Debug.Print ErrorNumber
End Sub

▌FileAttr( filenumber As Integer , returntype As Integer ) as Long

使用 Open 語句打開的文件的文件模式。

Part 說明
filenumber 必需;類型爲 Integer。 任何有效文件號。
returntype 必需;Integer。 指示要返回的信息類型的數值。 指定 1 將返回指示文件模式的值。 只在 16 位系統上,指定 2 來檢索操做系統文件句柄。 Returntype 2 在 32 位系統上不受支持並會致使錯誤。

當 returntype 參數爲1時, 下列返回值指示文件訪問模式:

返回值 Value
Input 1
Output 2
Random 4
Append 8
Binary 32

示例

Dim FileNum, Mode, Handle
FileNum = 1    ' Assign file number.
Open "TESTFILE" For Append As FileNum    ' Open file.
Mode = FileAttr(FileNum, 1)    ' Returns 8 (Append file mode).
Handle = FileAttr(FileNum, 2)    ' Returns file handle.
Close FileNum    ' Close file.

▌FileDateTime( pathname As String) as Date

返回指示文件建立或最後修改的 Variant (Date)。

示例

Dim MyStamp
' Assume TESTFILE was last modified on February 12, 1993 at 4:35:47 PM.
' Assume English/U.S. locale settings.
MyStamp = FileDateTime("TESTFILE")    ' Returns "2/12/93 4:35:47 PM".

▌FileLen( pathname As String) as Long

返回一個指定文件長度(以字節爲單位)的 Long 值。

示例

Dim MySize
MySize = FileLen("TESTFILE")    ' Returns file length (bytes).

[▌Filter( sourcearray, match, [ include, [ compare ]] )](#filter) as Array

返回一個從零開始的數組, 該數組包含基於指定的篩選條件的字符串數組的子集。

Part 說明
sourcearray 必需。 要搜索的字符串的一維度組。
match 必需。 要搜索的字符串。
include 可選。 Boolean 值,指示是否返回包括或排除 match 的子字符串。 若是 include 爲 True,則 Filter 返回包含 match 做爲子字符串的數組的子集。 若是 include 爲 False,則 Filter 返回不包含 match 做爲子字符串的數組的子集。
compare 可選。 指示要使用的字符串比較類型的數值。 請參閱「設置」部分了解相關值。
compare常量 說明
vbUseCompareOption -1 使用 Option Compare 語句的設置來執行比較。
vbBinaryCompare 0 執行二進制比較。
vbTextCompare 1 執行文本比較。
vbDatabaseCompare 2 僅用於 Microsoft Access。 根據數據庫中的信息執行比較。

[▌FormatCurrency( Expression、[ NumDigitsAfterDecimal, [ IncludeLeadingDigit, [ UseParensForNegativeNumbers, [ GroupDigits ]]]] )](#formatcurrency) as Currency

經過使用系統控制面板中定義的貨幣符號返回一個格式爲貨幣值的表達式。

Part 說明
Expression 必需。 要格式化的表達式。
NumDigitsAfterDecimal 可選。 指示要顯示的小數點右側的位數的數值。 默認值爲-1, 表示使用計算機的區域設置。
IncludeLeadingDigit 可選。 指示是否爲小數值顯示前導零的三態常數。 請參閱「設置」部分以瞭解各個值。
UseParensForNegativeNumbers 可選。 指示是否在圓括號內放置負值的三態常數。 請參閱「設置」部分以瞭解各個值。
GroupDigits 可選。 三態常量, 指示是否使用計算機的區域設置中指定的組分隔符對數字進行分組。 請參閱「設置」部分以瞭解各個值。

IncludeLeadingDigit、UseParensForNegativeNumbers 和 GroupDigits 參數包含如下設置:

常量 說明
vbTrue -1 True
vbFalse 0 False
vbUseDefault -2 使用計算機的區域設置中的設置。

[▌FormatDateTime( Date、[ NamedFormat ] )](#formatdatetime) as Date

返回格式爲日期或時間的表達式。

Part 說明
Date 必需。 要設置格式的日期表達式。
NamedFormat 可選。 指示所使用的日期/時間格式的數值。 若是省略,則會使用 vbGeneralDate
NamedFormat 常量 說明
vbGeneralDate 0 顯示日期和/或時間。 若是存在日期部分,則將其顯示爲短日期。 若是存在時間部分,則顯示爲長時間。 若是存在這兩個部分,則這兩個部分均會顯示。
vbLongDate 1 使用計算機的區域設置中指定的長日期格式顯示日期。
vbShortDate 2 使用計算機的區域設置中指定的短日期格式顯示日期。
vbLongTime 3 使用計算機的區域設置中指定的時間格式顯示時間。
vbShortTime 4 使用24小時制 (hh: mm) 顯示時間。

[▌FormatNumber( Expression、[ NumDigitsAfterDecimal, [ IncludeLeadingDigit, [ UseParensForNegativeNumbers, [ GroupDigits ]]]] )](#formatnumber) as Number

返回數字格式的表達式。

Part 說明
Expression 必需。 要格式化的表達式。
NumDigitsAfterDecimal 可選。 指示要顯示的小數點右側的位數的數值。 默認值爲-1, 表示使用計算機的區域設置。
IncludeLeadingDigit 可選。 指示是否爲小數值顯示前導零的三態常數。 請參閱「設置」部分以瞭解各個值。
UseParensForNegativeNumbers 可選。 指示是否在圓括號內放置負值的三態常數。 請參閱「設置」部分以瞭解各個值。
GroupDigits 可選。 三態常量, 指示是否使用計算機的區域設置中指定的組分隔符對數字進行分組。 請參閱「設置」部分以瞭解各個值。

IncludeLeadingDigit、UseParensForNegativeNumbers 和 GroupDigits 參數包含如下設置:

常量 說明
vbTrue -1 True
vbFalse 0 False
vbUseDefault -2 使用計算機的區域設置中的設置。

[▌FormatPercent( Expression、[ NumDigitsAfterDecimal, [ IncludeLeadingDigit, [ UseParensForNegativeNumbers, [ GroupDigits ]]]] )](#formatpercent) as String

Part 說明
Expression 必需。 要格式化的表達式。
NumDigitsAfterDecimal 可選。 指示要顯示的小數點右側的位數的數值。 默認值爲-1, 表示使用計算機的區域設置。
IncludeLeadingDigit 可選。 指示是否爲小數值顯示前導零的三態常數。 請參閱「設置」部分以瞭解各個值。
UseParensForNegativeNumbers 可選。 指示是否在圓括號內放置負值的三態常數。 請參閱「設置」部分以瞭解各個值。
GroupDigits 可選。 三態常量, 指示是否使用計算機的區域設置中指定的組分隔符對數字進行分組。 請參閱「設置」部分以瞭解各個值。

IncludeLeadingDigit、UseParensForNegativeNumbers 和 GroupDigits 參數包含如下設置:

常量 說明
vbTrue -1 True
vbFalse 0 False
vbUseDefault -2 使用計算機的區域設置中的設置。

▌FreeFile( rangenumber ) as Number

返回一個整數, 表示可由Open 語句使用的下一個文件號。

更多


[▌FV( rate, nper, pmt, [ pv, [ type ]] )](#fv) as Double

返回一個double , 它基於按期固定付款和固定利率指定年金的將來值。

年金是一段時間內一系列的固定的現金付款。 年金能夠是貸款(如房產抵押),也能夠是投資(如月存款計劃)。
必須使用以相同單位表示的付款時段計算 rate 和 nper 參數。 例如, 若是 rate 是使用月計算的, 則還必須使用月計算 nper 。
對於全部參數,已支出現金(例如,存款儲蓄)用負數表示;已收現金(例如,股利支票)用正數表示。

Part 說明
rate 必需。 指定每一個週期的利率的 Double。 例如,若是您得到了年利率 (APR) 爲 10% 的汽車貸款並進行月供,則每期利率爲 0.1/12 或 0.0083。
nper 必需。 指定年金付款期的總數的 Integer。 例如,若是您每個月償還爲期 4 年的汽車貸款,則您的貸款期總數爲 4 * 12(或 48)。
pmt 必需。 指定每月的付款的 Double。 付款一般包含了在該年金時期間不會改變的本金和利息。
pv 可選。 指定一系列將來付款的當前值(或總計)的 Variant。 例如,當您借錢買車時,貸款金額爲其支付每個月汽車付款的借方的當前值。 若是省略了,便假設爲 0。
type 可選。 指定付款的到期時間的 Variant。 若是付款在付款期結束時到期,則使用 0;若是付款在付款期開始時到期,則使用 1。 若是省略,則假定爲 0。

示例

Dim Fmt, Payment, APR, TotPmts, PayType, PVal, FVal
Const ENDPERIOD = 0, BEGINPERIOD = 1    ' When payments are made.
Fmt = "###,###,##0.00"    ' Define money format.
Payment = InputBox("How much do you plan to save each month?")
APR = InputBox("Enter the expected interest annual percentage rate.")
If APR > 1 Then APR = APR / 100    ' Ensure proper form.
TotPmts = InputBox("For how many months do you expect to save?")
PayType = MsgBox("Do you make payments at the end of month?", vbYesNo)
If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD
PVal = InputBox("How much is in this savings account now?")
FVal = FV(APR / 12, TotPmts, -Payment, -PVal, PayType)
MsgBox "Your savings will be worth " & Format(FVal, Fmt) & "."

▌GetAllSettings( appname, section ) as Array

更多


▌GetAttr( pathname As String) as Integer

返回表示文件、目錄或文件夾的屬性的 Integer 。

GetAttr 所返回的值是如下屬性值的和:

常量 說明
vbNormal 0 正常。
vbReadOnly 1 只讀。
vbHidden 2 可見.
vbSystem 4 系統文件。 在 Macintosh 上不可用。
vbDirectory 2 目錄或文件夾。
vbArchive 32 文件自上次備份以來已發生更改。 在 Macintosh 上不可用。
vbAlias 64 指定文件名爲別名。 僅在 Macintosh 上可用。

示例

'若是未設置 Archive 屬性,則如下 And 表達式的返回值爲零
Result = GetAttr(FName) And vbArchive

Dim MyAttr
' Assume file TESTFILE has hidden attribute set.
MyAttr = GetAttr("TESTFILE")    ' Returns 2.

' Returns nonzero if hidden attribute is set on TESTFILE.
Debug.Print MyAttr And vbHidden    

' Assume file TESTFILE has hidden and read-only attributes set.
MyAttr = GetAttr("TESTFILE")    ' Returns 3.

' Returns nonzero if hidden attribute is set on TESTFILE.
Debug.Print MyAttr And (vbHidden + vbReadOnly)    

' Assume MYDIR is a directory or folder.
MyAttr = GetAttr("MYDIR")    ' Returns 16.

▌Hour( time ) as Integer

返回指定表示一天的小時的 0 到 23 之間(含這兩個值)的整數的變量(整數)。

示例

Dim MyTime, MyHour
MyTime = #4:35:17 PM#    ' Assign a time.
MyHour = Hour(MyTime)    ' MyHour contains 16.

▌IIf( expr, truepart, falsepart ) as Any

Part 說明
expr 必需。 要計算的表達式。
truepart 必需。 expr 爲 True 時返回的值或表達式。
falsepart 必需。 expr 爲 False 時返回的值或表達式。

示例

Function CheckIt (TestMe As Integer)
    CheckIt = IIf(TestMe > 1000, "Large", "Small")
End Function


[▌Input( number, [ # ]filenumber )](#Input) as String

從以 Input 或 Binary 模式打開的文件中返回包含字符的String。

Part 說明
number 必需。 指定要返回字符個數的任意有效的數值表達式。
filenumber 必需。 任何有效的文件編號。

示例

Dim MyChar
Open "TESTFILE" For Input As #1    ' Open file.
Do While Not EOF(1)    ' Loop until end of file.
    MyChar = Input(1, #1)    ' Get one character.
    Debug.Print MyChar    ' Print to the Immediate window.
Loop
Close #1    ' Close file.

[▌InputBox( prompt, [ title ], [ default ], [ xpos ], [ ypos ], [ helpfile, context ] )](#InputBox) as String

在對話框中顯示提示,等待用戶輸入文本或單擊按鈕,而後返回包含文本框內容的字符串。

Part 說明
prompt 必需項。 字符串表達式在對話框中顯示爲消息。 prompt 的最大長度約爲 1024 個字符,具體取決於所使用的字符的寬度。 若是_prompt_包含多行, 則可使用回車符 (chr(13))、換行符 (chr(10)) 或回車換行符組合 ((chr (13) & ((chr (13)) 來分隔行。 ((chr(13) (** 每一個行的 Chr (10))。
title 可選。 對話框標題欄中顯示的字符串表達式。 若是省略 title,則標題欄中將顯示應用程序名稱。
default 可選。 文本框中顯示的字符串表達式,在未提供其餘輸入時做爲默認響應。 若是省略了 default,文本框將顯示爲空。
xpos 可選。 指定對話框的左邊緣與屏幕的左邊緣的水平距離(以緹爲單位)的數值表達式。 若是省略了 xpos,對話框將水平居中。
ypos 可選。 指定對話框的上邊緣與屏幕的頂部的垂直距離(以緹爲單位)的數值表達式。 若是省略了 ypos,對話框將位於屏幕垂直方向往下大約三分之一的位置。
helpfile 可選。 用於標識幫助文件的字符串表達式,前者用於爲對話框提供上下文相關的幫助。 若是提供 helpfile,則也必須提供 context。
context 可選。 幫助上下文數值的數值表達式,該數值由幫助做者爲相應的幫助主題分配。 若是提供 context,則也必須提供 helpfile。

示例

Dim Message, Title, Default, MyValue
Message = "Enter a value between 1 and 3"    ' Set prompt.
Title = "InputBox Demo"    ' Set title.
Default = "1"    ' Set default.
' Display message, title, and default value.
MyValue = InputBox(Message, Title, Default)

' Use Helpfile and context. The Help button is added automatically.
MyValue = InputBox(Message, Title, , , , "DEMO.HLP", 10)

' Display dialog box at position 100, 100.
MyValue = InputBox(Message, Title, Default, 100, 100)

[▌InStr( [ start ], string1, string2, [ compare ] )](#InStr) as Long

返回一個 Variant (Long) 值,指定一個字符串在另外一個字符串中首次出現的位置。

Part 說明
start 可選。 設置每次搜索的起始位置的數字表達式。 若是忽略,則搜索從第一個字符位置開始。 若是 start 包含 Null,則出現錯誤。 若是指定了 compare,則 start 參數是必需的。
string1 必需。 要搜索的字符串表達式。
string2 必需。 搜索到的字符串表達式。
compare 可選。 指定字符串比較的類型。 若是 compare 爲 Null,則將發生錯誤。 若是省略 compare,則 Option Compare 設置將決定比較的類型。 指定有效的 LCID (LocaleID) 以在比較中使用區域設置特定規則。
compare常量 說明
vbUseCompareOption -1 使用 Option Compare 語句的設置執行比較。
vbBinaryCompare 0 執行二進制比較。
vbTextCompare 1 執行文本比較。
vbDatabaseCompare 2 僅用於 Microsoft Access。 根據數據庫中的信息執行比較。
If InStr 返回
string1 是零長度 0
string1 爲 Null NULL
string2 是零長度 start
string2 爲 Null NULL
未找到 string2 0
在 string1 中找到 string2 找到匹配的位置
start > string2 0

示例

Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP"    ' String to search in.
SearchChar = "P"    ' Search for "P".

' A textual comparison starting at position 4. Returns 6.
MyPos = Instr(4, SearchString, SearchChar, 1)    

' A binary comparison starting at position 1. Returns 9.
MyPos = Instr(1, SearchString, SearchChar, 0)

' Comparison is binary by default (last argument is omitted).
MyPos = Instr(SearchString, SearchChar)    ' Returns 9.

MyPos = Instr(1, SearchString, "W")    ' Returns 0.

[▌InStrRev( stringcheck, stringmatch, [ start, [ compare ]] )](#InStrRev) as Long

返回一個字符串在另外一個字符串中首次出現的位置(從字符串的末尾開始)。

Part 說明
stringcheck 必需。 要搜索的字符串表達式。
stringmatch 必需。 所搜索到的字符串表達式。
start 可選。 設置每次搜索的起始位置的數字表達式。 若是省略,則使用 -1,這意味着搜索將從最後一個字符位置開始。 若是 start 包含 Null,則出現錯誤。
compare 可選。 指示計算子字符串時使用的比較類型的數值。 若是省略,則將執行二進制比較。 有關各個值的信息,請參閱「設置」部分。
compare常量 說明
vbUseCompareOption -1 使用 Option Compare 語句的設置執行比較。
vbBinaryCompare 0 執行二進制比較。
vbTextCompare 1 執行文本比較。
vbDatabaseCompare 2 僅用於 Microsoft Access。 根據數據庫中的信息執行比較。
If InStr 返回
string1 是零長度 0
string1 爲 Null NULL
string2 是零長度 start
string2 爲 Null NULL
未找到 string2 0
在 string1 中找到 string2 找到匹配的位置
start > Len(stringmatch) 0

[▌IPmt( rate, per, nper, pv, [ fv, [ type ]] )](#IPmt) as Double

返回一個 Double,它基於按期固定付款和固定利率指定年金的給按期間利率付款。

Part 說明
rate 必需。 指定每一個週期的利率的 Double。 例如,若是您得到了年利率 (APR) 爲 10% 的汽車貸款並進行月供,則每期利率爲 0.1/12 或 0.0083。
per 必需。 指定介於 1 和 nper 之間的付款期次的 Double。
nper 必需。 指定年金總付款期數的「Double」*。 例如,若是您要每個月償付四年期限的車貸,您的貸款總付款期爲 4 12 (或 48)。
pv 必需。 指定一系列將來付款或回執的現值或當前值的「Double」** 。 例如,若是您借錢買了一輛車,貸款金額則爲將要向借貸人每個月支付車貸的現值。
fv 可選。 指定在完成最後付款後所需的將來值或現金餘額的 Variant。 例如,貸款的將來值爲 $0,由於這是完成最後付款後的值。 可是, 若是您想要在18年的時間內爲孩子的教育版節省 $50000, 則 $50000 是將來的價值。 若是省略了,便假設爲 0。
type 可選。 指定付款的到期時間的 Variant。 若是付款在付款期結束時到期,則使用 0;若是付款在付款期開始時到期,則使用 1。 若是省略,則假定爲 0。

示例

Dim FVal, Fmt, PVal, APR, TotPmts, PayType, Period, IntPmt, TotInt, Msg
Const ENDPERIOD = 0, BEGINPERIOD = 1    ' When payments are made.
FVal = 0    ' Usually 0 for a loan.
Fmt = "###,###,##0.00"    ' Define money format.
PVal = InputBox("How much do you want to borrow?")
APR = InputBox("What is the annual percentage rate of your loan?")
If APR > 1 Then APR = APR / 100    ' Ensure proper form.
TotPmts = InputBox("How many monthly payments?")
PayType = MsgBox("Do you make payments at end of the month?", vbYesNo)
If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD
For Period = 1 To TotPmts    ' Total all interest.
    IntPmt = IPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType)
    TotInt = TotInt + IntPmt
Next Period
Msg = "You'll pay a total of " & Format(TotInt, Fmt) 
Msg = Msg & " in interest for this loan."
MsgBox Msg    ' Display results.

[▌IRR( values()、[ guess ] )](#IRR) as Double

返回一個雙精度值,該值爲一系列按期現金流(付款和收款)指定內部回報率。

Part 說明
值() 必需。 用於指定現金流值的雙精度數組。 該數組必須包含至少一個負值(付款)和一個正值(收款)。
出來 可選。 指定您估計的值的Variant將由IRR返回。 若是省略了,則_推測_爲 0.1(10%)。

更多


▌IsArray( varname as Any ) as Boolean

返回指示變量 是不是數組。

示例

Dim MyArray(1 To 5) As Integer, YourArray, MyCheck    ' Declare array variables.
YourArray = Array(1, 2, 3)    ' Use Array function.
MyCheck = IsArray(MyArray)    ' Returns True.
MyCheck = IsArray(YourArray)    ' Returns True.

▌IsDate( expression ) as Boolean

若是表達式是日期或可識別爲有效日期或時間,則返回True;不然,返回True。

示例

Dim MyVar, MyCheck
MyVar = "04/28/2014"    ' Assign valid date value.
MyCheck = IsDate(MyVar)    ' Returns True.

MyVar = "April 28, 2014"    ' Assign valid date value.
MyCheck = IsDate(MyVar)    ' Returns True.

MyVar = "13/32/2014"    ' Assign invalid date value.
MyCheck = IsDate(MyVar)    ' Returns False.

MyVar = "04.28.14"    ' Assign valid time value.
MyCheck = IsDate(MyVar)    ' Returns True.

MyVar = "04.28.2014"    ' Assign invalid time value.
MyCheck = IsDate(MyVar)    ' Returns False.

▌IsEmpty( expression ) as Boolean

返回一個指示是否已初始化變量的布爾值。

示例

Dim MyVar, MyCheck
MyCheck = IsEmpty(MyVar)    ' Returns True.

MyVar = Null    ' Assign Null.
MyCheck = IsEmpty(MyVar)    ' Returns False.

MyVar = Empty    ' Assign Empty.
MyCheck = IsEmpty(MyVar)    ' Returns True.

▌IsError( expression ) as Boolean

返回一個 Boolean 值,指示表達式是否爲錯誤值。

示例

Dim ReturnVal, MyCheck
ReturnVal = UserFunction()
MyCheck = IsError(ReturnVal)    ' Returns True.

▌IsMissing( argname ) as Boolean

返回一個布爾值, 該值指示是否已將可選Variant 參數傳遞給過程。

示例

Dim ReturnValue
' The following statements call the user-defined function procedure.
ReturnValue = ReturnTwice()    ' Returns Null.
ReturnValue = ReturnTwice(2)    ' Returns 4.

' Function procedure definition.
Function ReturnTwice(Optional A)
    If IsMissing(A) Then
        ' If argument is missing, return a Null.
        ReturnTwice = Null
    Else
        ' If argument is present, return twice the value.
        ReturnTwice = A * 2
    End If
End Function

▌IsNull( expression ) as Boolean

返回指示表達式是否包含無效數據 (Null) 的 Boolean 值。

示例

Dim MyVar, MyCheck
MyCheck = IsNull(MyVar)    ' Returns False.

MyVar = ""
MyCheck = IsNull(MyVar)    ' Returns False.

MyVar = Null
MyCheck = IsNull(MyVar)    ' Returns True.

▌IsNumeric( expression ) as Boolean

返回指示表達式是否可評估爲數值的Boolean值。

示例

Dim MyVar, MyCheck
MyVar = "53"    ' Assign value.
MyCheck = IsNumeric(MyVar)    ' Returns True.

MyVar = "459.95"    ' Assign value.
MyCheck = IsNumeric(MyVar)    ' Returns True.

MyVar = "45 Help"    ' Assign value.
MyCheck = IsNumeric(MyVar)    ' Returns False.

▌IsObject( expression ) as Boolean

返回一個指示標識符是否表示某個對象的變量的 Boolean 值。

示例

Dim MyInt As Integer              ' Declare variables.
Dim YourObject, MyCheck           ' Note: Default variable type is Variant.
Dim MyObject As Object
Set YourObject = MyObject         ' Assign an object reference.
MyCheck = IsObject(YourObject)    ' Returns True.
MyCheck = IsObject(MyInt)         ' Returns False.
MyCheck = IsObject(Nothing)       ' Returns True.
MyCheck = IsObject(Empty)         ' Returns False.
MyCheck = IsObject(Null)          ' Returns False.

[▌Join( sourcearray, [ delimiter ] )](#Join) as String

返回經過聯接數組中包含的大量子字符串建立的字符串。

Part 說明
sourcearray 必需。 一維度組,包含要聯接的子字符串。
delimiter 可選。 用於分隔返回字符串中子字符串的字符串。 若是省略,將使用空格 ("")。 若是 delimiter 是一個零長度字符串 (""),將鏈接列表中的全部項,而不使用分隔符。

[▌LBound( arrayname, [ dimension ] )](#LBound) as Long

返回一個 Long 型值,其中包含指示的數組維度的最小可用下標。

Part 說明
arrayname 必需。 數組變量的名稱;遵循標準變量命名約定。

維度 v可選;Variant (Long)。 指示返回哪一個維度的下限的整數。 1 表示第一個維度,2 表示第二個維度,依此類推。 若是省略 dimension,則假定爲 1。

示例

Dim Lower
Dim MyArray(1 To 10, 5 To 15, 10 To 20)     ' Declare array variables.
Dim AnyArray(10)
Lower = Lbound(MyArray, 1)     ' Returns 1.
Lower = Lbound(MyArray, 3)    ' Returns 10.
Lower = Lbound(AnyArray)    ' Returns 0 or 1, depending on
    ' setting of Option Base.

▌LCase( string Sd String) as String

返回已轉換爲小寫形式的 String。若是字符串包含 Null,則返回 Null。

示例

Dim UpperCase, LowerCase
Uppercase = "Hello World 1234"    ' String to convert.
Lowercase = Lcase(UpperCase)    ' Returns "hello world 1234".

▌Left( ) as

返回一個包含字符串左側指定字符數的 Variant (String)。

Part 說明
string 必需。 從中返回最左側字符的字符串表達式。 若是_字符串_包含 Null,則返回 Null。
Length 必需;Variant (Long)。 數值表達式指示要返回多少字符。 若是爲 0,則返回零長度字符串 ("")。 若是大於或等於「字符串」 __ 中的字符數量,則返回整個字符串。

註解

示例

Dim AnyString, MyStr
AnyString = "Hello World"    ' Define string.
MyStr = Left(AnyString, 1)   ' Returns "H".
MyStr = Left(AnyString, 7)   ' Returns "Hello W".
MyStr = Left(AnyString, 20)  ' Returns "Hello World".

▌Len( string | varname ) as Long

返回包含字符串中的字符數或存儲變量所需的字節數的長整數。

Part 說明
string 任何有效的字符串表達式。 若是_字符串_包含 Null,則返回 Null。
varname 任何有效的變量名稱。 若是 varname 包含 Null,則返回 Null。 若是 varname 是變量,則 Len 會像處理 String 同樣處理它,並始終返回其包含的字符數。

示例

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.

▌Loc( filenumber As Integer) as Long

返回指定打開的文件內的當前可讀/寫位置的 Long。

Mode 返回值
Random 在文件中讀取或寫入的最後一個記錄的編號。
Sequential 文件中除以 128 的當前字節位置。 可是,不使用也不須要 Loc 爲順序文件返回的信息。
Binary 讀取或寫入的最後一個字節的位置。

示例

Dim MyLocation, MyLine
Open "TESTFILE" For Binary As #1    ' Open file just created.
Do While MyLocation < LOF(1)    ' Loop until end of file.
    MyLine = MyLine & Input(1, #1)    ' Read character into variable.
    MyLocation = Loc(1)    ' Get current position within file.
' Print to the Immediate window.
    Debug.Print MyLine; Tab; MyLocation
Loop
Close #1    ' Close file.

▌LOF( filenumber ) as Long

返回一個Long , 表示使用Open 語句打開的文件的大小 (以字節爲單位)。

示例

Dim FileLength
Open "TESTFILE" For Input As #1    ' Open file.
FileLength = LOF(1)    ' Get length of file.
Close #1    ' Close file.

▌LTrim、RTrim 和 Trim( ) as String

返回 字符串 包含指定字符串副本(不含前導空格 (LTrim)、後續空格 (RTrim) 或前導和後續空格 (Trim))。

示例

Dim MyString, TrimString
MyString = "  <-Trim->  "    ' Initialize string.
TrimString = LTrim(MyString)    ' TrimString = "<-Trim->  ".
TrimString = RTrim(MyString)    ' TrimString = "  <-Trim->".
TrimString = LTrim(RTrim(MyString))    ' TrimString = "<-Trim->".
' Using the Trim function alone achieves the same result.
TrimString = Trim(MyString)    ' TrimString = "<-Trim->".

[▌Mid( string, start, [ length ]) )](#Mid) as String

返回一個 Variant (String),其中包含字符串中的指定數量的字符。若要肯定字符串中字符的數量,請使用 Len 函數。

Part 說明
string 必需。 從中返回字符的字符串表達式。 若是_字符串_包含 Null,則返回 Null。
start 必需,Long。 _字符串_中被視爲開始部分的字符位置。 若是 start 大於_字符串_中的字符數,則 Mid 返回零長度字符串 ("")。
Length 可選;Variant (Long)。 要返回的字符的數目。 若是省略此部分或此部分中的數目少於文本中的 length 字符數(包括 start 處的字符),則將返回從 start 位置到字符串末尾的全部字符。

示例

Dim MyString, FirstWord, LastWord, MidWords
MyString = "Mid Function Demo"    ' Create text string.
FirstWord = Mid(MyString, 1, 3)    ' Returns "Mid".
LastWord = Mid(MyString, 14, 4)    ' Returns "Demo".
MidWords = Mid(MyString, 5)    ' Returns "Function Demo".

▌Minute( time As Variant|Number|String) as Integer

返回指定介於 0 和 59 之間(含 0 和 59)的一個整數的 Variant (Integer),表明分鐘數。

示例

Dim MyTime, MyMinute
MyTime = #4:35:17 PM#    ' Assign a time.
MyMinute = Minute(MyTime)    ' MyMinute contains 35.

▌MIRR( values( ), finance_rate, reinvest_rate ) as Double

返回爲一系列按期現金流量(付款和收款)指定修改的內部報酬率的 Double 值。

更多


▌Month( date As Variant|Number|String) as Integer

返回指定 1 至 12(包括 1 和 12)之間表示月份的整數的 Variant (Integer)。

示例

Dim MyDate, MyMonth
MyDate = #February 12, 1969#    ' Assign a date.
MyMonth = Month(MyDate)    ' MyMonth contains 2.

[▌MonthName( month, [ abbreviate ] )](#MonthName) as String

返回指定的月份的字符串。

Part 說明
month 必需。 月份的數值指定。 例如,一月是 1,二月是 2,依此類推。
縮短 可選。 Boolean 值,指示是否要對月份名稱採用縮寫形式。 若是省略,則默認值爲 False,這意味着不對月份名稱採用縮寫形式。

[▌MsgBox( prompt, [ buttons, ] [ title, ] [ helpfile, context ] )](#MsgBox) as Void

部分 說明
prompt 必需項。 字符串表達式在對話框中顯示爲消息。 prompt 的最大長度約爲 1024 個字符,具體取決於所使用的字符的寬度。 若是 prompt 包含兩行以上,則能夠在每行之間使用回車符 (Chr(13))、換行符 (Chr(10)) 或回車換行符組合 (Chr(13) & Chr(10)) 將其分隔。
buttons 可選。 數值表達式,用於指定要顯示按鈕的數量和類型、要使用的圖標樣式、默認按鈕的標識和消息框的形式的值之和。 若是省略,則 buttons 的默認值爲 0。
title 可選。 對話框標題欄中顯示的字符串表達式。 若是省略 title,則標題欄中將顯示應用程序名稱。
helpfile 可選。 用於標識幫助文件的字符串表達式,前者用於爲對話框提供上下文相關的幫助。 若是提供 helpfile,則也必須提供 context。
context 可選。 幫助上下文數值的數值表達式,該數值由幫助做者爲相應的幫助主題分配。 若是提供 context,則也必須提供 helpfile。

buttons 參數設置

常量 說明
vbOKOnly 0 僅顯示「肯定」按鈕。
vbOKCancel 1 顯示「肯定」和「取消」按鈕。
vbAbortRetryIgnore 2 顯示「停止」、「重試」和「忽略」按鈕。
vbYesNoCancel 3 顯示「是」、「否」和「取消」按鈕。
vbYesNo 4 顯示「是」和「否」按鈕。
vbRetryCancel 5 顯示「重試」和「取消」按鈕。
vbCritical 16 顯示「關鍵消息」圖標。
vbQuestion 32 顯示「警告查詢」圖標。
vbExclamation 48 顯示「警告消息」圖標。
vbInformation 64 顯示「信息消息」圖標。
vbDefaultButton1 0 第一個按鈕是默認按鈕。
vbDefaultButton2 256 第二個按鈕是默認按鈕。
vbDefaultButton3 512 第三個按鈕是默認按鈕。
vbDefaultButton4 768 第四個按鈕是默認按鈕。
vbApplicationModal 0 應用程序模式;用戶在繼續在當前應用程序中工做前必須響應消息框。
vbSystemModal 4096 系統模式;在用戶響應消息框前,全部應用程序都掛起。
vbMsgBoxHelpButton 16384 在消息框中添加「幫助」按鈕。
vbMsgBoxSetForeground 65536 將消息框窗口指定爲前景窗口。
vbMsgBoxRight 524288 文本右對齊。
vbMsgBoxRtlReading 1048576 指定文本在希伯來語和阿拉伯語系統中應從右到左顯示。
返回值 說明
vbOK 1 肯定
vbCancel 2 Cancel
vbAbort 3 停止
vbRetry 4 重試
vbIgnore 5 忽略
vbYes 6
vbNo 7

示例

Dim Msg, Style, Title, Help, Ctxt, Response, MyString
Msg = "Do you want to continue ?"    ' Define message.
Style = vbYesNo + vbCritical + vbDefaultButton2    ' Define buttons.
Title = "MsgBox Demonstration"    ' Define title.
Help = "DEMO.HLP"    ' Define Help file.
Ctxt = 1000    ' Define topic context. 
        ' Display message.
Response = MsgBox(Msg, Style, Title, Help, Ctxt)
If Response = vbYes Then    ' User chose Yes.
    MyString = "Yes"    ' Perform some action.
Else    ' User chose No.
    MyString = "No"    ' Perform some action.
End If

▌Now( ) as Date

返回一個Variant (Date), 它根據計算機的系統日期和時間指定當前日期和時間。

示例

Dim Today
Today = Now    ' Assign current system date and time.

[▌NPer( rate, pmt, pv, [ fv, [ type ]] )](#NPer) as Double

返回一個Double,該Double根據按期的固定付款額和固定利率指定年金的期數。

更多


▌NPV( ) as Double

返回一個 Double,它基於一系列按期現金流(付款和收款)和貼現率指定投資的淨現值。
更多


▌Partition( number, start, stop, interval ) as String

返回 Variant (String),指示數字在計算的一系列範圍內出現的位置。

Part 說明
number 必需。 要針對區域計算的數字。
start 必需。 做爲整個數字範圍的開頭的數字。 該數字不能小於 0。
stop 必需。 總數字範圍的結束的數字。 該數字不能等於或小於 start。
interval 必需。 一個範圍和下一個範圍之間的差別的數字。 該數字不能小於1。

更多


[▌Pmt( rate, nper, pv, [ fv, [ type ]] )](#Pmt) as Double

返回 Double,以指定基於按期、定額支付和固定利率的年金支付。

更多


[▌PPmt( rate, per, nper, pv, [ fv, [ type ]] )](#PPmt) as Double

返回一個Double,該Double根據按期的固定付款額和固定利率來指定給定年金期間的本金付款。

更多


[▌PV( rate、 nper、 pmt、[ fv、[ type ]] )](#PV) as Double

返回一個 Double,它基於將來要支付的按期固定付款和固定利率指定年金的當前值。

更多


▌QBColor( color ) as Long

返回一個Long,表示與指定顏色編號相對應的RGB顏色代碼。


[▌Rate( nper, pmt, pv, [ fv, [ type, [ guess ]]] )](#Rate) as Double

返回一個Double,指定年金每一個期間的利率。

更多


[▌Replace( expression、 find、 replace、[ start、[ count, [ compare ]]] )](#Replace) as

Part 說明
expression 必需。 包含要替換的子字符串的字符串表達式。
find 必需。 要搜索的子字符串。
replace 必需。 替換子字符串。
start 可選。 要搜索和返回的_表達式_的子字符串的起始位置。 若是省略,則假定此值爲 1。
count 可選。 要執行子字符串替換的次數。 若是省略, 則默認值爲-1, 表示進行全部可能的替換。
compare 可選。 指示計算子字符串時使用的比較類型的數值。 請參閱「設置」部分以瞭解各個值。
compare常量 說明
vbUseCompareOption -1 使用 Option Compare 語句的設置來執行比較。
vbBinaryCompare 0 執行二進制比較。
vbTextCompare 1 執行文本比較。
vbDatabaseCompare 2 僅用於 Microsoft Access。 根據數據庫中的信息執行比較。
If Replace 返回
expression 是零長度的 零長度字符串 ("")
expression 是 Null 錯誤。
find 是零長度的 expression 的副本。
replace 是零長度的 _表達式_的副本已刪除_查找_的全部匹配項。
啓動 > Len(表達式) 零長度字符串。 字符串替換從_start_指示的位置開始。
count 是 0 expression 的副本。

▌RGB( red, green, blue ) as Long

返回表示 RGB 顏色值的 Long 整數。

示例

Dim Red, I, RGBValue, MyObject
Red = RGB(255, 0, 0)    ' Return the value for Red.
I = 75    ' Initialize offset.
RGBValue = RGB(I, 64 + I, 128 + I)     ' Same as RGB(75, 139, 203).
MyObject.Color = RGB(255, 0, 0)    ' Set the Color property of MyObject to Red.

▌Right( string, length ) as String

返回了從字符串的右邊開始包含特定數目的字符

Part 說明
string 必需。 字符串表達式,從中返回最右邊的字符。 若是_字符串_包含 Null,則返回 Null。
Length 必需;Variant (Long)。 數值表達式指示要返回多少字符。 若是爲 0,則返回零長度字符串 ("")。 若是大於或等於「字符串」 __ 中的字符數量,則返回整個字符串。

示例

Dim AnyString, MyStr
AnyString = "Hello World"      ' Define string.
MyStr = Right(AnyString, 1)    ' Returns "d".
MyStr = Right(AnyString, 6)    ' Returns " World".
MyStr = Right(AnyString, 20)   ' Returns "Hello World".

[▌Round( expression, [ numdecimalplaces ] )](#Round) as Number

返回四捨五入到指定小數位數的數。

Part 說明
expression 必需。 要進行四捨五入的數值表達式。
numdecimalplaces 可選。 指示將包含在四捨五入中的小數右側的位數。 若是省略,則 Round 函數將返回整數。

示例

Round(0.12335,4)
' 0,1234
Round(0.12345,4)
' 0,1234
Round(0.12355,4)
' 0,1236
Round(0.12365,4)
' 0,1236

WorksheetFunction.Round(0.12345,4)
' 0,1235
WorksheetFunction.RoundUp(0.12345,4)
' 0,1235
WorksheetFunction.RoundDown(0.12345,4)
' 0,1234

Round(0.00005,4)
' 0
WorksheetFunction.Round(0.00005,4)
' 0,0001
WorksheetFunction.RoundUp(0.00005,4)
' 0,0001
WorksheetFunction.RoundDown(0.00005,4)
' 0

▌Second( time ) as

返回 0 到 59 之間的整數(其中包含 0、59 這兩個數)用於表明一分鐘內的秒數。

示例

Dim MyTime, MySecond
MyTime = #4:35:17 PM#    ' Assign a time.
MySecond = Second(MyTime)    ' MySecond contains 17.

▌Seek( filenumber ) as Long

返回一個Long類型的值, 指定使用 Open 語句打開的文件內的當前讀/寫位置。

Seek返回一個介於1和 2147483647 (至關於 2 ^ 31-1) 的值 (包括這兩個值)。

更多


[▌Shell( pathname, [ windowstyle ] )](#Shell) as Double

運行可執行程序並在成功時返回表示程序的任務 ID 的 Variant (Double);不然返回零。

Part 說明
pathname 必需;Variant (String)。 要執行的程序的名稱以及任何須需的參數或命令行開關;可能包括目錄或文件夾和驅動器。 在 Macintosh 中,可使用 MacID 函數指定應用程序的簽名,而不是名稱。 如下示例使用 Microsoft Word 的簽名:Shell MacID("MSWD")
windowstyle 可選。 與要運行程序的窗口的樣式對應的 Variant (Integer)。 若是省略 windowstyle,則在最小化焦點的狀況下啓動程序。 在 Macintosh(系統 7.0 或更高版本)上,windowstyle 僅肯定程序在運行時是否得到焦點。
windowstyle常量 說明
vbHide 0 窗口將隱藏,而且焦點將傳遞給隱藏窗口。 vbHide 常量在 Macintosh 平臺中不適用。
vbNormalFocus 1 窗口具備焦點且還原爲其原始大小和位置。
vbMinimizedFocus 2 窗口將顯示爲具備焦點的圖標。
vbMaximizedFocus 3 使用焦點最大化窗口。
vbNormalNoFocus 4 窗口將還原爲其最新的大小和位置。 當前活動窗口仍保持活動狀態。
vbMinimizedNoFocus 6 窗口將顯示爲圖標。 當前活動窗口仍保持活動狀態。

示例

' Specifying 1 as the second argument opens the application in 
' normal size and gives it the focus.
Dim RetVal
RetVal = Shell("C:\WINDOWS\CALC.EXE", 1)    ' Run Calculator.

▌SLN( cost, salvage, life ) as Double

返回一個 Double,它指定單個週期的資產的線性折舊額。

更多


▌Space( number ) as String

返回由指定的空格數量構成的 String。參數number是要在字符串中留出的空格數。

示例

Dim MyString
' Returns a string with 10 spaces.
MyString = Space(10)

' Insert 10 spaces between two strings.
MyString = "Hello" & Space(10) & "World"

▌Spc( n ) as

print # 語句或 print 方法一塊兒使用以定位輸出。
參數n是在顯示或打印列表中的下一個表達式以前要插入的空格數。

更多


[▌Split( expression, [ delimiter, [ limit, [ compare ]]] )](#Split) as Array

Part 說明
expression 必需。 包含子字符串和分隔符的字符串表達式。 若是 expression 是零長度字符串 (""),則 Split 返回空數組,即不包括任何元素和數據的數組。
delimiter 可選。 用於標識子字符串限制的 String 字符。 若是省略,則假定空格符 (" ") 爲分隔符。 若是 delimiter 是零長度字符串,則返回包含完整 expression 字符串的只含單一元素的數組。
limit 可選。 要返回的子字符串的數目;-1 表示返回全部子字符串。
compare 可選。 指示計算子字符串時使用的比較類型的數值。 請參閱「設置」部分以瞭解各個值。
compare常量 說明
vbUseCompareOption -1 使用 Option Compare 語句的設置來執行比較。
vbBinaryCompare 0 執行二進制比較。
vbTextCompare 1 執行文本比較。
vbDatabaseCompare 2 僅用於 Microsoft Access。 根據數據庫中的信息執行比較。

[▌StrComp( string1, string2, [ compare ] )](#StrComp) as Integer

返回指示字符串比較的結果的 Variant (Integer)。

Part 說明
string1 必需。 任何有效的字符串表達式。
string2 必需。 任何有效的字符串表達式。
compare 可選。 指定字符串比較的類型。 若是_compare_ 參數爲Null, 則會發生錯誤。 若是省略 compare,則 Option Compare 設置將決定比較的類型。
compare常量 說明
vbUseCompareOption -1 使用 Option Compare 語句的設置來執行比較。
vbBinaryCompare 0 執行二進制比較。
vbTextCompare 1 執行文本比較。
vbDatabaseCompare 2 僅用於 Microsoft Access。 根據數據庫中的信息執行比較。
If 則 StrComp 返回
string1 小於 string2 -1
string1 等於 string2 0
string1 大於 string2 1
string1 或 string2 爲 Null NULL

示例

Dim MyStr1, MyStr2, MyComp
MyStr1 = "ABCD": MyStr2 = "abcd"    ' Define variables.
MyComp = StrComp(MyStr1, MyStr2, 1)    ' Returns 0.
MyComp = StrComp(MyStr1, MyStr2, 0)    ' Returns -1.
MyComp = StrComp(MyStr2, MyStr1)    ' Returns 1.

[▌StrConv( string, conversion, [ LCID ] )](#StrConv) as String

返回按規定轉換的字符串

Part 說明
string 必需。 要轉換的字符串表達式。
conversion 必需。 Integer。 指定要執行的轉換的類型的值的總和。
LCID 可選。 LocaleID(若是與系統 LocaleID 不一樣)。 (系統 LocaleID 是默認設置)。

conversion參數

常量 說明
vbUpperCase 1 將字符串轉換爲大寫字符。
vbLowerCase 2 將字符串轉換爲小寫字符。
vbProperCase 3 將字符串中每一個單詞的第一個字母轉換爲大寫。
vbWide 4 將字符串中的窄 (單字節) 字符轉換爲寬 (雙字節) 字符。
vbNarrow 8 將字符串中的寬 (雙字節) 字符轉換爲窄 (單字節) 字符。
vbKatakana 16 將字符串中的平假名字符轉換爲片假名字符。
vbHiragana 32 將字符串中的片假名字符轉換爲平假名字符。
vbUnicode 64 使用系統的默認代碼頁將字符串轉換爲 Unicode。 (在 Macintosh 上不可用)。
vbFromUnicode 128 將字符串從 Unicode 轉換爲系統的默認代碼頁。 (在 Macintosh 上不可用)

示例

Dim i As Long
Dim x() As Byte
x = StrConv("ABCDEFG", vbFromUnicode)    ' Convert string.
For i = 0 To UBound(x)
    Debug.Print x(i)
Next

▌String( number, character ) as String

返回包含指定長度重複字符串的 Variant (String)。若是爲大於255的_字符_指定一個數字, 則字符串將使用如下公式將該數字轉換爲有效的字符代碼:字符 Mod 256。

Part 說明
number 必需;Long。 所返回字符串的長度。 若是number包含null, 則返回null 。
通配符 必需;Variant。 指定字符或字符串表達式的字符代碼,其第一個字符用於構建返回的字符串。 若是字符包含null, 則返回null 。

示例

Dim MyString
MyString = String(5, "*")    ' Returns "*****".
MyString = String(5, 42)    ' Returns "*****".
MyString = String(10, "ABC")    ' Returns "AAAAAAAAAA".

▌StrReverse( ) as String

返回一個字符串,在該字符串中,指定字符串的字符順序將被顛倒。 若是 expression 是零長度字符串 (""),則會返回零長度字符串。 若是 expression 是 Null,則會發生錯誤。


[▌Switch( expr-1, value-1, [ expr-2, value-2..., [ expr-n, value-n ]] )](#Switch) as Any

計算表達式的列表並返回與列表中第一個結果爲 True 的表達式關聯的 Variant 值或表達式。

Part 說明
expr 必需。 要計算的變體表達式。
value 必需。 要在相應表達式爲 True 時返回的值或表達式。

示例

Function MatchUp(CityName As String)
    Matchup = Switch(CityName = "London", "English", CityName _
                    = "Rome", "Italian", CityName = "Paris", "French")
End Function

▌SYD( ) as Double

返回一個 Double,該值指定某項資產在指按期間的年限總額折舊。

更多


▌Tab( n ) as void

print # 語句或print 方法一塊兒使用以定位輸出。當您使用 Tab 函數和 Print 方法時,打印圖面將劃分爲統一的固定寬度的列。 每列的寬度爲所選字體的點大小中全部字符的寬度的平均值。

示例

Debug.Print Tab(10); "10 columns from start."

▌Time( ) as Date

返回一個指示當前系統時間的 Variant (Date)。

示例

Dim MyTime
MyTime = Time    ' Return current system time.

▌Timer( ) as Single

返回表示自午夜以來已過的秒數的 Single 。

示例

Dim PauseTime, Start, Finish, TotalTime
If (MsgBox("Press Yes to pause for 5 seconds", 4)) = vbYes Then
    PauseTime = 5    ' Set duration.
    Start = Timer    ' Set start time.
    Do While Timer < Start + PauseTime
        DoEvents    ' Yield to other processes.
    Loop
    Finish = Timer    ' Set end time.
    TotalTime = Finish - Start    ' Calculate total time.
    MsgBox "Paused for " & TotalTime & " seconds"
Else
    End
End If

▌TimeSerial( hour, minute, second ) as Date

返回包含特定的小時、分鐘和秒所對應的時間的 Variant (Date)。

Part 說明
hour 必需;Variant (Integer)。 介於 0 (12:00 A.M.) 和 23 (11:00 P.M.) 之間的數字(含這兩個數字)或數值表達式。
minute 必需;Variant (Integer)。 任何數值表達式。
second 必需;Variant (Integer)。 任何數值表達式。

示例

'上午5:45:00
TimeSerial(12 - 6, -15, 0)


Dim MyTime
MyTime = TimeSerial(16, 35, 17)    ' MyTime contains serial 
    ' representation of 4:35:17 PM.

▌TimeValue( time ) as Date

返回包含時間的 Variant (Date)。 必需的time參數一般是一個字符串表達式, 表示從 0:00:00 (12:00:00 A.M.) 到 23:59:59 (11:59:59 P.M.) 的時間 (包括這兩個時間)。 可是,time 也能夠是表示該範圍內時間的任意表達式。 若是 time 包含 Null,則返回 Null。

示例

Dim MyTime
MyTime = TimeValue("4:35:17 PM")    ' Return a time.

▌TypeName( varname ) as String

返回一個提供有關變量的信息的 String。

TypeName 字符串

返回的字符串 變量
object type 類型爲 objecttype 的對象
Byte 字節值
Integer 整數
Long 長整數
Single 單精度浮點數
Double 雙精度浮點數
Currency 貨幣值
Decimal 小數值
Date 日期值
String 字符串
Boolean 布爾值
Error 錯誤值
Empty
NULL
Object 對象
Unknown 類型未知的對象
Nothing 未引用對象的對象變量

示例

' Declare variables.
Dim NullVar, MyType, StrVar As String, IntVar As Integer, CurVar As Currency
Dim ArrayVar (1 To 5) As Integer
NullVar = Null    ' Assign Null value.
MyType = TypeName(StrVar)    ' Returns "String".
MyType = TypeName(IntVar)    ' Returns "Integer".
MyType = TypeName(CurVar)    ' Returns "Currency".
MyType = TypeName(NullVar)    ' Returns "Null".
MyType = TypeName(ArrayVar)    ' Returns "Integer()".

[▌UBound( arrayname, [ dimension ] )](#UBound) as Long

返回包含指定的數組維度的最大可用下標的Long數據類型。

示例

Dim Upper
Dim MyArray(1 To 10, 5 To 15, 10 To 20)    ' Declare array variables.
Dim AnyArray(10)
Upper = UBound(MyArray, 1)    ' Returns 10.
Upper = UBound(MyArray, 3)    ' Returns 20.
Upper = UBound(AnyArray)      ' Returns 10.

▌UCase( string ) as String

返回包含轉換爲大寫字母的指定字符串的 Variant (String)。若是_字符串包含 Null,則返回 Null。

示例

Dim LowerCase, UpperCase
LowerCase = "Hello World 1234"    ' String to convert.
UpperCase = UCase(LowerCase)    ' Returns "HELLO WORLD 1234".

▌VarType( varname ) as Integer

返回一個整數, 指示變量的子類型或對象的默認屬性的類型。

返回值
要麼是下列常量之一, 要麼返回其中一個數的總和。

常量 說明
vbEmpty 0 空(未初始化)
vbNull 1 Null(不是有效數據)
vbInteger 2 Integer
vbLong 3 長整數
vbSingle 4 單精度浮點數
vbDouble 5 雙精度浮點數
vbCurrency 6 貨幣值
vbDate 7 日期值
vbString 8 String
vbObject 9 對象
vbError 10 錯誤值
vbBoolean 11 布爾值
vbVariant 12 Variant(僅與變量的數組一塊兒使用)
vbDataObject 13 數據訪問對象
vbDecimal 14 小數值
vbByte 17 字節值
vbLongLong 20 LongLong整數 (僅在64位平臺上有效)
vbUserDefinedType 36 包含用戶定義類型的變量
vbArray 8192 數組 (此函數返回時老是添加到另外一個常量)

示例

Dim MyCheck
Dim IntVar, StrVar, DateVar, AppVar, ArrayVar
' Initialize variables.
IntVar = 459: StrVar = "Hello World": DateVar = #2/12/1969#
Set AppVar = Excel.Application
ArrayVar = Array("1st Element", "2nd Element")
' Run VarType function on different types.
MyCheck = VarType(IntVar)   ' Returns 2.
MyCheck = VarType(DateVar)  ' Returns 7.
MyCheck = VarType(StrVar)   ' Returns 8.
MyCheck = VarType(AppVar)   ' Returns 8 (vbString)
                            ' even though AppVar is an object.
MyCheck = VarType(ArrayVar) ' Returns 8204 which is
                            ' `8192 + 12`, the computation of
                            ' `vbArray + vbVariant`.

[▌Weekday( date、[ firstdayofweek ] )](#Weekday) as Integer

返回包含一個整數的 Variant (Integer),該整數表示星期數。

Part 說明
date 必需。 能夠表示日期的 Variant、數值表達式、字符串表達式或任意組合。 若是 date 包含 Null,則返回 Null。

firstdayofweek 可選。 一個指定一週的第一天的常量。 若是不指定,則假定爲 vbSunday。

firstdayofweek 參數,weekday返回值

常量 說明
vbSunday 1 週日(默認)
vbMonday 2 星期一
vbTuesday 3 星期二
vbWednesday 4 星期三
vbThursday 5 星期四
vbFriday 6 星期五
vbSaturday 7 星期六

示例

Dim MyDate, MyWeekDay
MyDate = #February 12, 1969#    ' Assign a date.
MyWeekDay = Weekday(MyDate)    ' MyWeekDay contains 4 because 
    ' MyDate represents a Wednesday.

▌WeekdayName( weekday, abbreviate, firstdayofweek ) as

Part 說明
weekday 必需。 表示一週中的某一天的數字標識。 一週中的每一天的 Numeric 值取決於 firstdayofweek 設置的設置。
abbreviate 可選。 指示一週中的每一天的名稱是否爲縮寫的 Boolean 值。 若是省略,則默認值爲 False,其意味着一週中的每一天的名稱不是縮寫的。
firstdayofweek 可選。 指示一週的第一天的 Numeric 值。 請參閱「設置」部分以瞭解各個值。

firstdayofweek 參數

常量 說明
vbSunday 1 週日(默認)
vbMonday 2 星期一
vbTuesday 3 星期二
vbWednesday 4 星期三
vbThursday 5 星期四
vbFriday 6 星期五
vbSaturday 7 星期六

▌Year( date ) as Integer

返回包含表示年的整數的變量(整數)。

示例

Dim MyDate, MyYear
MyDate = #February 12, 1969#    ' Assign a date.
MyYear = Year(MyDate)    ' MyYear contains 1969.

VB語句

[AppActivate title、[ wait ]](#AppActivate)

Part 說明
title 必需。 指定要激活的應用程序窗口的標題欄中的標題的字符串表達式。 可以使用 Shell 函數返回的任務 ID 代替 title 激活應用程序。
wait 可選。 指定在激活另外一個應用程序以前,調用應用程序是否具備焦點的 Boolean 值。 若是爲 False(默認值),則將當即激活指定應用程序,即便調用應用程序沒有焦點也是如此。 若是爲 True, 則調用應用程序將一直等待, 直到它得到焦點, 而後激活指定的應用程序。

示例

Dim MyAppID, ReturnValue 
AppActivate "Microsoft Word" ' Activate Microsoft 
 ' Word. 
 
' AppActivate can also use the return value of the Shell function. 
MyAppID = Shell("C:\WORD\WINWORD.EXE", 1) ' Run Microsoft Word. 
AppActivate MyAppID ' Activate Microsoft 
 ' Word. 
 
' You can also use the return value of the Shell function. 
ReturnValue = Shell("c:\EXCEL\EXCEL.EXE",1) ' Run Microsoft Excel. 
AppActivate ReturnValue ' Activate Microsoft 
 ' Excel.

Beep

蜂鳴音

示例

Dim I 
For I = 1 To 3 ' Loop 3 times. 
 Beep ' Sound a tone. 
Next I

[[ Call ] name [ argumentlist ]](#Call)

Part 說明
Call 可選;關鍵字。 若是指定,則必須將_ argumentlist_ 用括號括起。例如:Call MyProc(0)
name 必需。 要調用的過程的名稱。
argumentlist 可選。 要傳遞到過程的變量、數組或表達式的以逗號分隔的列表。 argumentlist 的組件可能包含關鍵字 ByVal 或 ByRef,這兩個關鍵字介紹調用過程如何對待參數。可是,ByVal 和 ByRef 僅當調用 DLL 過程時才能與 Call 一塊兒使用。 在 Macintosh 上,ByVal 和 ByRef 可在發出對 Macintosh 代碼資源的調用時與 Call 一塊兒使用。

示例

' Call a Sub procedure. 
Call PrintToDebugWindow("Hello World")     
' The above statement causes control to be passed to the following 
' Sub procedure. 
Sub PrintToDebugWindow(AnyString) 
    Debug.Print AnyString    ' Print to the Immediate window. 
End Sub 
 
' Call an intrinsic function. The return value of the function is 
' discarded. 
Call Shell(AppName, 1)    ' AppName contains the path of the  
        ' executable file. 
 
' Call a Microsoft Windows DLL procedure. The Declare statement must be  
' Private in a Class Module, but not in a standard Module. 
Private Declare Sub MessageBeep Lib "User" (ByVal N As Integer) 
Sub CallMyDll() 
    Call MessageBeep(0)    ' Call Windows DLL procedure. 
    MessageBeep 0    ' Call again without Call keyword. 
End Sub

ChDir path

必需的path參數是一個字符串表達式, 用於標識哪一個目錄或文件夾將成爲新的默認目錄或文件夾。 path 能夠包含驅動器。 若是未指定驅動器,ChDir 會更改當前驅動器上的默認目錄或文件夾。

示例

ChDir "D:\TMP" ' Make "D:\TMP" the current folder. 
ChDrive "D"    ' Make "D" the current drive.

ChDir "MacDrive:Tmp" ' On the Macintosh.

ChDir ".." ' Moves up one directory in Microsoft Windows. 
ChDir "::" ' Moves up one directory on the Macintosh.

' Assume "C:" is the current drive. The following statement changes 
' the default directory on drive "D:". "C:" remains the current drive. 
ChDir "D:\WINDOWS\SYSTEM"

ChDrive drive

更改當前驅動器。

示例

ChDrive "D" ' Make "D" the current drive.

Close

結束對使用 Open 語句打開的文件的輸入/輸出 (i/o)。

示例

Dim I, FileName 
For I = 1 To 3 ' Loop 3 times. 
 FileName = "TEST" & I ' Create file name. 
 Open FileName For Output As #I ' Open file. 
 Print #I, "This is a test." ' Write string to file. 
Next I 
Close ' Close all 3 open files.

[[ Public | Private ] Const constname [ As type ] = expression](#Const)

示例

' Constants are Private by default. 
Const MyVar = 459 
 
' Declare Public constant. 
Public Const MyString = "HELP" 
 
' Declare Private Integer constant. 
Private Const MyInt As Integer = 5 
 
' Declare multiple constants on same line. 
Const MyStr = "Hello", MyDouble As Double = 3.4567

Declare

在模塊級別使用, 以聲明對動態連接庫(DLL) 中的外部過程的引用。

更多

示例

#If VBA7 Then 
Declare PtrSafe Sub... 
#Else 
Declare Sub... 
#EndIf

Deftype

在模塊級別使用, 以設置變量的默認數據類型、傳遞給過程的參數以及函數屬性 Get 過程的返回類型, 它們的名稱以指定的字符。

更多


[DeleteSetting appname、 section、[ key ]](#DeleteSetting)

從應用程序在 Windows 註冊表(在 Macintosh 上)中的註冊項或應用程序的初始化文件中的信息中刪除節或項設置。

更多


Dim

聲明變量和分配存儲空間。
Dim [ WithEvents ] varname [ ( [ subscripts ] ) ] [ As [ New ] type ] [ , [ WithEvents ] varname [ ( [ subscripts ] ) ] [ As [ New ]type ]] . . .

示例

'默認狀況下,將AnyValue和MyValue聲明爲Variant並帶有值設置爲空。
Dim AnyValue, MyValue 
 
' 明確聲明一個Integer類型的變量。
Dim Number As Integer 
 
'一行上有多個聲明。由於省略了它的類型,AnotherVar是Variant類型
Dim AnotherVar, Choice As Boolean, BirthDate As Date 
 
'DayArray是Variants數組,其中索引了51個元素,從'0到50,假設對於如下狀況,「選項庫」設置爲0(默認值)當前模塊。
Dim DayArray(50) 
 
' 矩陣是整數的二維數組。
Dim Matrix(3, 4)As Integer 
 
' MyMatrix是具備顯式形式的雙精度三維數組的界限。
Dim MyMatrix(1 To 5, 4 To 9, 3 To 5)As Double 
 
' BirthDay是一個日期數組,索引從1到10。
Dim BirthDay(1 To 10)As Date 
 
'MyArray是變量的動態數組。
Dim MyArray()

Do...Loop

循環語句

示例

Public Sub LoopExample()
    Dim Check As Boolean, Counter As Long, Total As Long
    Check = True: Counter = 0: Total = 0 ' Initialize variables.
    Do ' Outer loop.
        Do While Counter < 20 ' Inner Loop
            Counter = Counter + 1 ' Increment Counter.
            If Counter Mod 10 = 0 Then ' Check in with the user on every multiple of 10.
                Check = (MsgBox("Keep going?", vbYesNo) = vbYes) ' Stop when user click's on No
                If Not Check Then Exit Do ' Exit inner loop.
            End If
        Loop
        Total = Total + Counter ' Exit Do Lands here.
        Counter = 0
    Loop Until Check = False ' Exit outer loop immediately.
    MsgBox "Counted to: " & Total
End Sub

End

結束語句

語句 說明
End 當即終止執行。 永遠不須要它自己, 但能夠放置在過程當中的任何位置以結束代碼執行, 關閉使用Open 語句打開的文件, 並清除變量。
End Function 結束Function 語句所必需的。
End If 須要結束塊If .。。而後 .。。Else 語句。
End Property 須要結束Property Let、 Property Get 或property Set 過程。
End Select 結束Select Case 語句所必需的。
End Sub 結束Sub 語句所必需的。
End Type 結束用戶定義的類型定義 (type 語句) 所必需的。
End With 須要結束With 語句。

示例

Sub Form_Load 
  Dim Password, Pword 
  PassWord = "Swordfish" 
  Pword = InputBox("Type in your password") 
  If Pword <> PassWord Then 
    MsgBox "Sorry, incorrect password" 
    End
  End If
End Sub

Enum

枚舉語句

[ Public | Private ] Enumname

membername [= constantexpression ]

membername [= constantexpression ]

End Enum

Part 說明
Public 可選。 指定 Enum 類型在整個項目內可見。 Enum 類型默認狀況下是 Public。
Private 可選。 指定 Enum 類型僅在出現該類型的模塊內可見。
name 必需。 Enum 類型的名稱。 name 必須是有效的 Visual Basic 標識符並在聲明 Enum 類型的變量或參數時被指定爲類型。
membername 必需。 用於指定名稱的有效 Visual Basic 標識符,可根據該名稱得出 Enum 類型組成元素的名稱。
constantexpression 可選。 元素值(計算爲 Long)。 若是未指定_constantexpression_ , 則分配的值爲零 (若是是第一個_成員名稱_), 或者1大於前面的_成員名稱_的值。

示例

Enum SecurityLevel 
 IllegalEntry = -1 
 SecurityLevel1 = 0 
 SecurityLevel2 = 1 
End Enum

Public Enum InterfaceColors 
 icMistyRose = &HE1E4FF& 
 icSlateGray = &H908070& 
 icDodgerBlue = &HFF901E& 
 icDeepSkyBlue = &HFFBF00& 
 icSpringGreen = &H7FFF00& 
 icForestGreen = &H228B22& 
 icGoldenrod = &H20A5DA& 
 icFirebrick = &H2222B2& 
End Enum

Erase arraylist

從新初始化固定大小數組的元素並釋放動態數組存儲空間。

數組類型 對固定數組元素的擦除效果
固定數值數組 將每一個元素設置爲 0。
固定字符串數組(可變長度) 將每一個元素設置爲零長度字符串 ("")。
固定字符串數組(固定長度) 將每一個元素設置爲 0。
固定 Variant 數組 將每一個元素設置爲 Empty。
用戶定義類型的數組 設置每一個元素,就好像它是單獨的變量同樣。
對象的數組。 將每一個元素設置爲特定值 Nothing。

示例

' Declare array variables. 
Dim NumArray(10) As Integer ' Integer array. 
Dim StrVarArray(10) As String ' Variable-string array. 
Dim StrFixArray(10) As String * 10 ' Fixed-string array. 
Dim VarArray(10) As Variant ' Variant array. 
Dim DynamicArray() As Integer ' Dynamic array. 
ReDim DynamicArray(10) ' Allocate storage space. 
Erase NumArray ' Each element set to 0. 
Erase StrVarArray ' Each element set to zero-length 
 ' string (""). 
Erase StrFixArray ' Each element set to 0. 
Erase VarArray ' Each element set to Empty. 
Erase DynamicArray ' Free memory used by array.

Error errornumber

模擬錯誤的發生。

示例

On Error Resume Next ' Defer error handling. 
Error 11 ' Simulate the "Division by zero" error.

[[ Public ] Event procedurename [ (arglist) ]](#Event)

Part 說明
Public 可選。 指定事件在整個項目中是可見的。 默認狀況下,「事件」** 類型爲 Public。 請注意,事件只能在聲明它們的模塊中引起。
procedurename 必需。 事件名稱;遵循標準變量命名約定。

arglist 參數具備如下語法和組成部分:

[ ByVal | ByRef ]varname[()] [ As type ]

Part 說明
ByVal 可選。 指示參數經過值傳遞。
ByRef 可選。 指示按引用傳遞參數。 ByRef 在 Visual Basic 中是默認值。
varname 必需。 表示傳遞給過程的參數的變量名稱;遵循標準變量命名約定。
type 可選。 傳遞給過程的參數的數據類型;多是 Byte、Boolean、Integer、Long、Currency、Single、Double、Decimal(當前不受支持)、Date、String(僅可變長度)、Object、Variant、用戶定義的類型或某對象類型。

示例

' Declare an event at module level of a class module 
 
Event LogonCompleted (UserName as String) 
 
Sub 
 RaiseEvent LogonCompleted("AntoineJan") 
End Sub

更多


Exit

退出 Do…Loop 塊、 For…Next 、 Function 、 Sub 或 Property 代碼。

語句 說明
Exit Do 提供一種退出Do .。。Loop 語句。 只能在 Do...Loop 語句內使用它。 Exit Do 將控制權轉移給 Loop 語句以後的語句。 在嵌套的 Do...Loop 語句內使用時,Exit Do 將控制權轉移給發生 Exit Do 的循環的上一嵌套層中的循環。
Exit For 提供一種退出 For 循環的方式。 它只能用於For .。。NextFor Each .。。Next 循環。 Exit For 將控制權轉移給 Next 語句以後的語句。 在嵌套的 For 循環內使用時,Exit For 將控制權轉移給發生 Exit For 的循環的上一嵌套層中的循環。
Exit Function 當即退出出現它的Function 過程。 繼續執行稱爲 Function 的語句以後的語句。
Exit Property 當即退出顯示它的屬性 過程。 繼續執行稱爲 Property 的過程以後的語句。
Exit Sub 當即退出出現它的Sub 過程。 繼續執行稱爲 Sub 的過程以後的語句。

示例

Sub ExitStatementDemo() 
Dim I, MyNum 
 Do ' Set up infinite loop. 
 For I = 1 To 1000 ' Loop 1000 times. 
 MyNum = Int(Rnd * 1000) ' Generate random numbers. 
 Select Case MyNum ' Evaluate random number. 
 Case 7: Exit For ' If 7, exit For...Next. 
 Case 29: Exit Do ' If 29, exit Do...Loop. 
 Case 54: Exit Sub ' If 54, exit Sub procedure. 
 End Select 
 Next I 
 Loop 
End Sub

FileCopy source, destination

複製文件。

Part 說明
source 必需。 指定要複製的文件的名稱的字符串表達式。 source 可包含目錄或文件夾和驅動器。
destination 必需。 指定目標文件名的字符串表達式。 destination 可包括目錄或文件夾和驅動器。

示例

Dim SourceFile, DestinationFile 
SourceFile = "SRCFILE" ' Define source file name. 
DestinationFile = "DESTFILE" ' Define target file name. 
FileCopy SourceFile, DestinationFile ' Copy source to target.

For Each...Next

對數組或集合中的每一個元素重複一組語句。

For Each element In group

[ statements ]

[ Exit For ]

[ statements ]

Next [ element ]

示例

Dim Found, MyObject, MyCollection 
Found = False    ' Initialize variable. 
For Each MyObject In MyCollection    ' Iterate through each element.  
    If MyObject.Text = "Hello" Then    ' If Text equals "Hello". 
        Found = True    ' Set Found to True. 
        Exit For    ' Exit loop. 
    End If 
Next

For...Next

將一組語句重複指定的次數。

For counter = start To end [ Step step ]

[ statements ]

[ Exit For ]

[ statements ]

Next [ counter ]

Part 說明
counter 必需。 用做循環計數器的數值變量。 該變量不能是布爾值或數組元素。
start 必需。 counter 的初始值。
end 必需。 counter 的最終值。
step 可選。 counter 每次經過循環時更改的量。 若是不指定,step 默認爲 1。
statements 可選。 For 和 Next 之間執行指定次數的一個或多個語句。

示例

Dim Words, Chars, MyString 
For Words = 10 To 1 Step -1 ' Set up 10 repetitions. 
 For Chars = 0 To 9 ' Set up 10 repetitions. 
 MyString = MyString & Chars ' Append number to string. 
 Next Chars ' Increment counter 
 MyString = MyString & " " ' Append a space. 
Next Words

Function

聲明構成Function 過程主體的名稱、參數和代碼。

[Public | Private | Friend] [ Static ] Function name [ ( arglist ) ] [ As type ]
[ statements ]
[ name = expression ]
[ Exit Function ]
[ statements ]
[ name = expression ]
End Function

示例

' The following user-defined function returns the square root of the 
' argument passed to it. 
Function CalculateSquareRoot(NumberArg As Double) As Double 
 If NumberArg < 0 Then ' Evaluate argument. 
  Exit Function ' Exit to calling procedure. 
 Else 
  CalculateSquareRoot = Sqr(NumberArg) ' Return square root. 
 End If 
End Function
Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs()) 
Dim ReturnValue 
' If the function is invoked as follows: 
ReturnValue = CalcSum(4, 3, 2, 1) 
' Local variables are assigned the following values: FirstArg = 4, 
' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default 
' lower bound for arrays = 1.

[Get [ # ] filenumber, [ recnumber ], varname](#Get)

將打開的磁盤文件中的數據讀取到變量中。

Part 說明
filenumber 必需。 任何有效的文件編號。
recnumber 可選。 Variant (Long)。 從其開始讀取的記錄編號(Random 模式文件)或字節數(Binary 模式文件)。
varname 必需。 將數據讀入的有效變量名稱。

示例

Type Record ' Define user-defined type. 
 ID As Integer 
 Name As String * 20 
End Type 
 
Dim MyRecord As Record, Position ' Declare variables. 
' Open sample file for random access. 
Open "TESTFILE" For Random As #1 Len = Len(MyRecord) 
' Read the sample file using the Get statement. 
Position = 3 ' Define record number. 
Get #1, Position, MyRecord ' Read third record. 
Close #1 ' Close file.

If...Then...Else

根據表達式的值,有條件地執行一組語句。

示例

Sub ControlProcessor(MyControl As Control) 
 If TypeOf MyControl Is CommandButton Then 
 Debug.Print "You passed in a " & TypeName(MyControl) 
 ElseIf TypeOf MyControl Is CheckBox Then 
 Debug.Print "You passed in a " & TypeName(MyControl) 
 ElseIf TypeOf MyControl Is TextBox Then 
 Debug.Print "You passed in a " & TypeName(MyControl) 
 End If 
End Sub

[Implements [ InterfaceName | Class ]](#Implements)

指定將在其所在的類模塊中實現的接口或類。

更多


Input #filenumber, varlist

從打開的順序文件中讀取數據並將此數據分配給變量。

Part 說明
filenumber 必需。 任何有效的文件編號。
varlist 必需。 從文件中讀取的被分配值的以逗號分隔的變量列表, 不能是數組或對象變量。 可是,可使用描述數組或用戶定義類型的元素的變量。

示例

Dim MyString, MyNumber 
Open "TESTFILE" For Input As #1    ' Open file for input. 
Do While Not EOF(1)    ' Loop until end of file. 
    Input #1, MyString, MyNumber    ' Read data into two variables. 
    Debug.Print MyString, MyNumber    ' Print data to the Immediate window. 
Loop 
Close #1    ' Close file.

Kill pathname

刪除磁盤上的文件。若要刪除目錄, 請使用RmDir 語句。

示例

Kill MacID("TEXT")

' Assume TESTFILE is a file containing some data. 
Kill "TestFile" ' Delete file. 
 
' Delete all *.TXT files in current directory. 
Kill "*.TXT"

Let
將表達式的值賦給變量或屬性。

示例

Dim MyStr, MyInt 
MyStr = "Hello World" 
MyInt = 5

Line Input

從打開的順序文件中讀取一行並將其分配給String 變量。

Part 說明
filenumber 必需。 任何有效的文件編號。
varname 必需。 有效 Variant 或 String 變量名稱。

示例

Dim TextLine 
Open "TESTFILE" For Input As #1 ' Open file. 
Do While Not EOF(1) ' Loop until end of file. 
 Line Input #1, TextLine ' Read line into variable. 
 Debug.Print TextLine ' Print to the Immediate window. 
Loop 
Close #1 ' Close file.

Loadobject

加載一個對象但不顯示該對象。

示例

' This is the Initialize event procedure for UserForm1 
Private Sub UserForm_Initialize() 
 Load UserForm2 
 UserForm2.Show 
End Sub 
' This is the Click event of UserForm2 
Private Sub UserForm_Click() 
 UserForm2.Hide 
End Sub 
 
' This is the click event for UserForm1 
Private Sub UserForm_Click() 
 UserForm2.Show 
End Sub

Lock、Unlock

Lock [ # ] filenumber, [ recordrange ] . . .

Unlock [ # ] filenumber, [ recordrange ]

設置 說明
recnumber 要開始鎖定或解鎖的記錄編號(Random 模式文件)或字節編號(Binary 模式文件)。
start 要鎖定或解鎖的第一個記錄或字節的編號。
end 要鎖定或解鎖的最後一個記錄或字節的編號。

示例

Type Record    ' Define user-defined type. 
    ID As Integer 
    Name As String * 20 
End Type 
 
Dim MyRecord As Record, RecordNumber    ' Declare variables. 
' Open sample file for random access. 
Open "TESTFILE" For Random Shared As #1 Len = Len(MyRecord) 
RecordNumber = 4    ' Define record number. 
Lock #1, RecordNumber    ' Lock record. 
Get #1, RecordNumber, MyRecord    ' Read record. 
MyRecord.ID = 234    ' Modify record. 
MyRecord.Name = "John Smith" 
Put #1, RecordNumber, MyRecord    ' Write modified record. 
Unlock #1, RecordNumber    ' Unlock current record. 
Close #1    ' Close file.

LSet

在字符串變量中將字符串左對齊,或將一個用戶定義類型的變量複製到其餘用戶定義類型的另外一個變量。

LSet stringvar = string

LSet varname1 = varname2

Part 說明
stringvar 必需。 字符串變量的名稱。
string 必需。 在 stringvar 中左對齊的字符串表達式。
varname1 必需。 要複製到的用戶定義類型的變量名。
varname2 必需。 要從中複製的用戶定義類型的變量名。

示例

Dim MyString 
MyString = "0123456789" ' Initialize string. 
Lset MyString = "<-Left" ' MyString contains "<-Left ".

[Mid(stringvar、 start、[ length ])= string](#Mid)
將stringvar中指定數量的字符替換爲其餘字符串中的字符。

Part 說明
stringvar 必需。 要修改的字符串變量的名稱。
start 必需;Variant (Long)。 stringvar 中開始文本替換的字符位置。
Length 可選;Variant (Long)。 要替換的字符數。 若是省略,則將使用全部 string。
string 必需。 用於替換 stringvar 的字符串表達式。

示例

Dim MyString 
MyString = "The dog jumps" ' Initialize string. 
Mid(MyString, 5, 3) = "fox" ' MyString = "The fox jumps". 
Mid(MyString, 5) = "cow" ' MyString = "The cow jumps". 
Mid(MyString, 5) = "cow jumped over" ' MyString = "The cow jumpe". 
Mid(MyString, 5, 3) = "duck" ' MyString = "The duc jumpe".

MkDir path

新建目錄或文件夾。

示例

MkDir "MYDIR" ' Make new directory or folder.

Nameoldpathname As newpathname

重命名磁盤文件、目錄或文件夾。

示例

Dim OldName, NewName 
OldName = "OLDFILE": NewName = "NEWFILE" ' Define file names. 
Name OldName As NewName ' Rename file. 
 
OldName = "C:\MYDIR\OLDFILE": NewName = "C:\YOURDIR\NEWFILE" 
Name OldName As NewName ' Move and rename file.

On Error

啓用錯誤處理例程並指定該例程在程序中的位置;還可用於禁用錯誤處理例程。

On Error GoTo line

On Error Resume Next

On Error GoTo 0

更多


Open

啓用對文件的輸入/輸出 (I/O)。

Open pathname For mode [ Access access ] [ lock ] As [ # ] filenumber [ Len = reclength ]

Part 說明
pathname 必需。 指定文件名的字符串表達式,可包括目錄或文件夾和驅動器。
mode 必需。 指定文件模式的關鍵字:Append、Binary、Input、Output 或 Random。 若是未指定,則以 Random 訪問模式打開文件。
access 可選。 指定可對打開的文件執行的操做的關鍵字:Read、Write 或 Read Write。
lock 可選。 指定由其餘進程限制在打開的文件上的操做的關鍵字:共享、鎖定讀取、鎖定寫入和鎖定讀寫。
filenumber 必需。 一個有效文件號,範圍爲 1 到 511(含 1 和 511)。 使用FreeFile 函數可獲取下一個可用的文件編號。
reclength 可選。 小於或等於 32,767(字節)的數。 對於以隨機訪問模式打開的文件,此值爲記錄長度。 對於序列文件,此值爲緩衝的字符數。

更多


Option Base { 0 | 1 }

在模塊級別使用, 以聲明數組下標的默認下限。

示例

Option Base 1 ' Set default array subscripts to 1. 
 
Dim Lower 
Dim MyArray(20), TwoDArray(3, 4) ' Declare array variables. 
Dim ZeroArray(0 To 5) ' Override default base subscript. 
' Use LBound function to test lower bounds of arrays. 
Lower = LBound(MyArray) ' Returns 1. 
Lower = LBound(TwoDArray, 2) ' Returns 1. 
Lower = LBound(ZeroArray) ' Returns 0.

Option Compare { Binary | Text | Database }

在模塊級別使用, 以聲明在比較字符串數據時要使用的默認比較方法。

示例

' Set the string comparison method to Binary. 
Option Compare Binary ' That is, "AAA" is less than "aaa". 
' Set the string comparison method to Text. 
Option Compare Text ' That is, "AAA" is equal to "aaa".

Option Explicit

在模塊級別使用, 以強制顯式聲明該模塊中的全部變量。

示例

Option Explicit ' Force explicit variable declaration. 
Dim MyVar ' Declare variable. 
MyInt = 10 ' Undeclared variable generates error. 
MyVar = 10 ' Declared variable does not generate error.

Option Private

在容許跨多個項目引用的主機應用程序中使用時,「Option Private Module」 防止模塊的內容在其項目外被應用。 在不容許此類引用的主機應用程序(如 Visual Basic 的獨立版本)中,「Option Private」無效。

示例


[Print #filenumber, [ outputlist ]](#Print)

Part 說明
filenumber 必需。 任何有效的文件編號。
outputlist 可選。 要打印的表達式或表達式列表。

outputlist參數:

[{ Spc(n) | Tab [ (n) ]}] [ expression ] [ charpos ]

設置 說明
Spc(n) 用於在輸出中插入空格,其中 n 爲要插入的空格數。
Tab(n) 用於將插入點定位到絕對列號,其中 n 爲列號。 使用不帶參數的 Tab 可將插入點定位到下一個打印區域的起始位置。
expression 要打印的數字表達式或字符串表達式。
charpos 指定下一個字符的插入點。 使用分號可將插入點定位到上一個顯示字符的正後方。 使用Tab(n) 將插入點定位到一個絕對列號。 使用不帶參數的 Tab 可將插入點定位到下一個打印區域的起始位置。 若是省略 charpos,將在下一行上打印下一個字符。

示例

Open "TESTFILE" For Output As #1 ' Open file for output. 
Print #1, "This is a test" ' Print text to file. 
Print #1, ' Print blank line to file. 
Print #1, "Zone 1"; Tab ; "Zone 2" ' Print in two print zones. 
Print #1, "Hello" ; " " ; "World" ' Separate strings with space. 
Print #1, Spc(5) ; "5 leading spaces " ' Print five leading spaces. 
Print #1, Tab(10) ; "Hello" ' Print word at column 10. 
 
' Assign Boolean, Date, Null and Error values. 
Dim MyBool, MyDate, MyNull, MyError 
MyBool = False : MyDate = #February 12, 1969# : MyNull = Null 
MyError = CVErr(32767) 
' True, False, Null, and Error are translated using locale settings of 
' your system. Date literals are written using standard short date 
' format. 
Print #1, MyBool ; " is a Boolean value" 
Print #1, MyDate ; " is a date" 
Print #1, MyNull ; " is a null value" 
Print #1, MyError ; " is an error value" 
Close #1 ' Close file.

Private

在模塊級別使用, 以聲明私有變量並分配存儲空間。

Private [ WithEvents ] varname [ ( [ subscripts ] ) ] [ As [ New ] type ]
[ , [ WithEvents ] varname [ ( [ subscripts ] ) ] [ As [ New ] type ]] . . .

示例

Private NumberOfEmployees As Integer
Private X As New Worksheet
Private Number As Integer ' Private Integer variable. 
Private NameArray(1 To 5) As String ' Private array variable. 
' Multiple declarations, two Variants and one Integer, all Private. 
Private MyVar, YourVar, ThisVar As Integer

Property Get

聲明構成屬性過程的主體的名稱、參數和代碼, 這將獲取屬性的值。

示例

Dim CurrentColor As Integer 
Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3 
 
' Returns the current color of the pen as a string. 
Property Get PenColor() As String 
 Select Case CurrentColor 
 Case RED 
 PenColor = "Red" 
 Case GREEN 
 PenColor = "Green" 
 Case BLUE 
 PenColor = "Blue" 
 End Select 
End Property 
 
' The following code gets the color of the pen 
' calling the Property Get procedure. 
ColorName = PenColor

Property Let

聲明構成屬性過程的主體的名稱、參數和代碼, 這將爲屬性分配值。

示例

Dim CurrentColor As Integer 
Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3 
 
' Set the pen color property for a Drawing package. 
' The module-level variable CurrentColor is set to 
' a numeric value that identifies the color used for drawing. 
Property Let PenColor(ColorName As String) 
 Select Case ColorName ' Check color name string. 
 Case "Red" 
 CurrentColor = RED ' Assign value for Red. 
 Case "Green" 
 CurrentColor = GREEN ' Assign value for Green. 
 Case "Blue" 
 CurrentColor = BLUE ' Assign value for Blue. 
 Case Else 
 CurrentColor = BLACK ' Assign default value. 
 End Select 
End Property 
 
' The following code sets the PenColor property for a drawing package 
' by calling the Property let procedure. 
 
PenColor = "Red"

Property Set

聲明構成屬性過程的主體的名稱、參數和代碼, 以設置對對象的引用。

示例

' The Pen property may be set to different Pen implementations. 
Property Set Pen(P As Object) 
 Set CurrentPen = P ' Assign Pen to object. 
End Property

Public

在模塊級別使用, 以聲明公共變量和分配存儲空間。

示例

Public NumberOfEmployees As Integer
Public X As New Worksheet

Put

將數據從變量寫入磁盤文件。

示例

Put #4,,FileBuffer

RaiseEvent

觸發在類、窗體或文檔中的模塊級別聲明的事件。

示例

' Declare an event at module level of a class module 
Event LogonCompleted (UserName as String) 
 
Sub 
 ' Raise the event. 
 RaiseEvent LogonCompleted ("AntoineJan") 
End Sub

[Randomize [ number ]](#Randomize)

初始化隨機數字生成器。若是不使用 Randomize ,則當第一次調用 Rnd 函數(不具備參數)時,它將使用與種子相同的數字,而且接下來會將最後生成的數字用做種子值。(若要重複隨機數字的順序,請先當即調用帶負參數的 Rnd ,而後再將 Randomize 與數值參數一塊兒使用。 對與 number 相同的值使用 Randomize 不會重複上一個順序。)

示例

Dim MyValue 
Randomize ' Initialize random-number generator. 
 
MyValue = Int((6 * Rnd) + 1) ' Generate random value between 1 and 6.

ReDim

在過程級使用, 用於爲動態數組變量從新分配存儲空間。

示例

ReDim X(10, 10, 10) 
. . . 
ReDim Preserve X(10, 10, 15)

Dim MyArray() As Integer ' Declare dynamic array. 
Redim MyArray(5) ' Allocate 5 elements. 
For I = 1 To 5 ' Loop 5 times. 
 MyArray(I) = I ' Initialize array. 
Next I

Redim MyArray(10) ' Resize to 10 elements. 
For I = 1 To 10 ' Loop 10 times. 
 MyArray(I) = I ' Initialize array. 
Next I

Redim Preserve MyArray(15) ' Resize to 15 elements.

Rem comment

用於包括程序中的解釋性備註。

示例

Dim MyStr1, MyStr2 
MyStr1 = "Hello": Rem Comment after a statement separated by a colon. 
MyStr2 = "Goodbye" ' This is also a comment; no colon is needed.

Reset

關閉使用Open 語句打開的全部磁盤文件。Reset 語句關閉經過 Open 語句打開的全部活動文件,並將全部文件緩存的內容寫入磁盤。

示例

Dim FileNumber 
For FileNumber = 1 To 5 ' Loop 5 times. 
 ' Open file for output. FileNumber is concatenated into the string 
 ' TEST for the file name, but is a number following a #. 
 Open "TEST" & FileNumber For Output As #FileNumber 
 Write #FileNumber, "Hello World" ' Write data to file. 
Next FileNumber 
Reset ' Close files and write contents 
 ' to disk.

Resume
語法

Resume [ 0 ]

Resume Next

Resume line

示例

Sub ResumeStatementDemo() 
 On Error GoTo ErrorHandler ' Enable error-handling routine. 
 Open "TESTFILE" For Output As #1 ' Open file for output. 
 Kill "TESTFILE" ' Attempt to delete open file. 
 Exit Sub ' Exit Sub to avoid error handler. 
ErrorHandler: ' Error-handling routine. 
 Select Case Err.Number ' Evaluate error number. 
  Case 55 ' "File already open" error. 
   Close #1 ' Close open file. 
  Case Else 
   ' Handle other situations here.... 
 End Select 
 Resume ' Resume execution at same line that caused the error. 
End Sub

RmDir path

示例

' Assume that MYDIR is an empty directory or folder. 
RmDir "MYDIR" ' Remove MYDIR.

RSet stringvar = string

在字符串變量中靠右對齊字符串。

Part 說明
stringvar 必需。 字符串變量的名稱。
string 必需。 要在 stringvar 內靠右對齊的字符串表達式。

示例

Dim MyString 
MyString = "0123456789"   ' Initialize string. 
Rset MyString = "Right->" ' MyString contains " Right->".

SaveSettingappname、 section、 key、 setting

在 Windows 註冊表的應用程序條目中保存或建立應用程序項,或在 Macintosh 上,在應用程序的初始化文件中保存或建立信息。

示例

' Place some settings in the registry. 
SaveSetting appname := "MyApp", section := "Startup", _ 
 key := "Top", setting := 75 
SaveSetting "MyApp","Startup", "Left", 50 
' Remove section and all its settings from registry. 
DeleteSetting "MyApp", "Startup"

[Seek[ # ] filenumber, position](#Seek)

在使用Open 語句打開的文件中設置下一次讀取/寫入操做的位置。

更多


Select Case

執行幾組語句之一,具體取決於表達式的值。

示例

Case 1 To 4, 7 To 9, 11, 13, Is > MaxNumber

Case "everything", "nuts" To "soup", TestItem

Dim Number 
Number = 8    ' Initialize variable. 
Select Case Number    ' Evaluate Number. 
Case 1 To 5    ' Number between 1 and 5, inclusive. 
    Debug.Print "Between 1 and 5" 
' The following is the only Case clause that evaluates to True. 
Case 6, 7, 8    ' Number between 6 and 8. 
    Debug.Print "Between 6 and 8" 
Case 9 To 10    ' Number is 9 or 10. 
Debug.Print "Greater than 8" 
Case Else    ' Other values. 
    Debug.Print "Not between 1 and 10" 
End Select

[SendKeys string、[ wait ]](#SendKeys)

向活動窗口發送一個或多個鍵擊,就像按鍵盤上的按鍵同樣。

更多

示例

Dim ReturnValue, I 
ReturnValue = Shell("CALC.EXE", 1)    ' Run Calculator. 
AppActivate ReturnValue     ' Activate the Calculator. 
For I = 1 To 100    ' Set up counting loop. 
    SendKeys I & "{+}", True    ' Send keystrokes to Calculator 
Next I    ' to add each value of I. 
SendKeys "=", True    ' Get grand total. 
SendKeys "%{F4}", True    ' Send ALT+F4 to close Calculator.

Set

將對象引用分配給變量或屬性。

示例

Dim myChildForms(1 to 4) As Form1 
Set myChildForms(1) = New Form1 
Set myChildForms(2) = New Form1 
Set myChildForms(3) = New Form1 
Set myChildForms(4) = New Form1

Dim YourObject, MyObject, MyStr 
Set MyObject = YourObject    ' Assign object reference. 
' MyObject and YourObject refer to the same object. 
YourObject.Text = "Hello World"    ' Initialize property. 
MyStr = MyObject.Text    ' Returns "Hello World". 
 
' Discontinue association. MyObject no longer refers to YourObject. 
Set MyObject = Nothing    ' Release the object.

SetAttrpathname , attributes

設置文件的屬性信息。

Part 說明
pathname 必需。 指定文件名的字符串表達式,可包括目錄或文件夾和驅動器。
attributes 必需。 常量或數值表達式, 其總和指定文件屬性。
常量 說明
vbNormal 0 標準(默認)
vbReadOnly 1 只讀
vbHidden 2 隱藏
vbSystem 4 系統文件。 在 Macintosh 上不可用。
vbArchive 32 文件自上次備份以來已發生更改。
vbAlias 64 指定文件名爲別名。 僅在 Macintosh 上可用。

示例

SetAttr "TESTFILE", vbHidden ' Set hidden attribute. 
SetAttr "TESTFILE", vbHidden + vbReadOnly ' Set hidden and read-only 
 ' attributes.

Static

在過程級使用, 用於聲明變量和分配存儲空間。 在 Static 語句內聲明的變量會在代碼運行時一直保留其值。

示例

Static EmployeeNumber(200) As Integer

Static X As New Worksheet

Stop

可將 Stop 語句置於過程當中的任意位置來掛起執行。 使用 Stop 語句與在代碼中設置斷點類似。

Stop 語句將掛起執行,但與 End 不一樣,除非它位於已編譯的可執行 (.exe) 文件中,不然它將關閉任何文件或清除變量。

示例

Dim i As Long 
For i = 1 To 10 ' Start For...Next loop. 
 Debug.Print i ' Print i to the Immediate window. 
 Stop ' Stop during each iteration. 
Next i

Sub

聲明構成Sub 過程的主體的名稱、參數和代碼。


Time = time

設置系統時間。

示例

Dim MyTime 
MyTime = #4:35:17 PM# ' Assign a time. 
Time= MyTime ' Set system time to MyTime.

Type

在模塊級別使用, 以定義包含一個或多個元素的用戶定義的數據類型。

更多

示例

Type StateData 
    CityCode (1 To 100) As Integer    ' Declare a static array. 
    County As String * 30 
End Type 
 
Dim Washington(1 To 100) As StateData

Unload object

刪除內存中的對象。

示例

' This is the Initialize event procedure for UserForm1 
Private Sub UserForm_Initialize() 
 Load UserForm2 
 UserForm2.Show 
End Sub 
' This is the Click event for UserForm2 
Private Sub UserForm_Click() 
 Unload UserForm2 
End Sub 
 
' This is the Click event for UserForm1 
Private Sub UserForm_Click() 
 Unload UserForm1 
End Sub

[While condition [ statements ] Wend](#While...Wend)

示例

Dim Counter 
Counter = 0 ' Initialize variable. 
While Counter < 20 ' Test value of Counter. 
 Counter = Counter + 1 ' Increment Counter. 
Wend ' End While loop when Counter > 19. 
Debug.Print Counter ' Prints 20 in the Immediate window.

Width #filenumber, width

向使用Open 語句打開的文件分配輸出行寬度。

示例

Dim I 
Open "TESTFILE" For Output As #1 ' Open file for output. 
VBA.Width 1, 5 ' Set output line width to 5. 
For I = 0 To 9 ' Loop 10 times. 
 Print #1, Chr(48 + I); ' Prints five characters per line. 
Next I 
Close #1 ' Close file.

With

對單個對象或用戶定義類型執行一系列語句。

示例

With MyLabel 
 .Height = 2000 
 .Width = 2000 
 .Caption = "This is MyLabel" 
End With

[Write #filenumber、[ outputlist ]](#Write)

將數據寫入到順序文件中。

示例

Open "TESTFILE" For Output As #1    ' Open file for output. 
Write #1, "Hello World", 234    ' Write comma-delimited data. 
Write #1,    ' Write blank line. 
 
Dim MyBool, MyDate, MyNull, MyError 
' Assign Boolean, Date, Null, and Error values. 
MyBool = False : MyDate = #February 12, 1969# : MyNull = Null 
MyError = CVErr(32767) 
' Boolean data is written as #TRUE# or #FALSE#. Date literals are  
' written in universal date format, for example, #1994-07-13#  
 'represents July 13, 1994. Null data is written as #NULL#.  
' Error data is written as #ERROR errorcode#. 
Write #1, MyBool ; " is a Boolean value" 
Write #1, MyDate ; " is a date" 
Write #1, MyNull ; " is a null value" 
Write #1, MyError ; " is an error value" 
Close #1    ' Close file.
相關文章
相關標籤/搜索