MS Access VBA下载附件Mkdir路径不存在



我正在尝试下载Access表中的所有附件,并按Year\Month文件夹存储它们。我可以下载它们,并使用这篇文章的指导原则,通过ID将它们存储在文件夹中。

MS Access VBA-尝试提取表中的每个文件';s的磁盘附件?

然而,现在我试图修改一下代码,它会给我一个错误"76",说Path not Found。但在代码中,我认为我已经在使用If Len(Dir(folder,vbDirectory((=0 Then MkDir(folder(…创建文件夹。。。。此外,当我在调试模式下将鼠标悬停在mkdir上时,它显示:folder="C:\Personal \Desktop\a\2014\11\",这是我的表上的前几项

有人能帮忙吗?

该表具有"年"、"月"one_answers"附件"列。目标是按照年份和月份放置所有附件,格式为:"C:\Personal \Desktop\a\Year\Month\">

Sub a()
Dim database As DAO.database
Dim table As DAO.Recordset
Dim PONum As String
Dim folder As String
Set database = CurrentDb
Dim PKey As String
Dim P2Key As String
Set table = database.OpenRecordset("NIS")
With table ' For each record in table
Do Until .EOF 'exit with loop at end of table
Set Attachments = table.Fields("Attachments").Value 'get list of attachments
PKey = table.Fields("Year").Value ' get record key
P2Key = table.Fields("Month").Value
folder = "C:PersonalDesktopa" & PKey & "" & P2Key & ""  'initialise folder name to create
If Len(Dir(folder, vbDirectory)) = 0 Then ' if folder does not exist then create it
MkDir (folder)
End If
'  Loop through each of the record's attachments'
While Not Attachments.EOF 'exit while loop at end of record's attachments
'  Save current attachment to disk in the above-defined folder.
Attachments.Fields("FileData").SaveToFile (folder)
Attachments.MoveNext 'move to next attachment
Wend
.MoveNext 'move to next record
Loop
End With
End Sub

您的问题可能是一个或多个较低级别的文件夹不存在。您应该检查每个级别,在循环之前一次检查前三个级别,然后因为您使用年份和月份作为进一步的子文件夹,所以也需要在循环中一次检查一个级别。

folder = "C:Personal"
If Len(Dir(folder, vbDirectory)) = 0 Then
MkDir folder
End If
folder = folder & "Personal"
If Len(Dir(folder, vbDirectory)) = 0 Then
MkDir folder
End If
folder = folder & "a"
If Len(Dir(folder, vbDirectory)) = 0 Then
MkDir folder
End If
With table ' For each record in table
Do Until .EOF 'exit with loop at end of table
Set Attachments = table.Fields("Attachments").Value 'get list of attachments
PKey = table.Fields("Year").Value ' get record key
If Len(Dir(folder & "" & PKey, vbDirectory)) = 0 Then
MkDir folder * "" & Pkey
End If 
P2Key = table.Fields("Month").Value
If Len(Dir(folder & "" & PKey & "" & PKey2, vbDirectory)) = 0 Then
MkDir folder * "" & Pkey & "" & PKey2
End If 
afolder = folder & "" & PKey & "" & P2Key  ' folder name for save
'  Loop through each of the record's attachments'
While Not Attachments.EOF 'exit while loop at end of record's attachments
'  Save current attachment to disk in the above-defined folder.
Attachments.Fields("FileData").SaveToFile (afolder)
Attachments.MoveNext 'move to next attachment
Wend
.MoveNext 'move to next record
Loop
End With

我不确定,但我怀疑.SaveToFolder的参数是否需要一个尾部反斜杠,所以请注意,我在修改您的代码时删除了它,并将其称为afolder,以避免混淆,并允许基于folder进行重建,因此,如果需要尾部反斜线,请将其放回。

最新更新