Global variable is empty if 2 similar xls files with same macro are opened

Viewed 469

There is macro in Excel which was already written and there was bug reported on this and I have to fix this. Initial investigations are below... There is ABC.xls file which has the macro.

Now, the macro has a sub named changeTheCode which is getting called when I press Ctrl + M.

This sub will open a Open File Dialog where the user can choose a CSV file. The path of the CSV file I am storing in a global variable declare outside of all the function...

Public txtFileNameAndPath As String

This global variable will be used to save the changes into the CSV file when the user closes the excel.

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Call saveUnicodeCSV
    Call deleteXLS
End Sub

I use this ABC.xls file for opening a ABC123.CSV file.

I use this DEF.xls (a copy of ABC.xls) file to open DEF123.CSV file. But when I open the DEF123.CSV using Ctrl + M, the sub changeTheCode of the ABC.xls is getting called and the global variable txtFileNameAndPath of DEF.xls is empty and when I close the Excel, things are not getting saved because of this.

enter image description here

Code where the global variable is getting set.

Public txtFileNameAndPath As String
Sub CodePageChange()
    Dim SheetName As Worksheet
    Dim fd As Office.FileDialog
    Dim sheetName1 As String
    Dim tabSheetName As String

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    With fd
        '....
        '....
        '....
        If .Show = True Then
          txtFileNameAndPath = .SelectedItems(1)
        Else
            MsgBox "Please start over.  You must select a csv file."
            Exit Sub
        End If
    End With

Inputs on how to handle this will help me a lot.

Note: The Excel containing macro will be given to customer. Hence I cannot ask customer to do some registry tweaks to open the Excel in separate instance.

Thanks.

8 Answers
Related