Hello, I have a process where users combine data in a single spreadsheet. That data then needs sent to a text file where it will imported into a server database process. I can get the process to create the text file, save changes and then close the text file with a workbook.close statement assigned to a macro button. My issue is if that macro button is clicked twice excel crashes. It appears to hit a snag on the Workbooks("Import_ETL.txt").Close SaveChanges:=True script as it seems to get confused which active workbook since the macro also creates. I've tried multiple variations of close scripts plus tried splitting it out with separate create and close macros but it's still crashing if ran multiple times. At the end of the day I'm attempting to make this user break proof so regardless if ran multiple times it will still create a text file as I only need the latest greatest version. Hope that makes sense. For full disclosure the code below was hobbled together from various forum posts. Values in TEST SALESDB ETL source file are text but any values passed should work. Macro also needs sub-folder in this files location called Import ETL as export will drop there.
Sub mcr4_1_Create_ETL_TXT()
'
' mcrCreate_ETL_TXT Macro
'Deletes existing Import ETL if one exists
Dim aFile As String
aFile = ThisWorkbook.Path & "\Import ETL\Import_ETL.txt"
If Len(Dir$(aFile)) > 0 Then
Kill aFile
End If
'Creates new Import ETL
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Worksheets("TEST SALESDB ETL").Range("A:A").Copy
Sheets.Add.Name = "TEST ETL"
Selection.PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Sheets("TEST ETL").Move
ActiveWorkbook.SaveAs Filename:= _
ThisWorkbook.Path & "\Import ETL\Import_ETL.txt", FileFormat:= _
xlText, CreateBackup:=False
'THIS IS THE BREAK, IF REMOVED IT WORKS WITH SECOND AND SUBSEQUENT BUTTON CLICK
Workbooks("Import_ETL.txt").Close SaveChanges:=True
MsgBox "ETL file has been created in the Import ETL folder"
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Sub mcr4_1_Create_ETL_TXT()
'
' mcrCreate_ETL_TXT Macro
'Deletes existing Import ETL if one exists
Dim aFile As String
aFile = ThisWorkbook.Path & "\Import ETL\Import_ETL.txt"
If Len(Dir$(aFile)) > 0 Then
Kill aFile
End If
'Creates new Import ETL
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Worksheets("TEST SALESDB ETL").Range("A:A").Copy
Sheets.Add.Name = "TEST ETL"
Selection.PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Sheets("TEST ETL").Move
ActiveWorkbook.SaveAs Filename:= _
ThisWorkbook.Path & "\Import ETL\Import_ETL.txt", FileFormat:= _
xlText, CreateBackup:=False
'THIS IS THE BREAK, IF REMOVED IT WORKS WITH SECOND AND SUBSEQUENT BUTTON CLICK
Workbooks("Import_ETL.txt").Close SaveChanges:=True
MsgBox "ETL file has been created in the Import ETL folder"
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub