vs遍歷文件夾
❶ vba 遍歷指定文件夾(含子目錄)獲取文件名,哪種方法速度最快
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'這里很關鍵,決定宏執行快慢的關鍵
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'打開目錄選擇框
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "請選擇目錄"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'取消選擇
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'指定過濾的文件後綴
myExtension = "*.xls*"
'遍歷全路徑
myFile = Dir(myPath & myExtension)
'循環處理每一個文件
Do While myFile <> ""
'打開
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'確保工作簿被打開,在處理下一個文件時
DoEvents
'設置背景色
wb.Worksheets(1).Range("A1:Z1").Interior.Color = RGB(51, 98, 174)
'保存工作簿
wb.Close SaveChanges:=True
'確保工作簿被關閉,在處理下一個文件時
DoEvents
'接著處理下一個
myFile = Dir
Loop
'提示處理完成
MsgBox "處理完成!"
ResetSettings:
'恢復設置
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
❷ vb.net如何遍歷整個文件夾,後找出某一個文件
解壓密碼:1299
假設路徑為C:\abc
代碼:
Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim Files As ObjectModel.ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles("C:\abc") Dim FileSize As Long, FileName As String = Nothing Dim oFileSize As Long For Each File As String In Files oFileSize = My.Computer.FileSystem.GetFileInfo(File).Length If oFileSize > FileSize Then FileSize = oFileSize FileName = File End If Next Dim ListN As ListViewItem = New ListViewItem(My.Computer.FileSystem.GetName(FileName)) ListN.SubItems.Add(oFileSize & " byte") ListN.SubItems.Add(My.Computer.FileSystem.GetFileInfo(FileName).Extension & " 文件") ListN.SubItems.Add(FileName) ListView1.Items.Add(ListN) End SubEnd Class
詳見源代碼!!