I am trying to achieve the following: I have a workbook that whose job is to loop through a set of input files (from different departments), all of which are supposed to be identical. However, i have noticed that some departments tend to rename their sheets at will. I have code that loops through all files and checks whether a given sheet named "Template" is there or not.
Now, i have a long time to plan for this, but once the input from departments start pouring in, i have very little time to verify everything and import it. One such thing is to implement a "fix errors" function, which, among other things, checks for the presence of the "Template" sheet in the workbook. If it is not there, i want the macro to open the workbook, allow the user (me) to find the correct sheet, manually rename it to "Template", and then save and close. Only then do I want the code to continue to run (checking the next workbook or other errors in this same workbook), in a similar way that happens when a mesage box or file dialog opens.
I have the following for this function for now (part of a larger code, project is a custom class):
If Not project.FileHasSheet Then
answer = MsgBox("Open file and add sheet?", vbYesNo + vbQuestion)
If answer = vbYes Then
Set tempWorkbook = Workbooks.Open(ThisWorkbook.Path & "/Inputfiler/" & project.filename)
MsgBox ("done")
tempWorkbook.Close
Else
'do something
End If
The messagebox "done" is going to be removed once this works. The code above just opens the workbook and immediately closes it.
If Not project.FileHasSheet Then
answer = MsgBox("Open file and add sheet?", vbYesNo + vbQuestion)
If answer = vbYes Then
Set tempWorkbook = Workbooks.Open(ThisWorkbook.Path & "/Inputfiler/" & project.filename)
Do Until IsFileOpen(ThisWorkbook.Path & "/Inputfiler/" & project.filename) = False
DoEvents
Loop
MsgBox ("done")
tempWorkbook.Close
Else
'do something
End If
This does not work either. The other workbook opens and the "hourglass" starts spinning, not allowing the user to edit the newly opened workbook. The IsFileOpen function is:
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
Case Else
Error errnum
End Select
End Function