VB 如何让listview控件显示指定文件夹内的子文件夹和文件

2025年01月07日 06:43
有2个网友回答
网友(1):

Dim PathName As String '存放路径
Sub FolderList(PathName As String)
Dim sf As String
If Right(PathName, 1) <> "\" Then PathName = PathName & "\"
sf = Dir(PathName, vbDirectory) '获取第一个目录名
Do While sf <> ""
' 跳过当前的目录及上层目录
If sf <> "." And sf <> ".." Then
If (GetAttr(PathName + sf) And vbDirectory) = vbDirectory Then
Set ITM = ListView1.ListItems.Add(, , sf)
End If
End If
sf = Dir() ' 查找下一个目录
Loop
End Sub

Sub FileList(PathName As String)
Dim sDir As String
If Right(PathName, 1) <> "\" Then PathName = PathName & "\"
sDir = Dir(PathName & "*.*")
Do While Len(sDir) > 0
Set ITM = ListView1.ListItems.Add(, , sDir)
sDir = Dir
Loop
End Sub
Private Sub ShowAll()
PathName = "d:\vb" '这里我随便指定了一个初始目录
Call FolderList(PathName)
Call FileList(PathName)
End Sub

Private Sub Command1_Click()
Call ShowAll
End Sub

Private Sub Command2_Click()
ShowBack
End Sub

Private Sub Form_Load()
ListView1.ColumnHeaders.Add , , "文件", ListView1.Width
ListView1.View = lvwReport
ListView1.LabelEdit = lvwManual
End Sub
Private Sub ShowNext() '实现向下接着打开文件夹功能
PathName = PathName & ListView1.SelectedItem
Debug.Print PathName
ListView1.ListItems.Clear
Call FolderList(PathName)
Call FileList(PathName)
End Sub
Private Sub ShowBack() '实现向上功能
Dim sPathName() As String
Dim TempPath As String
Dim i As Integer
sPathName = Split(PathName, "\")
For i = 0 To UBound(sPathName) - 2
TempPath = TempPath & sPathName(i) & "\"
Next
PathName = TempPath
Debug.Print PathName
ListView1.ListItems.Clear
Call FolderList(PathName)
Call FileList(PathName)
End Sub

Private Sub ListView1_DblClick()
ShowNext
End Sub

网友(2):

SORRY,大侠我也不能搞定,自己拭拭吧!