1,使用菜单:[工程] -- [部件],勾选其中的:Microsoft Common Dialog Control 6.0 (SP6)
2,在窗体上添加1个文本框Text1,2个按钮,添加1个CommonDialog1控件。
3,设置文本框Text1的MultiLine 属性为True,ScrollBars 属性为2。
编写代码如下:
Option Explicit
Private Sub Command1_Click()
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'使用通用对话框实现寻找并打开指定文件
'CancelError属性为True。
On Error GoTo ErrHandler
'设置过滤器
CommonDialog1.Filter = "Text Files(*.txt)|*.txt|Batch Files(*.bat)|*.bat"
'指定缺省过滤器。
CommonDialog1.FilterIndex = 1
'显示"打开"对话框。
CommonDialog1.ShowOpen
'调用打开文件的过程
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'读文本文件
Dim MyStr As String '用来存放文本文件的内容
Dim MyStrLine As String '用来存放读取1行文本的内容
MyStr = ""
'读取文件信息
'以读的方式打开文件,其中文件名由用户通过CommonDialog1指定
Open CommonDialog1.FileName For Input As #1
Do While Not EOF(1) ' 循环至文件尾
Line Input #1, MyStrLine '读入一行
MyStr = MyStr & MyStrLine & vbCrLf
Loop
Close #1 ' 关闭文件。
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'将文件内容显示在文本框
Text1.Text = MyStr
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Exit Sub
ErrHandler:
'用户在通用对话框里按了"取消"按钮。
Exit Sub
End Sub
Private Sub Command2_Click()
End
End Sub
' 首先添加对话框控件,用对话框打开要加载的文本文件。
Private Sub Command1_Click()
Dim txtFile As String
Dim strRow As String, strText As String
With CommonDialog1
.Filter = "*.TXT|*.txt"
.ShowOpen
txtFile = .FileName
End With
If (txtFile = "") Then Exit Sub
If (Dir(txtFile) = "") Then Exit Sub
Open txtFile For Input As #1
Input #1, strText
Do While Not EOF(1)
DoEvents
Input #1, strRow
strText = strText & vbCrLf & strRow
Loop
Close #1
Text1.Text = strText
End Sub
Private Sub Command1_Click()
Dim f, strTxt, s: s = String(260, Chr(0))
Set f = CreateObject("MSComDlg.CommonDialog")
With f
.Flags = &H4
.MaxFileSize = 260
'.InitDir = "g:\"
.Filter = "所有文件(*.*)|*.*|文本文件(*.txt)|*.txt"
.FilterIndex = 2
'.DefaultExt = .Filter
.ShowSave
s = .FileName
End With
If s <> "" Then
Open s For Input Access Read As #1
Do While Not EOF(1)
Line Input #1, strTxt
Text1.Text = Text1.Text & strTxt & vbCrLf
Loop
Close #1
End If
Set f = Nothing
End Sub