VBA - 浏览,选择文件并将文件另存为

时间:2015-06-18 20:39:11

标签: vba ms-access access-vba savefiledialog save-as

我正在创建一个包含表单和报告的访问数据库。在我的一个表单中,我希望能够转到选择文件(.pdf,.doc,.xls)的文件夹,然后将其保存在专用的“附件”文件夹中。

我知道OLE对象和附件函数,但这两者都将保存数据库中的附件。我试图远离这一点,因为必须能够轻松访问附件并使数据库更轻松。

我一直在用VBA玩

Application.FileDialog(msoFileDialogFilePicker)

Application.FileDialog(msoFileDialogSaveAs)

这是我到目前为止所做的,但它不起作用:

Option Compare Database

Private Sub Select_Save_Click()

Call SelectFile

End Sub


Public Function SelectFile() As String




 Dim FD As FileDialog
 Dim File_Name As String
 Dim path As String

path = "O:\foldername"

Set FD = Application.FileDialog(msoFileDialogFilePicker)

With FD
    .AllowMultiSelect = False
    .Title = "Please select file to save as attachment"
    If .Show = True Then

        File_Name = Dir(.SelectedItems(1))

        SelectFile = .SelectedItems(1)

        new_name = path & File_Name

        .SelectedItems.Item(1).SaveAsFile new_name

        Me.Attach_Save = new_name


    Else
        Exit Function
    End If

    Set FD = Nothing

End With



End Function

1 个答案:

答案 0 :(得分:1)

考虑使用FileCopy,因为.SaveAsFile方法可能无法在FD对象中使用。另外,SaveAsFile method主要与使用电子邮件附件的MS Outlook VBA相关联。

另外,对FD对象外的字符串变量使用Dir(),而不是FD对象内的变量数组.SelectedItems(1)

最后,请注意我在路径字符串中添加了最后的反斜杠。

Dim FD As FileDialog
Dim File_Name As String
Dim path As String

path = "O:\foldername\"

Set FD = Application.FileDialog(msoFileDialogFilePicker)

With FD
    .AllowMultiSelect = False
    .Title = "Please select file to save as attachment"
    If .Show = True Then
        SelectFile = .SelectedItems(1)
    Else
        Exit Function        
    End If
End With

File_Name = Dir(SelectFile)       

FileCopy SelectFile, path_name & File_Name

Set FD = Nothing