使用命令按钮删除filelistbox中的指定文件

时间:2015-09-04 11:50:04

标签: vba

所以我的表单上有一个DirListBox,DriveListBox和一个FileListBox。 我还有一个删除命令按钮。我想要做的是当我按下删除命令按钮时删除我的FileListBox上显示的* .docx文件。这是我的代码:

Private Sub cmddel1_Click()
Dim nAns As Long
Dim strFile As String
If flb1.ListIndex < 0 Then
  'There is nothing selected in the listbox.
   Exit Sub
End If

strFile = flb1.Path & flb1.List(flb1.ListIndex)

 'Give them a chance to not delete the file
nAns = MsgBox("Please confirm to delete file ' " & strFile & "'?'", vbQuestion & vbYesNo)
 'If they choose Yes then delete the file.
If nAns = vbYes Then
  kill (flb1.path)
  End If
End Sub

假设flb1是我的FileListBox的名称。

这是我的DirListBox代码:

Private Sub Dir1_Change()
flb1.Path = Dir1.Path
End Sub

这是DriveListBox代码:

Private Sub Drive1_Change()
Dir.Path = Drive1.Drive
End Sub

出现的问题是,当我按下删除命令按钮时,它会运行到nAns = nAns = MsgBox("Please confirm to delete file ' " & strFile & "'?'", vbQuestion & vbYesNo),当我按下是Run-Time Error '53' File Not Found时,调试就在kill (flb1.path)上。< / p>

单击“删除”命令按钮时,我应该使用什么来删除Filelistbox上显示的.docx文件?

1 个答案:

答案 0 :(得分:1)

您只是指路径而不是实际文件本身。

您可以使用以下内容:

Kill strFile
or
Kill (strFile)

代码示例:

Sub Killfl()
    Dim flpath As String
    Dim flname As String
    Dim strFile As String
    flpath = "c:\Test\"
    flname = "Test.txt"
    strFile = flpath & flname
    Kill strFile
End Sub

以上代码删除File中名为File Extension .txt Test.txt的{​​{1}}