【发布时间】:2015-12-25 19:36:03
【问题描述】:
我一直在抓取该网站以解决我的问题。我在 Mac OS X 10.10.5 上使用 Excel 2011。
我的情况是这样的: 我有一堆 CSV 文件需要导入 Excel 以进行进一步的统计分析。这是我的一个 CSV 文件(与谷歌驱动器共享)的example。 数据用逗号分隔,并且应该导入到所有工作表中的单元格 A1(为了澄清,我不希望所有数据都在 A1 中。现在这很愚蠢,不是吗。CSV 数据应该从这里开始,并且跨越 A 列和 B 列,直到行号 ~1200 或任何长度)。导入给定 CSV 文件的工作表应以 CSV 文件命名(不带“.csv”),因为稍后我将使用工作表名称调用数据。 使用导入向导非常乏味,而且要导入 180 个,VBA 代码/宏会很有帮助,因为我需要 6 个非常专注的小时(而且我喜欢在 excel 中做一些聪明的事情)
目前我有一个添加新工作表的代码,但它不起作用
(1) 未导入数据 - 我收到运行时错误“5” - 过程调用或参数无效。
(2) 工作表以文件类型扩展名 .csv 命名。
关于为什么我在此之后收到错误的任何想法?:
With ActiveSheet.QueryTables.Add( _
Connection:="TEXT;" & Fname, _
Destination:=Range("A1"))l
当前代码:
Sub CSVIMPORTTEST2()
Dim MyPath As String
Dim MyScript As String
Dim MyFiles As String
Dim MySplit As Variant
Dim N As Long
Dim Fname As String
Dim mybook As Worksheet
On Error Resume Next
MyPath = MacScript("return (path to documents folder) as String")
'Or use MyPath = "Macintosh HD:Users:YourUserName:Desktop:TestFolder:"
MyScript = "set applescript's text item delimiters to (ASCII character 10) " & vbNewLine & _
"set theFiles to (choose file of type " & _
" (""public.comma-separated-values-text"") " & _
"with prompt ""Please select a file or files"" default location alias """ & _
MyPath & """ multiple selections allowed true) as string" & vbNewLine & _
"set applescript's text item delimiters to """" " & vbNewLine & _
"return theFiles"
MyFiles = MacScript(MyScript)
On Error GoTo 0
If MyFiles <> "" Then
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
MySplit = Split(MyFiles, Chr(10))
For N = LBound(MySplit) To UBound(MySplit)
'Get file name only and test if it is open
Fname = Right(MySplit(N), Len(MySplit(N)) - InStrRev(MySplit(N), _
Application.PathSeparator, , 1))
Set mybook = Nothing
On Error Resume Next
Set mybook = Sheets.Add(After:=Sheets(Worksheets.Count))
mybook.Name = Fname
On Error GoTo 0
Next
Worksheets(Fname).Activate
With ActiveSheet.QueryTables.Add( _
Connection:="TEXT;" & Fname, _
Destination:=Range("A1"))
.Name = "CSV" & Worksheets.Count + 1
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.TextFilePromptOnRefresh = False
.TextFilePlatform = xlMacintosh
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
End With
End If
End Sub
希望有人能帮忙
最好的问候埃米尔霍克
【问题讨论】:
-
失败时
Fname的值是多少?它是完整路径吗? -
看起来
Fname只包含文件名而不包含文件的完整路径,在这种情况下 Excel 将不知道文件在哪里!
标签: excel vba macos csv excel-2011