VBA excel Application.getsaveasfilename error 13 - vba

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

Related

How to catch silent failure of wdDialogFileSaveAs if file is locked?

I created a dialog with three buttons, where the third should save a Word document (Office Pro Plus 2013, BTW) as a PDF file.
Private Sub Button_Dokument_mit_Grafik_als_PDF_speichern_Click()
Dim Grafik As Boolean
Grafik = Options.PrintDrawingObjects
Options.PrintDrawingObjects = True
With Dialogs(wdDialogFileSaveAs)
.Format = wdFormatPDF
' .Format = 17 '17 = PDF
.Show
End With
Options.PrintDrawingObjects = Grafik
End Sub
If the PDF exists I can choose to overwrite it, which does work in most cases.
If the PDF to be overwritten is already open, in Adobe Reader for instance, then the file isn't saved, as it is locked. I don't get any notification that the file is locked.
How can I catch this and pop up the same message that I get when saving manually within Word?
EDIT:
To explain why my question is different to others that have been answered:
I don't need to check if the file is open in Word already. I'm saving the file as a PDF not as a Word file.
I need to check if the file is open and locked in any other application, such as Adobe Reader, Edge or whatever.
This check is done by Word (and/or the OS?) already, and THIS is the event I need to catch. I don't understand why I need to catch it at all, as the result of the check if the file does exist does come up, but the result of the check if the file is locked seems to be ignored.
The VBA code behaves as if the file has been saved, but it is not, if locked by any application other than Word.
I have no clue which code snippet exactly I would need to grab from Detect whether Excel workbook is already open
Here is what you might be looking for:
Sub SaveAsPdf()
Dim Grafik As Boolean
Grafik = Options.PrintDrawingObjects
Options.PrintDrawingObjects = True
Dim fDialog As FileDialog
Set fDialog = Application.FileDialog(msoFileDialogSaveAs)
fDialog.Title = "Save a file"
'works only in Word2016 not in word 2013;
'fDialog.InitialFileName = "*.pdf"
'we can use the filterindex property instead
fDialog.FilterIndex = 7
If fDialog.Show = -1 Then
Dim selectedFilePath As String
selectedFilePath = fDialog.SelectedItems(1)
If IsFileInUse(selectedFilePath) Then
MsgBox "The target pdf file you are trying to save is locked or used by other application." & vbCrLf & _
"Please close the pdf file and try again.", vbExclamation
Else
ActiveDocument.SaveAs2 selectedFilePath, wdFormatPDF
End If
End If
Options.PrintDrawingObjects = Grafik
End Sub
Private Function IsFileInUse(ByVal filePath As String) As Boolean
On Error Resume Next
Open filePath For Binary Access Read Lock Read As #1
Close #1
IsFileInUse = IIf(Err.Number > 0, True, False)
On Error GoTo 0
End Function
If you would like to use wdDialogFileSaveAs dialog, you can try the below code:
The Display method will display the dialog box without executing the actual functionality. You can validate the result of the display to identify the button clicked and use the execute method to execute the actual functionality.
'Save As Pdf using wdDialogFileSaveAs dialog
'However, it doesn't work as expected.
'The Display method should
Sub SaveAsPdf()
Dim dlg As Dialog
Dim dlgResult As Long
Set dlg = Dialogs(wdDialogFileSaveAs)
With dlg
.Format = wdFormatPDF
dlgResult = .Display
If dlgResult = -1 Then 'user clicks save button;
If .Name <> "" Then
If IsFileInUse(.Name) Then
MsgBox "The target pdf file you are trying to save is locked or used by other application." & vbCrLf & _
"Please close the pdf file and try again.", vbExclamation
Else
.Execute
End If
End If
End If
End With
End Sub
Please note that, the above code (wdDialogFileSaveAs dialog) doesn't work as expected in Word 2016 at least in my local enviornment. The Display method executes the actual functionality once the save button is clicked. Also it returns -2 as a dialog result if Save button is clicked.
Thanks to the help of #CSS (see answer and comments above), this is the full currently working code (unless I'd still find any flaws):
Private Sub Button_Dokument_mit_Grafik_als_PDF_speichern_Click()
Dim Grafik As Boolean
Grafik = Options.PrintDrawingObjects
Options.PrintDrawingObjects = True
Dim dlg As Dialog
Dim dlgResult As Long
Set dlg = Dialogs(wdDialogFileSaveAs)
With dlg
.Format = wdFormatPDF
dlgResult = .Display
If dlgResult = -1 Then 'user clicked save button
If .Name <> "" Then
If IsFileInUse(.Name) Then
MsgBox "The target PDF file you are trying to save is locked or used by other application." & vbCrLf & _
"Please close the PDF file and try again.", vbExclamation
Else
.Execute
End If
End If
End If
End With
Options.PrintDrawingObjects = Grafik
End Sub
Private Function IsFileInUse(ByVal filePath As String) As Boolean
On Error Resume Next
Open filePath For Binary Access Read Lock Read As #1
Close #1
IsFileInUse = IIf(Err.Number > 0, True, False)
On Error GoTo 0
End Function
Thanks to #CSS again. :)
You may want to edit your answer, though, so that it does reflect the finally working code. I've given appropriate thanks.

Export all modules from personal.xlsb

I would like to export/ maintain/ manage a text file backup of modules in my personal macro workbook personal.xlsb using VBA.
I cannot find an object library which refers to the modules themselves on msdn. Could someone point me in the right direction on this please?
Using Excel 2013.
You need to add Visual Basic for Application Extensibility X.X reference; or:
Sub load_reference_1()
ThisWorkbook.VBProject.References.AddFromGuid "{0002E157-0000-0000-C000-000000000046}", 5, 3
end sub
Sub Load_reference_2()
ThisWorkbook.VBProject.References.AddFromFile "C:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB"
end sub
Example:
Sub Macromodule_copy1()
ThisWorkbook.VBProject.VBComponents("Macroos").Export "E:\Macroos.bas"
With Workbooks.Add
.VBProject.VBComponents.Import "E:\Macroos.bas"
End With
End Sub
Further examples and source: Snb-Vba -awesome examples!-
I do exactly this, with my personal.xlsb and also with other macro workbooks.
I save the text files into a "VBA" subdirectory and put them into version control to keep track of the changes.
I was inspired by Mass importing modules & references in VBA which references https://www.rondebruin.nl/win/s9/win002.htm
I have a module called WriteBas containing this code:
Attribute VB_Name = "WriteBas"
Option Explicit
Sub WriteAllBas()
' Write all VBA modules as .bas files to the directory of ThisWorkbook.
' Implemented to make version control work smoothly for identifying changes.
' Designed to be called every time this workbook is saved,
' if code has changed, then will show up as a diff
' if code has not changed, then file will be same (no diff) with new date.
' Following https://stackoverflow.com/questions/55956116/mass-importing-modules-references-in-vba
' which references https://www.rondebruin.nl/win/s9/win002.htm
Dim cmp As VBComponent, cmo As CodeModule
Dim fn As Integer, outName As String
Dim sLine As String, nLine As Long
Dim dirExport As String, outExt As String
Dim fileExport As String
On Error GoTo MustTrustVBAProject
Set cmp = ThisWorkbook.VBProject.VBComponents(1)
On Error GoTo 0
dirExport = ThisWorkbook.Path + Application.PathSeparator + "VBA" + Application.PathSeparator
For Each cmp In ThisWorkbook.VBProject.VBComponents
Select Case cmp.Type
Case vbext_ct_ClassModule:
outExt = ".cls"
Case vbext_ct_MSForm
outExt = ".frm"
Case vbext_ct_StdModule
outExt = ".bas"
Case vbext_ct_Document
Set cmo = cmp.CodeModule
If Not cmo Is Nothing Then
If cmo.CountOfLines = cmo.CountOfDeclarationLines Then ' Ordinary worksheet or Workbook, no code
outExt = ""
Else ' It's a Worksheet or Workbook but has code, export it
outExt = ".cls"
End If
End If ' cmo Is Nothing
Case Else
Stop ' Debug it
End Select
If outExt <> "" Then
fileExport = dirExport + cmp.name + outExt
If Dir(fileExport) <> "" Then Kill fileExport ' From Office 365, Export method does not overwrite existing file
cmp.Export fileExport
End If
Next cmp
Exit Sub
MustTrustVBAProject:
MsgBox "Must trust VB Project in Options, Trust Center, Trust Center Settings ...", vbCritical + vbOKOnly, "WriteAllBas"
End Sub
and in my ThisWorkbook object, the BeforeSave event handler calls it each time the workbook is saved.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
WriteAllBas
End Sub
There's a second or two of overhead each time the workbook is saved.
Note: Under Office 2016 and earlier versions I didn't need to delete (Kill) the text file before exporting, but under Office 365 the Export method fails if the file exists.
I just save a date/timestamped copy of PERSONAL.xlsb to a backup drive location using the following code.
Sub PersonalBckup()
Const dstBak As String = "H:\PERSONAL MACROS\" 'change path to suit
Const dstBak2 As String = "D:\PERSONAL Macros\"
On Error Resume Next 'if either of the drives are not present, skip error.
Application.DisplayAlerts = False 'turn off warning popups
With Workbooks("PERSONAL.xlsb") 'name of your PERSONAL.xlsb file
.SaveCopyAs dstBak & "PERSONAL" & " as of " & Format(Now(), "YYYYMMDD_hhmmAMPM") & ".xlsb"
.SaveCopyAs dstBak2 & "PERSONAL" & " as of " & Format(Now(), "YYYYMMDD_hhmmAMPM") & ".xlsb"
.Save
End With
Application.DisplayAlerts = True 'Turn on warning popups
The backed-up file is saved with a date/timestamp: "PERSONAL as of 20180512_0136PM.xlsb"
I know this doesn't exactly answer the question, but perhaps it's still helpful. You can easily save all modules into a pdf by rigth clicking the modules folder and clicking print (and then clicking setup to change to print to pdf) . This won't give you a specific exported file that can be easily imported back in per se, but it keeps a safely saved file that you can always go back and reference should anything go wrong in your code. There's probably a way to automate this (or at least make it a one-time click when you save), but I haven't figured that out yet.

Match SaveAs2 Dialog File Type To Application.FileDialog

Say you want to have a button that the user can click and save a copy of the current file as a PDF(Documentation):
Application.ActiveDocument.SaveAs2 fileName:="fileName.pdf", FileFormat:=wdFormatPDF
This works fine, the user is presented with a save dialog, selects a location and the file is saved, however a few things are not correct:
The type displayed does not match what was specified in the VBA, how can this be correct? It still saves as type "PDF" without issue, even after showing "DOCX" as the file type in the "Save as Type" drop down. Also the "fileName.pdf" is not placed in the "File Name" box, its as if the dialog box is unaware of the options set in the VBA code(This same issue is also referenced in this post).
UPDATE 1
After taking a second look at my code I now realize that the SaveAs2 Method was not displaying the dialog menu, the correct version of the code(simplified) can be described as:
Dim selected As String: selected = Application.FileDialog(msoFileDialogSaveAs).Show()
Dim filePath As String
If selected <> 0 Then
filePath = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
Application.ActiveDocument.SaveAs2 fileName:=Split(filePath, ".")(0), FileFormat:=wdFormatPDF
End If
So then the real question(I guess) is how do you get "Application.FileDialog" to display the proper type you wish to save in under the "Save as type" drop down, and this has already been answered by #PatricK. Thanks everyone for the help, I apologize for the initial confused nature of this question.
I am surprised for SaveAs2 will bring you a prompt to be honest - Only a new document and .Save will bring you that prompt.
If you want to get something similar to that prompt, you use Application.FileDialog with type msoFileDialogSaveAs.
Use this code below (perhaps as an AddIn suits more):
Option Explicit
Sub MySaveAs()
Dim oPrompt As FileDialog, i As Long, sFilename As String
Set oPrompt = Application.FileDialog(msoFileDialogSaveAs)
With oPrompt
' Find the PDF Filter from Default Filters
For i = 1 To .Filters.Count
'Debug.Print i & " | " & .Filters(i).Description & " | " & .Filters(i).Extensions
' Locate the PDF filter
If InStr(1, .Filters(i).Description, "PDF", vbTextCompare) = 1 Then
.FilterIndex = i
Exit For
End If
Next
' Change the title and button text
.Title = "Saving """ & ActiveDocument.Name & """ to PDF format"
.ButtonName = "Save to PDF"
' Default name
.InitialFileName = ActiveDocument.Name
' Show the Prompt and get Filename
If .Show = -1 Then
sFilename = .SelectedItems(1)
Debug.Print "Final filename: " & sFilename
' Save the file as PDF
ActiveDocument.SaveAs2 sFilename, wdFormatPDF
End If
End With
Set oPrompt = Nothing
End Sub
Screenshot sample:

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!

Create New String Variables based on conditional statement and "merging" .dat files?

I'm trying to write a program that merge two or more .dat files in VBA excel. Basically, it first asks the user to select any number of files (more than 2). Then it "merges" the files based on the order that the user had selected them. By merge, I mean append or copy and paste one selected file into the previous selected file, and save as a brand new file. I'm stuck on on creating the new variables as Strings part, since I'm used to having the open prompt window pop up for just one file that need to be opened. Now it is conditional based on user's selection at the message box of whether he wants another file merged with the previous. It keeps asking this until the user selects no or cancel. So each time the user selects yes there needs to be a new variable created to store the file name to be opened later. How do I go about this process? And also How do I open up all of these files at the same time once the user hits "no" to stop merging the files, and is there any clever way to append or Copy and Paste .dat files, I've tried Hex Editor: HxD, How do I manipulate the Hex Edit program with VBA?
Sub Merge()
Dim Response, Message As String
Dim File1 As String 'Needs new variable created each time user selects "ok" on msgbox
ChDir "C:\"
File1 = Application.GetOpenFilename(Title:="Select File to be Merged")
If File1 = "False" Then Exit Sub
Message = "Select Another File To be Merged With?"
Response = MsgBox(Message, vbQuestion + vbOKCancel, "Merge Files")
If Response = vbOK Then
'Loop-mechanism to create a new variable each time. HOW?
Else
'Open .dat files and start the copy and pasting process HOW with Hex Editor?:I'm using a program called "HxD"
End If
End Sub
Thanks!
You can loop like this storing the names in an array of strings, then subsequently access each one individually for processing:
Sub Merge()
Dim File1 As String 'Needs new variable created each time user selects "ok" on msgbox
Dim AllFiles() As String
Dim count As Long
ChDir "C:\"
ReDim AllFiles(0)
Do
Application.EnableCancelKey = xlDisabled
File1 = Application.GetOpenFilename("DAT Files (*.dat),*.dat", 1, "Select File to be Merged")
Application.EnableCancelKey = xlErrorHandler
If (File1 = "False") Then Exit Do
ReDim Preserve AllFiles(count)
AllFiles(count) = File1
count = (count + 1)
If (MsgBox("Select Another File To be Merged With?", vbQuestion + vbOKCancel, "Merge Files") = vbCancel) Then Exit Do
Loop
If (count = 0) Then
MsgBox "No selection"
Exit Sub
End If
For count = 0 To UBound(AllFiles)
MsgBox "User selected file name: " & AllFiles(count)
'//boogy
Next
End Sub
GetOpenFilename also support an MultiSelect argument however it only works in a single directory and the order of selected files is not guaranteed.