Excel VBA打开1个CSV文件

使用Excel 2010,我试图添加一个代码,将打开文件select窗口供用户select他想要打开的CSV文件。

我的代码如下:

Dim OpenThisFile OpenThisFile = Application.GetOpenFilename 

这只是从我的一个旧的VBA文件,这是以前工作。 目前,当VBA读取第二行时,会打开文件select窗口,但是一旦我select一个CSV文件并打开它,就会出现错误Application-Defined or Object-Defined Error

GetOpenFilename将以Stringvariables的forms返回完整的filespec 。 你可以像这样parsing它:

 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 

在这里输入图像说明

如果你想要预先selectpath和文件types,那么:

 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