我想选择多个文件(如图所示);例如。“数据源质量”,“数据源安全性”,“数据源运输”,“数据源仓库”。
作为补充,如果选择的文件名为“ DataSource Quality 2020”等,则它仍应为有效选择。意思是说,只要文件名包含如上面的屏幕快照中所示的名称,它仍然应该被认为是正确的。
但是,如果选择的任何文件有误(部分文件名错误),则应该出现一个消息框,显示“否/选择了错误的文件”。
Dim hasRun As Boolean
Sub RunOnlyOnce()
Application.DisplayAlerts = True
If hasRun = False Then
Dim fNameAndPath As Variant
fNameAndPath = Application.GetOpenFilename(FileFilter:="All Files (*.*), *.*", Title:="Select Files To Be Opened", MultiSelect:=True)
Debug.Print fNameAndPath
Debug.Print Dir(fNameAndPath)
If Dir(fNameAndPath) = "DataSource.xlsx" Then
Workbooks.Open Filename:=fNameAndPath
hasRun = True
Exit Sub
Else
MsgBox "No/Wrong file selected. ", vbExclamation, "Oops!"
ThisWorkbook.Saved = False
Application.Quit
End If
End If
End Sub
这是我的代码:
Sub SubOpenDataSourceFiles()
'Declarations.
Dim WrkMotherWorkbook As Workbook
Dim VarFiles As Variant
Dim IntCounter01 As Integer
Dim StrFileName As String
Dim StrMarker As String
'Setting variables.
StrMarker = "DataSource"
Set WrkMotherWorkbook = ActiveWorkbook
'Request the user what files to open.
VarFiles = Application.GetOpenFilename(FileFilter:="All Files (*.*), *.*", _
Title:="Select Files To Be Opened", _
MultiSelect:=True _
)
'Checking if it has been selected any file.
On Error GoTo No_File_Selected
IntCounter01 = UBound(VarFiles)
On Error GoTo 0
'Scrolling through the files.
For IntCounter01 = 1 To UBound(VarFiles)
'Setting the variable in order to analyse the file name.
StrFileName = Split(VarFiles(IntCounter01), "\")(UBound(Split(VarFiles(IntCounter01), "\")))
'Checking if the left part of the file name differs from StrMarker.
If Left(StrFileName, Len(StrMarker)) <> StrMarker Then
'If it does differ, a message box pops up.
MsgBox "Unauthorized file.", vbExclamation, StrFileName
Else
'If it doesn't differ, it opens the file (assuming it's not a corrupted file).
Workbooks.Open Filename:=CStr(VarFiles(IntCounter01))
End If
Next
'Activating WrkMotherWorkbook.
WrkMotherWorkbook.Activate
No_File_Selected:
End Sub
它可能不如Gangula的优雅,但仍然可以使用。唯一的要点:打开文件时,我保持了“所有文件”的首选项。我仍然建议将其过滤为.xlsm或.xls或您应打开的任何类型的excel文件。就像Gangula的一样。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句