Problem with GetOpenFile Function: Cancel Button freezes my app

Hi Experts,

I am using the GetOpenFile function. It is working well, except for pressing the CANCEL button causes the dialog box and the application to freeze. Only option is to close out of Access with the Task Manager.

While I have adapated the code to good effect, mostly, I don't understand it too well. Any help is super appreciated. Here is my code:


Option Compare Database

Type tagOPENFILENAME
lStructSize As Long
hwndOwner As Long
hInstance As Long
strFilter As String
strCustomFilter As String
nMaxCustFilter As Long
nFilterIndex As Long
strFile As String
nMaxFile As Long
strFileTitle As String
nMaxFileTitle As Long
strInitialDir As String
strTitle As String
Flags As Long
nFileOffset As Integer
nFileExtension As Integer
strDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type
Declare Function aht_apiGetOpenFileName Lib "comdlg32.dll" _
Alias "GetOpenFileNameA" (OFN As tagOPENFILENAME) As Boolean
Declare Function aht_apiGetSaveFileName Lib "comdlg32.dll" _
Alias "GetSaveFileNameA" (OFN As tagOPENFILENAME) As Boolean
Declare Function CommDlgExtendedError Lib "comdlg32.dll" () As Long
Global Const ahtOFN_READONLY = &H1
Global Const ahtOFN_OVERWRITEPROMPT = &H2
Global Const ahtOFN_HIDEREADONLY = &H4
Global Const ahtOFN_NOCHANGEDIR = &H8
Global Const ahtOFN_SHOWHELP = &H10
' You won't use these.
'Global Const ahtOFN_ENABLEHOOK = &H20
'Global Const ahtOFN_ENABLETEMPLATE = &H40
'Global Const ahtOFN_ENABLETEMPLATEHANDLE = &H80
Global Const ahtOFN_NOVALIDATE = &H100
Global Const ahtOFN_ALLOWMULTISELECT = &H200
Global Const ahtOFN_EXTENSIONDIFFERENT = &H400
Global Const ahtOFN_PATHMUSTEXIST = &H800
Global Const ahtOFN_FILEMUSTEXIST = &H1000
Global Const ahtOFN_CREATEPROMPT = &H2000
Global Const ahtOFN_SHAREAWARE = &H4000
Global Const ahtOFN_NOREADONLYRETURN = &H8000
Global Const ahtOFN_NOTESTFILECREATE = &H10000
Global Const ahtOFN_NONETWORKBUTTON = &H20000
Global Const ahtOFN_NOLONGNAMES = &H40000
' New for Windows 95
Global Const ahtOFN_EXPLORER = &H80000
Global Const ahtOFN_NODEREFERENCELINKS = &H100000
Global Const ahtOFN_LONGNAMES = &H200000


Function GetOpenFile(Optional varDirectory As Variant, _
Optional varTitleForDialog As Variant) As Variant
Forms!form1!LST_HOSPITALS.Visible = False
Forms!form1!lst_peers.Visible = False
Forms!form1!LST_RENEWAL_SELECTED.Visible = False
Forms!form1!lst_peers_selected.Visible = False
Forms!form1!add_renewal.Visible = False
Forms!form1!add_peer.Visible = False
Forms!form1!remove_peer.Visible = False
Forms!form1!remove_renewal.Visible = False
Forms!form1!Text21.Visible = False
Forms!form1!Text27.Visible = False

On Error GoTo HANDLECANCEL

Dim strFilter As String
Dim lngFlags As Long
Dim varFileName As Variant
' Specify that the chosen file must already exist,
' don't change directories when you're done
' Also, don't bother displaying
' the read-only box. It'll only confuse people.
lngFlags = ahtOFN_FILEMUSTEXIST Or _
ahtOFN_HIDEREADONLY Or ahtOFN_NOCHANGEDIR

If Forms!form1!MARKET_COMBO = "ny" Then
varDirectory = "J:\Hospital Network Analysis (Rachael)\Interim Analysis"
Else
varDirectory = "c:\"
End If

varTitleForDialog = "SAVE DEAL SUMMARY REPORT"


' Define the filter string and allocate space in the "c"
' string Duplicate this line with changes as necessary for
' more file templates.
strFilter = ahtAddFilterItem(strFilter, _
"Excel (*.xls)")
' Now actually call to get the file name.



varFileName = ahtCommonFileOpenSave( _
OpenFile:=False, _
InitialDir:=varDirectory, _
Filter:=strFilter, _
Flags:=lngFlags, _
DialogTitle:=varTitleForDialog)


If Not IsNull(varFileName) Then
varFileName = TrimNull(varFileName)
Else
Exit Function
End If






DoCmd.Minimize
'copy shell xls to a new deal specific file'
Dim sSource As String
Dim excelvar As String
If Forms!form1!MARKET_COMBO = "ny" Then
sSource = "\\oh2shared\reimbstrategyanalysis\HealthCare Analytics\Hospital Contracting\DEAL SUMMARY APPLICATION\templates\deal_summary_template.XLS"
Else
sSource = "\\oh2shared\reimbstrategyanalysis\HealthCare Analytics\Hospital Contracting\DEAL SUMMARY APPLICATION\templates\deal_summary_template_not_ny.XLS"
End If



FileCopy sSource, varFileName & ".xls"

'open the logic for packets dbase and run the queries'
Dim appAccess As Access.Application
    Dim dbStr As String
    dbStr = CurrentProject.Path & "\Logic for Packets.mdb"
    Set appAccess = New Access.Application
    appAccess.Visible = False
    appAccess.OpenCurrentDatabase dbStr
    appAccess.DoCmd.OpenForm "frm_automate_deal_summary"
Set appAccess = Nothing


'transfer tbl_financial_calculations to spreadsheet'
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel97, "tbl_financial_calculations", varFileName, True




Dim rs As DAO.Recordset
Dim ssql As String

Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Set xlApp = New Excel.Application
Dim Sheet As Object

    With xlApp
        .Visible = False
    Set xlWB = .Workbooks.Open(varFileName & ".xls", , False)
    
    

Set Sheet = xlApp.ActiveWorkbook.Sheets("raw_data")

ssql = "SELECT tbl_data_tab.* from tbl_data_tab;"
Set rs = CurrentDb.OpenRecordset(ssql)
Sheet.Range("A2").CopyFromRecordset rs

rs.Close
Set rs = Nothing

End With

ActiveWorkbook.Save
ActiveWorkbook.Close

Set xlApp = Nothing

DoCmd.Hourglass False


If Forms!form1!SYS_FAC_OPTION = 1 Then
excelvar = Forms!form1!COMBO_FAC_SYS
Else
excelvar = Forms!form1!LST_RENEWAL_SELECTED.ItemData(0)
End If

Forms!form1!LST_HOSPITALS.Visible = False
Forms!form1!lst_peers.Visible = False
Forms!form1!LST_RENEWAL_SELECTED.Visible = False
Forms!form1!lst_peers_selected.Visible = False
Forms!form1!add_renewal.Visible = False
Forms!form1!add_peer.Visible = False
Forms!form1!remove_peer.Visible = False
Forms!form1!remove_renewal.Visible = False
Forms!form1!Text21.Visible = False
Forms!form1!Text27.Visible = False


messagevar = MsgBox("Your Deal Summary Report for " & excelvar & " has been successfully saved.", vbInformation, "Confirmation")



Forms!form1!LST_HOSPITALS.Visible = True
Forms!form1!lst_peers.Visible = True
Forms!form1!LST_RENEWAL_SELECTED.Visible = True
Forms!form1!lst_peers_selected.Visible = True
Forms!form1!add_renewal.Visible = True
Forms!form1!add_peer.Visible = True
Forms!form1!remove_peer.Visible = True
Forms!form1!remove_renewal.Visible = True
Forms!form1!Text21.Visible = True
Forms!form1!Text27.Visible = True



HANDLECANCEL:
Exit Function


End Function
Function ahtCommonFileOpenSave( _
Optional ByRef Flags As Variant, _
Optional ByVal InitialDir As Variant, _
Optional ByVal Filter As Variant, _
Optional ByVal FilterIndex As Variant, _
Optional ByVal DefaultExt As Variant, _
Optional ByVal FileName As Variant, _
Optional ByVal DialogTitle As Variant, _
Optional ByVal hwnd As Variant, _
Optional ByVal OpenFile As Variant) As Variant
' This is the entry point you'll use to call the common
' file open/save dialog. The parameters are listed
' below, and all are optional.
'
' In:
' Flags: one or more of the ahtOFN_* constants, OR'd together.
' InitialDir: the directory in which to first look
' Filter: a set of file filters, set up by calling
' AddFilterItem. See examples.
' FilterIndex: 1-based integer indicating which filter
' set to use, by default (1 if unspecified)
' DefaultExt: Extension to use if the user doesn't enter one.
' Only useful on file saves.
' FileName: Default value for the file name text box.
' DialogTitle: Title for the dialog.
' hWnd: parent window handle
' OpenFile: Boolean(True=Open File/False=Save As)
' Out:
' Return Value: Either Null or the selected filename

On Error GoTo error_handler

Dim OFN As tagOPENFILENAME
Dim strFileName As String
Dim strFileTitle As String
Dim fResult As Boolean
' Give the dialog a caption title.
If Forms!form1!MARKET_COMBO = "ny" Then
InitialDir = "J:\Hospital Network Analysis (Rachael)\Interim Analysis"
Else
If IsMissing(InitialDir) Then InitialDir = CurDir
End If
If IsMissing(Filter) Then Filter = ""
If IsMissing(FilterIndex) Then FilterIndex = 1
If IsMissing(Flags) Then Flags = 0&
If IsMissing(DefaultExt) Then DefaultExt = ""
Dim excelvar As String
If Forms!form1.SYS_FAC_OPTION = 1 Then
excelvar = Forms!form1.COMBO_FAC_SYS & "_" & Year(Date) & "_" & Month(Date) & "_" & Day(Date)
Else
excelvar = Forms!form1.LST_RENEWAL_SELECTED.ItemData(0) & "_" & Year(Date) & "_" & Month(Date) & "_" & Day(Date)
End If

FileName = excelvar
If IsMissing(DialogTitle) Then DialogTitle = ""
If IsMissing(hwnd) Then hwnd = Application.hWndAccessApp
If IsMissing(OpenFile) Then OpenFile = False
' Allocate string space for the returned strings.
strFileName = Left(FileName & String(256, 0), 256)
strFileTitle = String(256, 0)
' Set up the data structure before you call the function
With OFN
.lStructSize = Len(OFN)
.hwndOwner = hwnd
.strFilter = Filter
.nFilterIndex = FilterIndex
.strFile = strFileName
.nMaxFile = Len(strFileName)
.strFileTitle = strFileTitle
.nMaxFileTitle = Len(strFileTitle)
.strTitle = DialogTitle
.Flags = Flags
.strDefExt = DefaultExt
.strInitialDir = InitialDir
' Didn't think most people would want to deal with
' these options.
.hInstance = 0
.strCustomFilter = ""
.nMaxCustFilter = 0
.lpfnHook = 0
'New for NT 4.0
.strCustomFilter = String(255, 0)
.nMaxCustFilter = 255
End With
' This will pass the desired data structure to the
' Windows API, which will in turn it uses to display
' the Open/Save As Dialog.

fResult = aht_apiGetSaveFileName(OFN)


' The function call filled in the strFileTitle member
' of the structure. You'll have to write special code
' to retrieve that if you're interested.
If fResult Then
' You might care to check the Flags member of the
' structure to get information about the chosen file.
' In this example, if you bothered to pass in a
' value for Flags, we'll fill it in with the outgoing
' Flags value.
If Not IsMissing(Flags) Then Flags = OFN.Flags
ahtCommonFileOpenSave = TrimNull(OFN.strFile)
Else
ahtCommonFileOpenSave = vbNullString
End If


    
error_handler:
Exit Function

End Function
Function ahtAddFilterItem(strFilter As String, _
strDescription As String, Optional varItem As Variant) As String
' Tack a new chunk onto the file filter.
' That is, take the old value, stick onto it the description,
' (like "Databases"), a null character, the skeleton
' (like "*.mdb;*.mda") and a final null character.

If IsMissing(varItem) Then varItem = "*.*"
ahtAddFilterItem = strFilter & _
strDescription & vbNullChar & _
varItem & vbNullChar
End Function
Private Function TrimNull(ByVal strItem As String) As String
Dim intPos As Integer
intPos = InStr(strItem, vbNullChar)
If intPos > 0 Then
TrimNull = Left(strItem, intPos - 1)
Else
TrimNull = strItem
End If
End Function

Open in new window

tscott_72Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott McDaniel (Microsoft Access MVP - EE MVE )Infotrakker SoftwareCommented:
Your code uses the GetOpenFile API calls, which means the Cancel button is managed by Windows. If using the Cancel freezes your application, then you may have troubles with your Windows installation - have you applied all updates?

You might also do maintenance on your database. First, make a backup copy, then do this:

1) Compact your database.
2) Compile the database. Open the VBA Editor, click Debug - Compile. Fix any errors, continue doing this until the menuitem is disabled.
3) Compact again.
4) Build a new, blank database and import everything into that new database. Be sure to remake any references if needed.

tscott_72Author Commented:
i could try all these suggestions. I appreciate. However, I'm thinking the problem is in the ocde itself. I have other dbases that also use the API call and the cancel button works fine. I will try these suggestions
Jim Dettman (Microsoft MVP/ EE MVE)President / OwnerCommented:

 Put a STOP at line 105 of your code post.

 Execute the app and see if you hit the stop when you cancel the dialog.  If you do, then the fault is in your code.

 Use F8 to step through the code to find out where your getting hung up.  

  The other issue may be what your feeding the dialog.  Check that the parameters specified on 99-104 are valid.

  I'd be surprised if it was Windows broken in such a fundamental way (you'd be having lots of other problems and not just with this app).

JimD.
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

Scott McDaniel (Microsoft Access MVP - EE MVE )Infotrakker SoftwareCommented:
<I have other dbases that also use the API call and the cancel button works fine>

Then this would indicate trouble with the database, it would seem (assuming that you're correctly calling the API, as JimD suggests).

A compact takes about 10 seconds to perform in most cases. At the very least, try that.
tscott_72Author Commented:
cool.... problem solved!

put the STOP at 105. Code was hitting the Stop. VARFILENAME= "" when the cancel button is hit. 107 attempted to exit function when VARFILENAME is null. Apparently, "" DOES NOT EQUAL NULL. Change the condition to = "" and the it now exits the function when I press cancel.

Thank you for the programming technique. Back to basics can solve real problems.

Dale FyeOwner, Dev-Soln LLCCommented:
If you hit cancel, the api call (ahtCommonFileOpenSave) will return an empty string, not a NULL value, so you should be testing for the Len(varFileName) = 0 rather than IsNull(varFileName)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Applications

From novice to tech pro — start learning today.