'復制下面代碼到窗體
'把代碼中的C:\123.txt替換成妳的文件地址
Private Sub Form_Load()
Me.Command1.Caption = "添加"
Me.Command2.Caption = "刪除"
Me.Command3.Caption = "修改"
Me.Command4.Caption = "保存"
End Sub
'=============
'添加
Private Sub Command1_Click()
Me.List1.Clear
If ReadText("c:\123.txt", Me.List1) = False Then
MsgBox "文件讀取失敗"
End If
End Sub
'=============
'刪除
Private Sub Command2_Click()
On Error GoTo err
Dim i As Integer
i = Me.List1.ListIndex
If i >= 0 Or i < Me.List1.ListCount - 1 Then
Me.List1.RemoveItem i
End If
Command4_Click
Exit Sub
err:
MsgBox "操作失敗"
End Sub
'=============
'修改
Private Sub Command3_Click()
On Error GoTo err
Dim i As Integer
i = Me.List1.ListIndex
Me.List1.RemoveItem i
Me.List1.AddItem Me.Text1.Text, i
Command4_Click
Exit Sub
err:
MsgBox "操作失敗"
End Sub
'=========================
'保存
Private Sub Command4_Click()
If Me.List1.ListCount = 0 Then Exit Sub
If SaveText("c:\123.txt", Me.List1) = False Then
MsgBox "文件保存失敗"
End If
End Sub
'======================================
'ListBox單擊事件
'在Textbox中顯示數據
Private Sub List1_Click()
Dim i As Integer
Dim strTxt As String
i = Me.List1.ListIndex
strTxt = Me.List1.List(i)
Me.Text1.Text = strTxt
End Sub
'===================================
'讀取TXT文件
'strPath為文件路徑
'lisBox 為ListBox空間
'調用方法示例: Call ReadText("c:\123.txt", Me.ListBox1)
Private Function ReadText(ByVal strPath As String, ByVal lisBox As ListBox) As Boolean
On Error GoTo err
Dim strLine As String
Dim Int1 As Integer
Int1 = FreeFile
Open strPath For Input As #Int1
Do While Not EOF(1)
Line Input #Int1, strLine
lisBox.AddItem strLine
Loop
Close #Int1
ReadText = True
Exit Function
err:
ReadText = False
End Function
'===================================
'保存TXT文件
'strPath為文件路徑
'lisBox 為ListBox空間
'調用方法示例: Call SaveText("c:\123.txt", Me.ListBox1)
Private Function SaveText(ByVal strPath As String, ByVal lisBox As ListBox) As Boolean
On Error GoTo err
Dim strLine As String
Dim Int1, i As Integer
Int1 = FreeFile
Open strPath For Output As #Int1
For i = 0 To Me.List1.ListCount - 1
DoEvents
Print #Int1, Me.List1.List(i)
Next i
Close #Int1
SaveText = True
Exit Function
err:
SaveText = False
End Function