简体   繁体   English

使用VBA打开FileDialog

[英]Open FileDialog using VBA

I download reports on a daily/weekly basis but when downloading the system auto generates the file name with a date at the end although the basic file name is the same. 我每天/每周下载报告,但下载时系统会自动生成文件名,但文件名的末尾带有日期,尽管基本文件名相同。 ie ANAPOS - 20141001. I'm using a simple open command (Workbooks.OpenText Filename:="C:\\Users\\903270\\Documents\\Excel\\ANAPOS.txt") to do some other stuff but before doing so I need to rename the file to ANAPOS.txt before I can run it. 即ANAPOS-20141001。我正在使用一个简单的打开命令(Workbooks.OpenText文件名:=“ C:\\ Users \\ 903270 \\ Documents \\ Excel \\ ANAPOS.txt”)来执行其他操作,但在此之前,我需要重命名我可以先将文件保存到ANAPOS.txt。 Is there any code that will allow my macro to search for ANAPOS with out all the other info at the end? 是否有任何代码可让我的宏搜索ANAPOS,而最后没有其他所有信息? Any help appreciated. 任何帮助表示赞赏。

Set filePath to where you want to search filePath设置到要搜索的位置

Sub getANAPOS()
Dim Filter As String, filePath As String

filePath = "C:\Data\VBA\SO\"
Filter = "ANAPOS files (*.txt), filepath & ANAPOS*.txt"

ANAPOSSelectedFile = Application.GetOpenFilename(Filter)

End Sub

EDIT FOLLOWING CLARIFICATION BY OP 通过OP编辑说明

Sticking with the same theme, this should give you some scope to work with. 坚持相同的主题,这应该给您一些工作空间。 It essentially 'automatically' renames the selected file in situ, unless it already exists. 除非已存在,否则它基本上是“自动”在原位重命名所选文件。 Acknowledgements to @Gary's Student for his neat ideas to parse the GetOpenFileName result, here . 致谢改为@加里的学生,他巧妙的想法来解析GetOpenFileName结果, 在这里

Sub renameANAPOS()
Dim Filter As String, filePath As String, newName As String

'filter txt file names containing 'ANAPOS'
Filter = "ANAPOS files (*.txt), filepath & ANAPOS*.txt"

'the 'rename' name
newfName = "ANAPOS"

'navigate to original ANAPOS file and location details
ANAPOSSelectedFile = Application.GetOpenFilename(Filter)

'parse selected file details
fullArr = Split(ANAPOSSelectedFile, "\")
detArr = Split(fullArr(UBound(fullArr)), ".")
fullArr(UBound(fullArr)) = ""
fPath = Join(fullArr, "\")
fName = detArr(0)
fExt = detArr(1)

'rename file in not already exixts
    If Len(Dir(fPath & newfName & "." & fExt)) > 0 Then
        MsgBox newfName & "." & fExt & " already exists in this folder."
        Exit Sub
    Else
        Name ANAPOSSelectedFile As fPath & newfName & "." & fExt
    End If

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM