VBA中有时要判断文件或文件夹是否存在,为打开文件作准备,这里采用错误机制来判断
代码如下:
Function 文件或文件夹是否存在(全路径 As String) As Boolean
On Error GoTo
EarlyExit
If Not Dir(全路径, vbDirectory) = vbNullString Then
文件或文件夹是否存在 = True
End If
Exit Function
EarlyExit:
文件或文件夹是否存在 = False
End Function
需在说明的是,参数“全路径”要有盘符之类的,呵呵
使用方法与其它函数一样
VBA的 *** 作中,有时要打开一个文件,但要是文件已打开,再次通过程序打开时,会出现错误,因此,在打开文件之前,需在先判断文件是否已打开,下面是判断代码:
Function 文件是否打开(文件名 As
String) As Boolean
On Error Resume Next
文件是否打开 = True
If StrComp(Workbooks(文件名).Name, 文件名, vbTextCompare) 0 Then
文件是否打开 = False
End If
End Function
需要说明的是,参数“文件名”是短文件名(不带路径的文件名)
Function 特殊文件夹路径(文件夹名
As String) As String
Dim WSHShell As Object
Dim lj As String
Set WSHShell =
CreateObject("Wscript.Shell")
lj = WSHShell.SpecialFolders(文件夹名)
Set WSHShell = Nothing
特殊文件夹路径 = lj
End Function
文件夹名有:
AllUsersDesktop
AllUsersStartMenu
AllUsersPrograms
AllUsersStartup
Desktop
Favorites
Fonts
MyDocuments
NetHood
PrintHood
Programs
Recent
SendTo
StartMenu
Startup
Templates
以下代码,楼主可以参考,打开文件夹,选择文件后自动打开Sub text()
With Application.FileDialog(msoFileDialogFilePicker)
.InitialFileName = ThisWorkbook.Path &"\"
.Title = "请选择对应文本文件"
.AllowMultiSelect = False
If .Show Then f = .SelectedItems(1) Else Exit Sub '
End With
Shell "RUNDLL32.EXE URL.DLL,FileProtocolHandler " &f, vbMaximizedFocus
End Sub
【引用位置】 https://blog.csdn.net/pashine/article/details/42100237
'-------------------------------------------
'获取某文件夹下的所有Excel文件
'-------------------------------------------
Sub getExcelFile(sFolderPath As String)
On Error Resume Next
Dim f As String
Dim file() As String
Dim x
k = 1
ReDim file(1)
file(1) = sFolderPath &""
End Sub
'-------------------------------------------
'获取某文件夹下的所有文件和子目录下的文件
'-------------------------------------------
Sub getAllFile(sFolderPath As String)
'Columns(1).Delete
On Error Resume Next
Dim f As String
Dim file() As String
Dim i, k, x
x = 1
i = 1
k = 1
ReDim file(1 To i)
file(1) = sFolderPath &""
'-- 获得所有子目录
Do Until i >k
f = Dir(file(i), vbDirectory)
Do Until f = ""
If InStr(f, ".") = 0 Then
k = k + 1
ReDim Preserve file(1 To k)
file(k) = file(i) &f &""
End If
f = Dir
Loop
i = i + 1
Loop
'-- 获得所有子目录下的所有文件
For i = 1 To k
f = Dir(file(i) &" . ")'通配符 . 表示所有文件,*.xlsx Excel文件
Do Until f = ""
'Range("a" &x) = f
Range("a" &x).Hyperlinks.Add Anchor:=Range("a" &x), Address:=file(i) &f, TextToDisplay:=f
x = x + 1
f = Dir
Loop
Next
End Sub
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)