使用Excel 2010,我试图添加一个代码,打开文件选择窗口,供用户选择他想要打开的CSV文件。
我的代码如下:
Dim OpenThisFile
OpenThisFile = Application.GetOpenFilename
这只是从我以前的一个旧VBA文件中获取的,这在以前是有效的。目前,当VBA读取第二行时,它会打开文件选择窗口,但只要我选择一个CSV文件并点击OPEN就会出现错误Application-Defined or Object-Defined Error
答案 0 :(得分:2)
GetOpenFilename
会将完整的 filespec 作为 String 变量返回。你可以解析它:
Sub qwerty()
Dim f As String, Path As String, _
FileName As String, FileType As String
f = Application.GetOpenFilename()
MsgBox f
ary = Split(f, "\")
bry = Split(ary(UBound(ary)), ".")
ary(UBound(ary)) = ""
Path = Join(ary, "\")
FileName = bry(0)
FileType = bry(1)
Range("A1") = Path
Range("A2") = FileName
Range("A3") = FileType
End Sub
如果您想预先选择路径和文件类型,那么:
Sub qwerty2()
Dim f As String, Path As String, _
FileName As String, FileType As String
ChDir "C:\TestFolder"
f = Application.GetOpenFilename(FileFilter:="Text Files (*.csv), *.csv")
MsgBox f
ary = Split(f, "\")
bry = Split(ary(UBound(ary)), ".")
ary(UBound(ary)) = ""
Path = Join(ary, "\")
FileName = bry(0)
FileType = bry(1)
Range("A1") = Path
Range("A2") = FileName
Range("A3") = FileType
End Sub