我收到运行时错误' 52':代码如下。 VBA突出显示错误:vFile = Dir(ThisWorkbook.Path&" C:\ Users \ user_id \ Desktop \ ml \ testdirectory \")。
此目录存在,此处有.csv文件。以下是此目录中的文件名:12345678-111111.forecast.csv; 12345-222.forecast.csv。
'fixing:run time error '-2147467259 automation error unspecified error
Sub Unprotect_WorkSheet_With_Password()
Sheets("Sheet1").Unprotect "YourPassword"
End Sub
Sub Consolidate()
Dim sSQL As String 'SQL String
Dim oCn As Object 'Connection
Dim oRs As Object 'Recordset
Dim vFile As Variant 'File Name
Dim sCustomer As String 'Customer ID
Dim sItem As String 'Inventory Item ID
' Get filenames
vFile = Dir(ThisWorkbook.Path & "C:\Users\user_id\Desktop\ml\testdirectory\*.csv")
' Create SQL
While vFile <> vbNullString
If sSQL <> vbNullString Then sSQL = sSQL & vbCr & "Union " & vbCr
sCustomer = Split(vFile, "-")(0)
sItem = Split(Split(vFile, "-")(1), ".")(0)
sSQL = sSQL & "Select '" & sCustomer & "' as Customer, '" & sItem & "' as Item, * from [" & vFile & "]"
vFile = Dir
DoEvents
Wend
' Create Connection Objects
Set oCn = CreateObject("ADODB.Connection")
Set oRs = CreateObject("ADODB.Recordset")
oCn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & ThisWorkbook.Path & ";" & _
"Extended Properties=""Text;HDR=YES;FMT = CSVDelimited"";"
oRs.Open sSQL, oCn
Debug.Print sSQL
If Sheet1.ListObjects.Count > 0 Then Sheet1.ListObjects(1).Delete
Sheet1.ListObjects.Add( _
SourceType:=xlSrcQuery, _
Source:=oRs, _
Destination:=Sheet1.Range("C6")).QueryTable.Refresh
oRs.Close
oCn.Close
Set oRs = Nothing
Set oCn = Nothing
End Sub
在互联网上进行研究后,发现它可能是由.forecast.csv引起的。我删除了.forecast并运行了VBA代码,但它没有解决问题。
另一个测试:(我得到不同的错误) 路径=&#34; C:\ Users \ user_id \ Desktop \ ml \ testdirectory \&#34; vFile = Dir(Path&amp;&#34; * .csv&#34;)
Path = "C:\Users\user_id\Desktop\ml\testdirectory\"
vFile = Dir(Path & "*.forecast.csv")
答案 0 :(得分:0)
您的ThisWorkbook.Path
将返回C:\Documents and Settings\myprofile\Desktop
之类的内容。
所以你的DIR行读作:"C:\Documents and Settings\myprofile\DesktopC:\Users\user_id\Desktop\ml\testdirectory\*.csv"
。
当然这不可能是正确的 - 你在那里有两次驱动器号....
也许它应该像ThisWorkbook.Path & "\ml\testdirectory\*.csv"
提供ml
一样,位于工作簿所在的同一文件夹的子文件夹中。