VBA Excel文件对话框返回selecteditem作为对象
我正在使用VBA for Excel中的函数来搜索文件,并要求用户选择“未找到” 当我使用VBA Excel文件对话框返回selecteditem作为对象,vba,excel,Vba,Excel,我正在使用VBA for Excel中的函数来搜索文件,并要求用户选择“未找到” 当我使用application.filedialogfilepicker选择文件时,.selecteditem(1)将作为字符串返回,但理想情况下,我需要它作为对象返回 有没有一种方法可以改变这一点,或者我从一开始就走错了方向 Public myDir As String Public newFilePath As String Public FileSys As Object Public myFolder
application.filedialog
filepicker
选择文件时,.selecteditem(1)
将作为字符串返回,但理想情况下,我需要它作为对象返回
有没有一种方法可以改变这一点,或者我从一开始就走错了方向
Public myDir As String
Public newFilePath As String
Public FileSys As Object
Public myFolder
Function LoadFileName(FileStart As String, FileType As String)
newFilePath = ActiveWorkbook.Path
myDir = newFilePath & "\Daily reports"
ChDrive (Left(ActiveWorkbook.Path, 2))
ChDir myDir
Set FileSys = CreateObject("Scripting.FileSystemObject")
Set myFolder = FileSys.GetFolder(myDir)
On Error GoTo FileNotFound
Dim dteFile As Date
Dim oFS As Object
Dim objFile As Object
Dim FileName As Object
Dim strFileToOpen As Office.FileDialog
dteFile = DateSerial(1900, 1, 1)
Set FileSys = CreateObject("Scripting.FileSysetmObject")
For Each objFile In myFolder.Files
If FileSys.GetFile(objFile).DateCreated >= dteFile And UCase(Left(objFile.Name, 3)) = FileStart Then
dteFile = FileSys.GetFile(objFile).DateCreated
Set FileName = objFile
End If
Next
FileFound:
fileConfirm = MsgBox("Is " & FileName.Name & " the report you wish to use?", vbYesNoCancel + vbQuestion)
If fileConfirm = vbCancel Then
End
ElseIf fileConfirm = vbNo Then
GoTo SelectFile
ElseIf fileConfirm = vbYes Then
Set LoadFileName = FileName
Exit Function
End If
FileNotFound:
MsgBox "Unable to find most recent report." & vbCrLf & _
"Please select the file you wish to use.", vbInformation + vbOKOnly
SelectFile:
Set strFileToOpen = Application.FileDialog(msoFileDialogFilePicker)
With strFileToOpen
.AllowMultiSelect = False
.Title = "Pleas select report to use."
.Filters.Clear
.Filters.Add "Excel", "*." & FileType & "*"
End With
If strFileToOpen.Show = -1 Then
FileName = strFileToOpen.SelectedItems(1)
GoTo FileFound
Else
forceBreak = MsgBox("No file has been selected. Would you like to try again?", vbExclamation + vbYesNo)
If forceBreak = vbNo Then
MsgBox "The CQUIN daily patient list cannot be generated without both EPIC and CHEQS reports." & _
"Please ensure these have been run and saved in the correct locations.", vbCritical
End
Else
GoTo SelectFile
End If
End If
End Function
我终于自己找到了解决办法。对于那些想要它的人,这就是我所缺少的: 我只需要使用
.GetFile
If strFileToOpen.Show = -1 Then
Set FileName = FileSys.GetFile(strFileToOpen.SelectedItems(1))
GoTo FileFound
Else
您希望将文件名转换为什么类型的对象?它应该返回什么“对象”?此对象将与filettype不同。如果您需要打开另一个Excel文件,请使用从对话框中获得的文件名。@YowE3K对不起,我应该这么说。这是一个文件对象。你想要一个文件对象似乎很奇怪。Excel中最常见的事情是需要文件名,因此我担心调用代码现在必须获取返回的对象,并使用其
名称
或路径
属性,即返回您开始使用的字符串。(但是,只要它能工作,我想那没关系。)