您的位置:首頁>正文

VBA|使用和定制Excel內置對話方塊

在Excel中, 對話方塊可以實現應用程式與使用者的交互。 在VBA中, Excel提供了調用這些內置對話方塊的介面, 使開發者可充分利用內置對話方塊實現更多的操作。

1 用FindFile方法打開文件

Sub 打開工作簿()

Dim wb As Workbook

Set wb = ActiveWorkbook

If Application.FindFile Then '顯示“打開”對話方塊

MsgBox "已打開工作簿文件!"

wb.Activate

Else

MsgBox "打開工作簿失敗!"

End If

End Sub

'上面代碼運行後, 顯示“打開”對話方塊, 選擇一個工作簿, 按一下“打開”後即可打開該工作簿

2 使用對話方塊獲取單個檔案名

2.1 使用GetOpenFilename方法顯示“打開”對話方塊, 獲取選擇的檔案名

Sub 獲取單個檔案名()

Dim strFilt As String

Dim strTitle As String

Dim strFname As Variant

strFilt = "文字檔(*.txt),*.txt," & _

"Excel文件(*.xls;*.xlsx;*.xlsm),*.xls;*.xlsx;*.xlsm," & _

"所有檔(*.*),*.*"

strTitle = "打開Excel文件"

strFname = Application.GetOpenFilename _

(fileFilter:=strFilt, _

Title:=strTitle)

If strFname = False Then

MsgBox "沒選擇檔!"

Else

MsgBox "選擇的檔是:" & strFname

End If

End Sub

2.2 使用GetSaveAsFilename方法打開“另存為”對話方塊獲取檔案名

Sub 獲取保存檔案名()

Dim fn As String

fn = Application.GetSaveAsFilename( _

fileFilter:="Text Files (*.txt), *.txt")

If fn <> "False" Then

'在此處編寫保存檔的代碼

MsgBox "保存檔為:" & fn

End If

End Sub

3 使用對話方塊獲取多個檔案名

Sub 獲取多個檔案名()

Dim strFilt As String

Dim strTitle As String

Dim strFname As Variant

Dim i As Integer

Dim strMsg As String

strFilt = "文字檔(*.txt),*.txt," & _

"Excel文件(*.xls;*.xlsx;*.xlsm),*.xls;*.xlsx;*.xlsm," & _

"所有檔(*.*),*.*"

strTitle = "打開Excel文件"

strFname = Application.GetOpenFilename _

(fileFilter:=strFilt, _

Title:=strTitle, _

MultiSelect:=True) '允許選擇多個檔

If Not IsArray(strFname) Then '返回值不是陣列

MsgBox "沒選擇檔!"

Else

For i = LBound(strFname) To UBound(strFname)

strMsg = strMsg & strFname(i) & vbCrLf

Next

MsgBox "選擇的檔是:" & vbNewLine & strMsg

End If

End Sub

4 使用Dialogs集合可以調用所有Excel內置對話方塊

Excel2007中有1101個內置對話方塊, 如下面代碼可以調用“對齊"標籤頁:

Sub 對齊對話方塊()

Application.Dialogs(xlDialogAlignment).Show

End Sub

5 設置內置對話方塊的初始值

在VBA中, 可以通過更改對話方塊的選項參數, 定制使用者需要的對話方塊:

Sub 設置字體1()

Application.Dialogs(xlDialogFontProperties).Show _

"黑體", "粗體", 20, True, True, False, , _

True, 5, 4, True, 3

End Sub

Sub 設置字體2()

Application.Dialogs(xlDialogFontProperties).Show _

arg1:="黑體", arg2:="粗體", arg3:=20, _

arg4:=True, arg5:=True, arg7:=True, arg8:=True, _

arg9:=5, arg10:=4, arg11:=True, arg12:=3

End Sub

選擇需要設置字體的儲存格區域後, 運行上面的代碼, 調用自訂的內置對話方塊後, 即可對選擇區域進行格式設置:

-End-

同類文章
Next Article
喜欢就按个赞吧!!!
点击关闭提示