strFile = Application.GetOpenFilename ' Workbooks.Open strFile
With ActiveSheet.QueryTables.Add( _
Connection:="strFile", _
Destination:=Range("$A$1"))
'我尝试过: 使用ActiveSheet.QueryTables.Add(_ 连接:=" TEXT; strFile",_ 目的地:=范围(" $ A $ 1&#34))
这会引发错误,说“"运行时错误' 1004&#39 ;; 所以你有任何线索,为什么它显示我错误??
答案 0 :(得分:1)
经过一些快速测试后,我想我已经找到了问题。您需要确保没有将字符串“strFile”传入连接,并且需要将TEXT连接到连接字符串。这在这里得到证明:
strFile = Application.GetOpenFilename 'Workbooks.Open strFile
strFile = "TEXT;" & strFile 'Add the TEXT; to beginning of connection string
With ActiveSheet.QueryTables.Add(Connection:= _
strFile, Destination _
:=Range("$A$1"))
... 'Remainder of code
End With
为了更好地衡量,您可能希望将With ActiveSheet.QueryTables.Add ...
代码放在IF语句中,该语句检查以确保选择了文件。
例如:
Dim strFile As String
strFile = Application.GetOpenFilename 'Workbooks.Open strFile
strFile = "TEXT;" & strFile
If strFile <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
strFile, Destination _
:=Range("$A$1"))
... 'Remainder of code
End With
Else
MsgBox "No file was selected!"
End If