VBA另存为自定义文件

时间:2018-08-13 07:57:29

标签: excel vba excel-vba file save-as

我一直试图将一些excel数据保存为自定义文本文件格式。通过关注this post,我并没有走得太远。 Excel引发运行时错误'13':类型不匹配。任何想法为什么会发生这种情况?

该错误发生在第三行:

设置对话框= Application.GetSaveAsFilename(FileFilter:=“自定义文件,*。custom”)

Sub SaveCustomData()
    Dim dialog As Variant
    Set dialog = Application.GetSaveAsFilename(FileFilter:="Custom file, *.custom")
    ' !!! The code runs this far !!!

    With dialog
        .InitialFileName = Application.ActiveWorkbook.Path & Application.PathSeparator
        .AllowMultiSelect = False

        Dim file As String
        Dim fso As FileSystemObject
        Set fso = New FileSystemObject
        Dim fileStream As TextStream

        If .Show = True Then
            file = .SelectedItems(1)

            Set fileStream = fso.CreateTextFile(dialog, ForWriting, True)

            ' Writing data to file here

            fileStream.Close

        End If
    End With
End Sub

1 个答案:

答案 0 :(得分:2)

Application.GetSaveAsFilename返回所选文件的名称(如果用户取消对话框,则返回False)。您不能(也不想)将其分配给您的dialog变量

您引用的帖子的问题使用Application.FileDialog(3)(3应该用常量msoFileDialogFilePicker代替),这将返回Dialog-其余代码的构建方式。

但是,在帖子的 answer 中,使用了Application.GetSaveAsFilename。由于此命令将实际工作表的文件夹用作起始文件夹,并且不允许多选,因此您的代码可以简化为

Sub SaveCustomData()
    Dim fileName As Variant
    fileName  = Application.GetSaveAsFilename(FileFilter:="Custom file, *.custom")
    if fileName = False then 
        MsgBox "No filename selected, data not saved"
        exit sub
    end if

    Dim file As String
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim fileStream As TextStream

    Set fileStream = fso.CreateTextFile(fileName, ForWriting, True)
    ...
End Sub