由于客户要求不能使用vb的common dialog,所以我使用API的GetSaveFileName方法来实现保存对话框的功能。代码如下:Private Const OFN_HIDEREADONLY = &H4
Private Const OFN_OVERWRITEPROMPT = &H2Private Declare Function GetSaveFileName Lib "comdlg32.dll" Alias "GetSaveFileNameA" (pOpenfilename As OPENFILENAME) As Long
  
Private Type OPENFILENAME
    lStructSize As Long
    hwndOwner As Long
    hInstance As Long
    lpstrFilter As String
    lpstrCustomFilter As String
    nMaxCustFilter As Long
    nFilterIndex As Long
    lpstrFile As String
    nMaxFile As Long
    lpstrFileTitle As String
    nMaxFileTitle As Long
    lpstrInitialDir As String
    lpstrTitle As String
    flags As Long
    nFileOffset As Integer
    nFileExtension As Integer
    lpstrDefExt As String
    lCustData As Long
    lpfnHook As Long
    lpTemplateName As String
End TypePublic Function ShowSaveDialog(hwnd As Long) As String
    Dim rtn As Integer
    Dim ofn As OPENFILENAME
    Dim fileName As String
    
On Error GoTo errExit    ofn.lStructSize = Len(ofn)
    ofn.hwndOwner = hwnd
    ofn.lpstrFile = "tablename.xls" + String$(255, Chr$(0))
    ofn.nMaxFile = 255
    ofn.lpstrFileTitle = String$(255, 0)
    ofn.nMaxFileTitle = 255
    ofn.lpstrInitialDir = Environ$("currentDir")
    ofn.lpstrFilter = "Microsoft Excel" + Chr$(0) + "*.xls"
    ofn.nFilterIndex = 1
    ofn.flags = OFN_HIDEREADONLY + OFN_OVERWRITEPROMPT
    ofn.lpstrTitle = "save file"
    rtn = GetSaveFileName(ofn)    If rtn >= 1 Then
        fileName = ofn.lpstrFile
        fileName = Left(fileName, InStr(fileName, Chr(0)) - 1)
        If InStr(fileName, ".xls") < 1 Then
            fileName = fileName + ".xls"
        End If
        ShowSaveDialog = fileName
    End If
    Exit Function
    
errExit:
    Err.Raise Err.Number, Err.Source, Err.Description
    
End Function
问题是我指定了ofn.flags = OFN_OVERWRITEPROMPT,当我选择一个已有文件时,会给出是否覆盖提示,但是如果我手动输入一个已存在的文件名(不带扩展名)时,却没有提示直接覆盖了。有什么方法可以解决这个问题吗?非常感谢

解决方案 »

  1.   

    "a" 和 "a.xls" 当然不同了,得到返回值后再判断时不自动添加 ".xls",直接提示文件类型不对要求重选。
      

  2.   

    ofn.lpstrFilter = "Microsoft Excel" + Chr$(0) + "*.xls"
    文件类型默认为xls ,我试过系统的保存对话框,或者用common dialog里的对话框
    在这种情况下,都是提示是否覆盖的,api里的方法判断是否保存时,好像是没有把默认的扩展名加上。按照用户的操作习惯,我们很少会输入扩展名的,头疼阿。。
      

  3.   

    后缀名可以自己判断,根据用户输入的文件名,判断最后4个字符是否 .ABC,如果是则不变,如果不是则加上
      

  4.   

    如果你是想要覆盖提示,加上
        ofn.lpstrDefExt = "xls"