How to Update a Microsoft Project Sub-Project Using VBA - vba

We are attempting to update the status date in the sub-projects of a Schedule using VBA following the suggestions here and here. Ideally we'd like to keep the files closed while doing so, but are open to suggestions if that isn't strictly possible.
The relevant code looks like this:
If ActiveProject.Subprojects.count > 0 Then
Dim msg: msg = MsgBox("Change Status Date for unopened Subprojects?", vbYesNo, "Change Status Dates for Unopened Subprojects?")
Dim subp As SubProject
If msg = vbYes Then
Application.StatusBar = "Updating Sub-Projects..."
For Each subp In ActiveProject.Subprojects
subp.SourceProject.StatusDate = newDate
subp.SourceProject.SaveAs subp.SourceProject.Name
Next
End If
End If
This appears to work, however when we open the sub-project files the Status Date hasn't changed (as seen on Project > Status > Status Date). The date below is the same before and after:
Alternatives that also have not worked.
We've tried setting Projects(subp.SourceProject.Name).StatusDate:
If ActiveProject.Subprojects.count > 0 Then
Dim msg: msg = MsgBox("Change Status Date for unopened Subprojects?", vbYesNo, "Change Status Dates for Unopened Subprojects?")
Dim subp As SubProject
If msg = vbYes Then
Application.StatusBar = "Updating Sub-Projects..."
For Each subp In ActiveProject.Subprojects
Projects(subp.SourceProject.Name).StatusDate = newDate
subp.SourceProject.SaveAs subp.SourceProject.Name
Next
End If
End If
We've tried to open the sub-projects first and then to change the value (we've tried both FileOpen & FileOpenEx):
If ActiveProject.Subprojects.count > 0 Then
Dim msg: msg = MsgBox("Change Status Date for unopened Subprojects?", vbYesNo, "Change Status Dates for Unopened Subprojects?")
Dim subp As SubProject
If msg = vbYes Then
Application.StatusBar = "Updating Sub-Projects..."
For Each subp In ActiveProject.Subprojects
FileOpen subp.SourceProject.Path
subp.SourceProject.StatusDate = newDate
FileClose pjSave
Next
End If
End If
And then we've tried saving the sub-projects in various ways using:
subp.SourceProject.SaveAs subp.SourceProject.Name
Projects(subp.SourceProject.path).SaveAs subp.SourceProject.Name
As an interesting data point, we do notice that both the SourceProject.StatusDate and Projects(subp.SourceProject.Name).StatusDate for a given sub-project are what we set them to, even if the sub-project, once opened in MSP, does not reflect the value in the interface.
Note: we have tried closing/re-opening and manual save all (user input). No go.
Any suggestions are more than welcome.
EDIT #1
Note that we have also attempted saving the master schedule following the loop using two methods.
First, code leading up to the save:
'save name of Master Schedule to imsProj
dim imsProj as string: imsProj = ActiveProj.Name
If ActiveProject.Subprojects.count > 0 Then
'Here is where we run the above loop
End If
'Ensure the Master Schedule is the active project
Projects(imsProj).Activate
'Master Schedule save goes here. See below.
Then:
Save Method 1
'Save all open Projects, including master
For i = 1 To Projects.count
Projects(i).SaveAs Projects(i).Name
Next i
Save Method 2:
FileSave
Neither works.
Is there a setting in MSP that we are not considering?

Instead of trying to save each subproject individually, save the entire master at the end. Turning of alerts prevents a pop-up confirmation box for each subproject.
Sub SetSubProjectStatusDate()
Dim newDate As Date
newDate = #1/11/2022#
If ActiveProject.Subprojects.Count > 0 Then
Dim msg As VbMsgBoxResult
msg = MsgBox("Change Status Date for unopened Subprojects?", vbYesNo + vbQuestion _
, "Change Status Dates?")
If msg = vbYes Then
Application.StatusBar = "Updating Sub-Projects..."
Dim subp As Subproject
For Each subp In ActiveProject.Subprojects
subp.SourceProject.StatusDate = newDate
Next
DisplayAlerts = False
FileSave
DisplayAlerts = True
End If
End If
End Sub

This is incredibly frustrating, but it appears the IMS and its subprojects were somehow corrupted. No evident cause, no evident effect other than with how the status dates appear. Using a fresh set of MPPs resolved the matter.
Here is the final working code:
If ActiveProject.Subprojects.count > 0 Then
Dim msg: msg = MsgBox("Change Status Date for unopened Subprojects?", vbYesNo, "Change Status Dates for Unopened Subprojects?")
Dim subp As SubProject
If msg = vbYes Then
Application.StatusBar = "Updating Sub-Projects..."
For Each subp In ActiveProject.Subprojects
subp.SourceProject.StatusDate = temp
Next
End If
End If
Projects(imsProj).Activate
FileSave

Related

Auto-updating Power Query Connection via VBA when closing a file

I have an excel workbook (which is updated daily) to which I have established a couple power query connections, they look like this:
IMG
When clicking the little button to update the connection it works fine, updates, new lines are added, changes in data happen. I've then set out to execute this update through VBA in an automatic fashion when the data source files finishes being worked on and is closed (In a manner that would make opening the file with the queries and manually updating them unnecessary), following are examples of what I've tried(All using the "Workbook_BeforeClose" event):
Method 1 (Unsuccessful):
Sub Workbook_BeforeClose(cancel As Boolean)
CarryOn = MsgBox("Update connections? (May take a minute)", vbYesNo, "Update connections")
If CarryOn = vbYes Then
Dim strFilename As String: strFilename = "R:\filepath\Querydestination.xlsm"
Dim QD As Workbook 'QD = Query Destination
Set QD = Workbooks.Open(Filename:=strFilename)
QD.RefreshAll
QD.Connections("Query - Database").Refresh
QD.Connections("Query - Support$_FilterDatabase").Refresh
QD.Save
QD.Close
ThisWorkbook.Save
Beep
MsgBox "Connections updated!"
End If
End Sub
I've since found the code from the first answer of the following post:
Auto-updating Power Query Connection via VBA
The code currently looks like this:
Sub Workbook_BeforeClose(cancel As Boolean)
CarryOn = MsgBox("Update connections? (May take a minute)", vbYesNo, "Update connections")
If CarryOn = vbYes Then
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:= _
"R:\filepath\Database.xlsb" _
, FileFormat:=50
Dim strFilename As String: strFilename = "R:\filepath\Querydestination.xlsm"
Dim QD As Workbook 'QD = Query Destination
Set QD = Workbooks.Open(Filename:=strFilename)
Dim con As WorkbookConnection
Dim Cname As String
For Each con In ActiveWorkbook.Connections
If Left(con.Name, 8) = "Query - " Then
Cname = con.Name
With ActiveWorkbook.Connections(Cname).OLEDBConnection
.BackgroundQuery = False
.Refresh
End With
End If
Next
QD.Save
QD.Close
ThisWorkbook.Save
Beep
MsgBox "Connections updated!"
Application.DisplayAlerts = True
End If
End Sub
Here's the problem: I've tried Refresh_all, Update connections, Updtade individual connection by name and a bunch of other stuff, only the method in the link and shown in the code above has worked. Sometimes it hiccups in the .Refresh line but thats it. I works on my machine, when opening the Query Destination file new lines and changes are there, without the need to manually open the file and hit the "Refresh" or "Refresh all" buttons.
The only matter is: the code runs smoothly sometimes, but sometimes it doesn't and throws an error: [IMG] [IMG].
I really don't know what is causing it, the queries destination workbook is not open and nobody is using it, I've made sure of that. How to stop this error from occuring?

AddIns.Add statement throwing an Internal Error 51

I am trying to install addins programmatically (more precisely, it is automated version update on Workbook_Open event) but I have run into an issue with the AddIns.Add method, which just "does not work". I copy the desired adding into C:\Users\[username]\Documents\Addins and then feed the full filepath to AddIns.Add, however the addin is not added, as evidenced by the subsequent statement failing (subscript out of range, the name of the supposedly added addin does not exist).
During the install attempt, the execution simply runs through the AddIns.Add without any issue (except the result) but on stepping through, I am getting Internal error (Error 51). I have tried a number of ways to work around that, add Application.Wait before and after the AddIns.Add to make sure it has sufficient time, putting it into a Do While Loop statement to attempt multiple executions, but to no avail.
AddIns.Add Filename:=sInstallPath & sFile
AddIns(sAddinFullName).Installed = True
Btw this worked until yesterday, when I did a couple codes updates but not even remotely close to this area. I think I had some issues with this in past because the statement was envelopped by Application.Wait (Now + TimeValue("0:00:01")), which I think resolved probably a similar issue but I cannot recall that any more.
Edit: Adding a broader part of the code - a function that does the installation proper and on success, returns True.
Function InstallAddin(sFullPath, sAddinName) As Boolean
Dim oAddin As Object
Dim bAdded As Boolean
Dim i As Integer
Do Until bAdded = True Or i = 10
For Each oAddin In AddIns
If oAddin.Name = sAddinName Then
bAdded = True
Exit For
End If
Next oAddin
If bAdded = False Then
'Application.Wait (Now + TimeValue("0:00:01"))
AddIns.Add Filename:=sFullPath, CopyFile:=False
Debug.Print "Attempt " & i
'Application.Wait (Now + TimeValue("0:00:01"))
End If
i = i + 1
Loop
If bAdded = True Then
'disable events to prevent recurrence - installing addin counts as opening its workbook
Application.EnableEvents = False
AddIns(sAddinName).Installed = True
Application.EnableEvents = True
InstallAddin = True
End If
End Function
sFullPath : "C:\Users\Eleshar\Documents\Addins\MyAddin - v.0.25.xlam"
sAddinName : "MyAddin - v.0.25"
The "MyAddin - v.0.25.xlam" file is present in the installation path.
There is a piece of code elsewhere, which ensures that a regular WB is open during this event.
Edit 2: The full functionality of the macro is:
On opening the file by a user, offering self-install.
On opening the file by a user, checking for previous installed versions, offering self-installation (after which it removes the old versions, including itself).
On Workbook_Open, checking a Sharepoint repository for any new versions, offering to install the newest one available and removing any older versions including itself.
Edit 3: So I found an interesting thing... AddIns.Add does not seem to work when executed from the code (the addin does not get listed in Developer > Addins). However when I type the same exact statement into the immediate window during the execution, it works and then the addin can get installed...
Since you do not show all your used code, please try the next one. I am using it to auto install the add-ins I design:
Private Sub Workbook_Open()
Dim Name As String, tmp As Boolean, n As Boolean, Merk As String
Name = ThisWorkbook.BuiltinDocumentProperties(1) '(1)
On Error Resume Next
tmp = AddIns(Name).Installed
If Err.Number <> 0 Then
Err.Clear: On Error GoTo 0
If Workbooks.Count = 0 Then n = True
If n Then
Workbooks.Add
Merk = ActiveWorkbook.Name
End If
AddIns.Add FileName:=ThisWorkbook.FullName
AddIns(Name).Installed = True
If n Then Workbooks(Merk).Close False
End If
On Error GoTo 0
End Sub
'(1) it represents the Add-inn title. It can be set programmatically or manual in Properties - Details - Title. When add-in is not open!
So I did not really figure out the issue with AddIns.Add, however I worked around that but having the macro directly edit the Excel registry keys to install the add in.
Sub AddinInstall(sAddinName As String, ByVal sFullPath As String)
Dim oShell As Object: Set oShell = CreateObject("WScript.Shell")
Dim i As Integer: i = 0
Dim iIndex As Integer
Dim sRegKey As String: sRegKey = "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Excel\Options\OPEN"
Dim sSZ As String
sFullPath = ChrW(34) & sFullPath & ChrW(34)
On Error Resume Next
Do 'loop through registry keys (non-existent key results in error, so errors must be disabled) to find if lower version is installed
i = i + 1
sSZ = ""
sSZ = oShell.RegRead(sRegKey & CStr(i))
If Len(sSZ) > 0 Then
If sSZ Like "*" & sAddinName & "*" Then
Debug.Print sSZ
iIndex = i 'get number at the end of registry key name
End If
End If
Loop Until Len(sSZ) = 0
If iIndex > 0 Then 'previous version installed - overwrite
oShell.RegWrite sRegKey & CStr(iIndex), sFullPath, "REG_SZ"
Else 'previous version not found, create new registry key
oShell.RegWrite sRegKey & CStr(i), sFullPath, "REG_SZ"
End If
On Error GoTo 0
End Sub

VBA Script to check if text file is open or not

I am checking if a file is open or not that is a .txt file
Private Sub CommandButton1_Click()
Dim strFileName As String
' Full path and name of file.
strFileName = "D:\te.txt"
' Call function to test file lock.
If Not FileLocked(strFileName) Then
' If the function returns False, open the document.
MsgBox "not open"
Else
MsgBox "open"
End If
End Sub
Function FileLocked(strFileName As String) As Boolean
On Error Resume Next
' If the file is already opened by another process,
' and the specified type of access is not allowed,
' the Open operation fails and an error occurs.
Open strFileName For Binary Access Read Write Lock Read Write As #1
Close #1
' If an error occurs, the document is currently open.
If Err.Number <> 0 Then
' Display the error number and description.
MsgBox "Error #" & Str(Err.Number) & " - " & Err.Description
FileLocked = True
Err.Clear
End If
End Function
It turns out .txt when opened using notepad doesn't lock the file, so it can not be known if a .txt file is open or not. And hence, if that .txt file is opened in Wordpad or Sakura, etc., your code should work or at least other code from the net should work.
I found that if a text file is opened using FileSystemObject, then the file is not locked and can still be edited by other users. As a potential workaround, you could make a file with a single bit to indicate when the other file is in use, and include checking that bit in your code. Here's my code as a rough example:
'FSO parameters
Const ForAppending = 8
Const ForReading = 1
Const ForWriting = 2
Sub WriteToFile()
Set fso = CreateObject("Scripting.FileSystemObject")
'Check the current lock bit (1 is locked, 0 is unlocked)
Set FileLock = fso.OpenTextFile("C:\FileLock.txt", ForReading)
Dim LockBit As Integer
LockBit = FileLock.ReadAll
FileLock.Close
'If the bit is 1 (file in use) then wait 1 second and try again (up to 10 times)
For try = 1 To 10
If LockBit = 1 Then
Application.Wait (Now + TimeValue("0:00:1"))
Set FileLock = fso.OpenTextFile("C:\FileLock.txt", ForReading)
LockBit = FileLock.ReadAll
FileLock.Close
Else: GoTo Line1 'when the bit is 0 (file available)
End If
If try = 10 Then
MsgBox "File not available"
Exit Sub
End If
Next try
Line1:
Call LockTheFile(fso, True) 'Change the lock bit to "1" to show the file's in use
Set WriteFile = fso.OpenTextFile("C:\WriteFile.txt", ForWriting)
'Do what you will with the file
MsgBox "Write Successful"
WriteFile.Close
Call LockTheFile(fso, False) 'Change the lock bit to "0" to show the file's available
End Sub
I made this sub separate to make the main code more streamlined
Sub LockTheFile(fso, SetLock As Boolean)
'Write "1" to a lock file to indicate the text file is in use, or "0" to indicate not in use
Set BitFile = fso.CreateTextFile("C:\FileLock.txt", True)
If SetLock = True Then
BitFile.WriteLine "1"
Else
BitFile.WriteLine "0"
End If
BitFile.Close
End Sub

VBA excel Application.getsaveasfilename error 13

I'm trying to create a macro to have the user save a backup of the workbook to a specific place. I tried my code below but got an error 13 message. I don't need it to be saved as a macro-enabled workbook, but I thought that would be easier.
Sub openSaveDialog()
'
' gives error 13 message when clicking save
'
Dim saveSuccess As Boolean
Dim fNameRec As String
Dim dateNow As String
Dim saveToDir As String
saveToDir = "Z:\location of save\Old Archive spreadsheets\"
dateNow = Format(Now(), "mmddyyyy")
fNameRec = saveToDir & "BinderArchiveBackup_" & dateNow
Sheets(3).Range("E25") = fNameRec
'check if backed up today
If (Sheets(3).Range("E22") = Date) Then
MsgBox "backup already saved today no need to save again"
Exit Sub
End If
'open save as window
saveSuccess = Application.GetSaveAsFilename(InitialFileName:=fNameRec, FileFilter:= _
"Excel Files (*.xlsx)," & "*.xlsx, Macro Enabled" & _
"Workbook (*.xlsm), *xlsm")
'if backup saved, update date of last backup
If saveSuccess Then
Sheets(3).Range "E22" = Date
MsgBox "save successful"
End If
'if backup not saved, inform user
If Not saveSuccess Then
MsgBox "save canceled, please save backup before adding new items to the archive today"
End If
End Sub
Things I tried tweaking
File filter to just macro enabled
File filter to just excel workbook
Blank file filter saving as type all files
Blank file filter with .xlsx at the end of the name
initial filename without directory but with ChDir so it opens in the right save location anyway
Any help would be great.
Save as window that opens
GetSaveAsFilename returns a Variant, which will be a boolean False if the user cancelled the SaveAs dialog, or a string containing the filename that they chose if they didn't cancel the dialog.
Your line saying
Dim saveSuccess As Boolean
will cause an issue if a non-boolean value is returned. So use
Dim saveSuccess As Variant
instead.
This will still leave you with other problems though:
Sheets(3).Range "E22" = Date is invalid, and is probably meant to be Sheets(3).Range("E22") = Date
*xlsm should probably be *.xlsm
At no point are you actually saving the file. Your final bits of code should probably be something like:
If saveSuccess = False Then
'if backup not saved, inform user
MsgBox "save canceled, please save backup before adding new items to the archive today"
Else
If UCase(Right(saveSuccess, 5)) = ".XLSM" Then
ActiveWorkbook.SaveAs saveSuccess, xlOpenXMLWorkbookMacroEnabled
'if backup saved, update date of last backup
Sheets(3).Range("E22") = Date
MsgBox "save successful"
ElseIf UCase(Right(saveSuccess, 5)) = ".XLSX" Then
ActiveWorkbook.SaveAs saveSuccess, xlOpenXMLWorkbook
'if backup saved, update date of last backup
Sheets(3).Range("E22") = Date
MsgBox "save successful"
Else
MsgBox "Unrecognised file extension chosen - backup not created"
End If
End If

Import files into workbook using For Loop. Check that missing file matches selected file

I wrote the following procedure to import, copy and paste the information from 5 workbooks into their designated worksheets of my main workbook. It is extremely important that the imported files are copied and pasted on the correct sheet, otherwise, my whole project's calculations fail.
The procedure is written so that if the file to be imported is not found in the designated path an Open File Dialog opens and the user can browse for the file. Once the file is found, the procedure imports that file into the main workbook.
It all works fine, but I jus realized that if a file is missing and the user checks an file name in the directory, it will bring in that file and paste it on the workbook. This is a problem, and I do not know how to prevent or warn the user from importing the wrong file.
In other words my loop starts as For n As Long = 1 to 5 Step 1 If the file that is missing is n=3 or statusReport.xls and the Open File Dialog opens, the user can select any file on that directory or any other and pasted on the designated sheet. What I want is to warn the user that it has selected a file not equal to n=3 or statusReport.xls
Here is the functions for the 5 worksheets to be imported and the sheets to be pasted on:
Public Function DataSheets(Index As Long) As Excel.Worksheet
'This function indexes both the data employee and position
'export sheets from Payscale.
'#param DataSheets, are the sheets to index
Select Case Index
Case 1 : Return xlWSEmployee
Case 2 : Return xlWSPosition
Case 3 : Return xlWSStatusReport
Case 4 : Return xlWSByDepartment
Case 5 : Return xlWSByBand
End Select
Throw New ArgumentOutOfRangeException("Index")
End Function
Public Function GetImportFiles(Index As Long) As String
'This function houses the 5 files
'used to import data to the project
'#param GetImportFiles, are the files to be
'imported and pasted on the DataSheets
Select Case Index
Case 1 : Return "byEmployee.csv"
Case 2 : Return "byPosition.csv"
Case 3 : Return "statusReport.xls"
Case 4 : Return "byDepartment.csv"
Case 5 : Return "byband.csv"
End Select
Throw New ArgumentOutOfRangeException("Index")
End Function
This is the procedure to import, copy and paste the files. It is heavily commented for my own sanity and for those trying to figure out what is going on. I also noted below where I need to insert the check to make sure that the file selected equals n
'This procedure imports the Client Listing.xlsx sheet. The procedure checks if the file is
'in the same directory as the template. If the file is not there, a browser window appears to allow the user
'to browse for the missing file. A series of message boxes guide the user through the process and
'verifies that the user picked the right file. The user can cancel the import at any time.
'Worksheet and Workbook Variables
Dim xlDestSheet As Excel.Worksheet
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim strImportFile As String
Dim xlWBSource As Object = Nothing
Dim xlWBImport As Object = Nothing
'Loop through the 5 sheets and files
For n As Long = 1 To 5 Step 1
strImportFile = xlWBPath & "\" & GetImportFiles(n)
xlDestSheet = DataSheets(n)
'Convert the indexed sheet name to a string
'so that it can be passed through the xlWB.Worksheets paramater
Dim strDestSheetName As String = xlDestSheet.Name
'If the file is found, then import, copy and paste the
'data into the corresponding sheets
If Len(Dir(strImportFile)) > 0 Then
xlWBSource = Globals.ThisWorkbook.Application.ActiveWorkbook
xlWBImport = Globals.ThisWorkbook.Application.Workbooks.Open(strImportFile)
xlWBImport.Worksheets(1).Cells.Copy(xlWB.Worksheets(strDestSheetName).Range("A1"))
xlWBImport.Close()
Else
'If a sheet is missing, prompt the user if they
'want to browse for the file.
'Messagbox variables
Dim msbProceed As MsgBoxResult
Dim strVmbProceedResults As String = ("Procedure Canceled. Your project will now close")
Dim strPrompt As String = " source file does not exist." & vbNewLine & _
"Press OK to browse for the file or Cancel to quit"
'If the user does not want to browse, then close the workbook, no changes saved.
msbProceed = MsgBox("The " & strImportFile & strPrompt, MsgBoxStyle.OkCancel + MsgBoxStyle.Question, "Verify Source File")
If msbProceed = MsgBoxResult.Cancel Then
msbProceed = MsgBox(strVmbProceedResults, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical)
xlWB.Close(SaveChanges:=False)
Exit Sub
Else
'If the user does want to browse, then open the File Dialog
'box for the user to browse for the file
'Open Fil Dialog box variable and settings
Dim ofdGetOpenFileName As New OpenFileDialog()
ofdGetOpenFileName.Title = "Open File " & strImportFile
ofdGetOpenFileName.InitialDirectory = xlWBPath
ofdGetOpenFileName.Filter = "Excel Files (*.xls;*.xlsx; *.xlsm; *.csv)| *.xls; *.csv; *.xlsx; *.xlsm"
ofdGetOpenFileName.FilterIndex = 2
ofdGetOpenFileName.RestoreDirectory = True
'If the user presses Cancel on the box, warn that no
'file has been selected and the workbook will close
If ofdGetOpenFileName.ShowDialog() = System.Windows.Forms.DialogResult.Cancel Then
'Message box variables
Dim msbContinue As MsgBoxResult
Dim strAlert As String = ("You have not selected a workbook." & vbNewLine & _
"The project will now close without saving changes")
'Once the user presses OK, close the file and do not save changes
msbContinue = MsgBox(strAlert, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "No Workbook Seletected")
xlWB.Close(SaveChanges:=False)
Exit Sub
Else
'If the user does select the file, then import the file
'copy and paste on workbook.
'***Here is where I need to check that strImportFile =n, if it does not warn the user******
strImportFile = ofdGetOpenFileName.FileName
xlWBImport = Globals.ThisWorkbook.Application.Workbooks.Open(strImportFile)
xlWBImport.Worksheets(1).Cells.Copy(xlWB.Worksheets(strDestSheetName).Range("A1"))
xlWBImport.Close()
End If
Try
'Import the remainder of the files
xlWBSource = Globals.ThisWorkbook.Application.ActiveWorkbook
xlWBImport = Globals.ThisWorkbook.Application.Workbooks.Open(strImportFile)
xlWBImport.Worksheets(1).Cells.Copy(xlWB.Worksheets(strDestSheetName).Range("A1"))
xlWBImport.Close()
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical, "Unexpected Error")
End Try
End If
End If
Next
End Sub
Any help will be appreciated and/or any recommendations to improve my code as well.
thank you.
This looks like a possible application for a GoTo - objected to by many but it does still have its uses!!
Compare the file name with an if statement and if incorrect notify the user and return them to the browse dialog.
Else
Retry:
'If the user does want to browse, then open the File Dialog
'box for the user to browse for the file
'Open Fil Dialog box variable and settings
Dim ofdGetOpenFileName As New OpenFileDialog()
ofdGetOpenFileName.Title = "Open File " & strImportFile
ofdGetOpenFileName.InitialDirectory = xlWBPath
ofdGetOpenFileName.Filter = "Excel Files (*.xls;*.xlsx; *.xlsm; *.csv)| *.xls; *.csv; *.xlsx; *.xlsm"
ofdGetOpenFileName.FilterIndex = 2
ofdGetOpenFileName.RestoreDirectory = True
'If the user presses Cancel on the box, warn that no
'file has been selected and the workbook will close
If ofdGetOpenFileName.ShowDialog() = System.Windows.Forms.DialogResult.Cancel Then
'Message box variables
Dim msbContinue As MsgBoxResult
Dim strAlert As String = ("You have not selected a workbook." & vbNewLine & _
"The project will now close without saving changes")
'Once the user presses OK, close the file and do not save changes
msbContinue = MsgBox(strAlert, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "No Workbook Seletected")
xlWB.Close(SaveChanges:=False)
Exit Sub
Else
'If the user does select the file, then import the file
'copy and paste on workbook.
'***Here is where I need to check that strImportFile =n, if it does not warn the user******
strImportFile = ofdGetOpenFileName.FileName
If strImportFile <> GetImportFiles(n) then
msgbox("You have not selected the correct file please try again")
GoTo Retry
End If
xlWBImport = Globals.ThisWorkbook.Application.Workbooks.Open(strImportFile)
xlWBImport.Worksheets(1).Cells.Copy(xlWB.Worksheets(strDestSheetName).Range("A1"))
xlWBImport.Close()
End If
Hope this helps....
Should have also added to this it is advisable to put the GoTo as the result of a query to the user otherwise they can find themselves in an endless loop if they are unable to locate the correct file!