Search code examples
excelvbasavefiledialog

File should be updated but a copy is saved instead


sorry if the Name of the topic isnt perfect, its difficult to describe since Iam already relatively close to the end.

My macro calls another file, copies it, opens the copy, paste some data and then is supposed to save and close it. Unfortunatly, the file is copied, the copy is opned and it looks like the data is pasted. Then the "save as" dialog appears and tells me that a file with this name already exists. I type in another name and save the file.

Now instead of original and updated I have 3 files:

The original, one copy without any updates but the initial name and a second Version with the updates but the other name i have to choose in the "save as" dialog.

How do i get it so that there is only the old and the updated file and the changes are saved in the original file (preferably without any prompt/dialog)

I hope I explained the issue well enough please fell free to ask questions, any help is appreciated.

'select old file to copy, insert data from this workbook into the copy, save the copy.

PfadVorlageDatei = Application.GetOpenFilename("Exceldateien,*.xls*", 1, "Vorlage auswählen")

PfadNeueDatei = Application.GetSaveAsFilename(FileFilter:= _
"Exceldateien (*.xlsx), *.xlsx", Title:="Datei speichern", _
InitialFileName:="")

FileCopy PfadVorlageDatei, PfadNeueDatei

Set NeueDatei = Workbooks.Open(Filename:=PfadNeueDatei, ReadOnly:=True)

With ThisWorkbook.Worksheets("Test")
.Range(.Cells(8, 2), .Cells(100, 100)).Copy
End With

With NeueDatei.Worksheets("Test").Range("B8")
    .PasteSpecial xlPasteFormats
    .PasteSpecial xlPasteValues
End With

NeueDatei.Close SaveChanges:=True ' i guess here is the issue

Solution

  • As @FunThomas said, just change the line

    Set NeueDatei = Workbooks.Open(Filename:=PfadNeueDatei, ReadOnly:=True)
    

    to

    Set NeueDatei = Workbooks.Open(Filename:=PfadNeueDatei, ReadOnly:=False)
    

    worked perfectly. Thanks alot!