Foutmelding bij Application.GetSaveAsFilename als bestand in gebruik is

Henk G 220 Reputatiepunten
2025-11-01T17:34:56.13+00:00

Ik gebruik dit om bepaalde gegevens op te slaan.

Als er een bestandsnaam wordt gekozen die al bestaat en die ik open heb staan, dan gaat het fout bij de macro. Dit wordt niet opgelost door If filePath <> False Then

Hoe kan ik dit ondervangen

filePath = Application.GetSaveAsFilename( _

    InitialFileName:="", _

    FileFilter:="Excel-werkmap (*.xlsx), *.xlsx")

' Sla het nieuwe bestand op en sluit het

If filePath <> False Then

    newWB.SaveAs Filename:=filePath, FileFormat:=xlOpenXMLWorkbook, Password:="YourPassword"

    newWB.Close False

    MsgBox "" & vbNewLine & filePath, , "Bestand succesvol opgeslagen"

Else

    newWB.Close False

    MsgBox "Opslaan geannuleerd.", vbExclamation

End If
Microsoft 365 en Office | Excel | Overige | Windows
0 opmerkingen Geen opmerkingen

3 antwoorden

Sorteren op: Oudste
  1. Kai-H 32,935 Reputatiepunten Extern personeel Microsoft Moderator
    2025-11-03T07:33:08.3666667+00:00

    (Disclaimer: de verstrekte informatie is vertaald met behulp van een automatische vertaaltool. Hoewel we streven naar nauwkeurigheid, geven vertalingen mogelijk niet altijd de betekenis, context of intentie van de oorspronkelijke inhoud volledig weer.)

    Hallo, Henk G

    Bedankt voor uw bericht op het Microsoft Q&A-forum.

    U loopt tegen een fundamentele beperking van Excel/Windows aan: u kunt een werkboek dat momenteel geopend is (door u of een andere gebruiker/proces) niet overschrijven. Wanneer Application.GetSaveAsFilename een pad retourneert dat verwijst naar een bestaand, geopend werkboek, mislukt SaveAs met een foutmelding ‘bestand is in gebruik/niet beschikbaar’ (meestal 1004). De If filePath <> False Then beschermt alleen tegen annulering; het beschermt u niet tegen ‘bestand in gebruik’.

    Hier zijn enkele oplossingen die u kunt proberen om dit probleem op te lossen:

    Drop-in, defensieve code

    Option Explicit
    
    '=== Helpers ===
    
    Private Function FileExists(ByVal filePath As String) As Boolean
        On Error Resume Next
        FileExists = (Len(Dir$(filePath)) > 0)
        On Error GoTo 0
    End Function
    
    'Checks if a workbook with this FullName is open in this Excel instance
    Private Function IsWorkbookOpenInExcel(ByVal filePath As String) As Boolean
        Dim wb As Workbook
        For Each wb In Application.Workbooks
            'Compare normalized full names
            If StrComp(LCase$(wb.FullName), LCase$(filePath), vbTextCompare) = 0 Then
                IsWorkbookOpenInExcel = True
                Exit Function
            End If
        Next wb
        IsWorkbookOpenInExcel = False
    End Function
    
    'Checks if the file is locked by any process (Excel or other)
    Private Function IsFileLocked(ByVal filePath As String) As Boolean
        Dim ff As Integer
        ff = FreeFile
        On Error Resume Next
        'Try to open with both read & write locks; if it errors, it's locked
        Open filePath For Binary Access Read Write Lock Read Write As #ff
        If Err.Number <> 0 Then
            IsFileLocked = True
        Else
            IsFileLocked = False
            Close #ff
        End If
        Err.Clear
        On Error GoTo 0
    End Function
    
    'Generates "name (n).ext" in the same folder if the target exists/is locked
    Private Function NextAvailableName(ByVal filePath As String) As String
        Dim folder As String, baseName As String, ext As String
        Dim n As Long, altPath As String
        Dim p As Long
    
        p = InStrRev(filePath, Application.PathSeparator)
        folder = Left$(filePath, p)
        baseName = Mid$(filePath, p + 1)
    
        'Split name and extension
        Dim dotPos As Long
        dotPos = InStrRev(baseName, ".")
        If dotPos > 0 Then
            ext = Mid$(baseName, dotPos) 'includes dot
            baseName = Left$(baseName, dotPos - 1)
        Else
            ext = ""
        End If
    
        n = 2
        Do
            altPath = folder & baseName & " (" & n & ")" & ext
            If Not FileExists(altPath) And Not IsFileLocked(altPath) Then
                NextAvailableName = altPath
                Exit Function
            End If
            n = n + 1
            'Safety to avoid infinite loop
            If n > 1000 Then
                NextAvailableName = filePath
                Exit Function
            End If
        Loop
    End Function
    
    '=== Your save routine ===
    Public Sub SaveNewWorkbookSafely(ByVal newWB As Workbook)
        Dim filePath As Variant
        Dim targetPath As String
        Dim msg As String, res As VbMsgBoxResult
    
        'Prompt for a name
        filePath = Application.GetSaveAsFilename( _
            InitialFileName:="", _
            FileFilter:="Excel-werkmap (*.xlsx), *.xlsx")
    
        'Handle Cancel properly: GetSaveAsFilename returns Boolean False
        If VarType(filePath) = vbBoolean And filePath = False Then
            newWB.Close SaveChanges:=False
            MsgBox "Opslaan geannuleerd.", vbExclamation
            Exit Sub
        End If
    
        targetPath = CStr(filePath)
    
        'If the chosen file exists, check usage and decide action
        If FileExists(targetPath) Then
            Dim openInExcel As Boolean, locked As Boolean
            openInExcel = IsWorkbookOpenInExcel(targetPath)
            locked = IsFileLocked(targetPath) 'covers open in other Excel instance/process
    
            If openInExcel Or locked Then
                'Offer alternatives
                msg = "Het gekozen bestand bestaat al en is momenteel in gebruik." & vbCrLf & vbCrLf & _
                      "Kies een optie:" & vbCrLf & _
                      "• Ja  = Sla op als kopie met een nieuwe naam" & vbCrLf & _
                      "• Nee = Kies een andere bestandsnaam (opnieuw)" & vbCrLf & _
                      "• Annuleren = Stoppen zonder op te slaan"
                res = MsgBox(msg, vbYesNoCancel + vbExclamation, "Bestand in gebruik")
    
                Select Case res
                    Case vbYes
                        Dim altName As String
                        altName = NextAvailableName(targetPath)
                        'Use SaveCopyAs: creates file without switching active workbook
                        'If you need to continue working in newWB, SaveAs is fine too since it's a new WB
                        newWB.SaveAs Filename:=altName, FileFormat:=xlOpenXMLWorkbook, Password:="YourPassword"
                        newWB.Close SaveChanges:=False
                        MsgBox "Bestand succesvol opgeslagen als kopie:" & vbCrLf & altName, vbInformation
    
                    Case vbNo
                        'Re-prompt user for another name
                        filePath = Application.GetSaveAsFilename( _
                            InitialFileName:="", _
                            FileFilter:="Excel-werkmap (*.xlsx), *.xlsx")
                        If VarType(filePath) = vbBoolean And filePath = False Then
                            newWB.Close SaveChanges:=False
                            MsgBox "Opslaan geannuleerd.", vbExclamation
                            Exit Sub
                        End If
                        targetPath = CStr(filePath)
                        'Try to save to the new target
                        newWB.SaveAs Filename:=targetPath, FileFormat:=xlOpenXMLWorkbook, Password:="YourPassword"
                        newWB.Close SaveChanges:=False
                        MsgBox "Bestand succesvol opgeslagen:" & vbCrLf & targetPath, vbInformation
    
                    Case vbCancel
                        newWB.Close SaveChanges:=False
                        MsgBox "Opslaan geannuleerd.", vbExclamation
                        Exit Sub
                End Select
            Else
                'File exists but not in use: Excel will prompt to overwrite
                'You can delete first or let SaveAs prompt. SaveAs will replace the file.
                newWB.SaveAs Filename:=targetPath, FileFormat:=xlOpenXMLWorkbook, Password:="YourPassword"
                newWB.Close SaveChanges:=False
                MsgBox "Bestand succesvol overschreven:" & vbCrLf & targetPath, vbInformation
            End If
    
        Else
            'Brand‑new path: safe to save
            newWB.SaveAs Filename:=targetPath, FileFormat:=xlOpenXMLWorkbook, Password:="YourPassword"
            newWB.Close SaveChanges:=False
            MsgBox "Bestand succesvol opgeslagen:" & vbCrLf & targetPath, vbInformation
        End If
    
    End Sub
    

    Waarom dit werkt

    • GetSaveAsFilename-validatie: deze retourneert False (Boolean) wanneer de gebruiker annuleert; vergelijken met False moet zorgvuldig gebeuren. De code gebruikt VarType om typeverwarring te voorkomen.
    • Open/vergrendeld-controles:
      • IsWorkbookOpenInExcel detecteert of het doelwerkboek is geopend in dezelfde Excel-instantie (zodat u het expliciet kunt aanpakken).
      • IsFileLocked detecteert vergrendelingen op OS-niveau (inclusief andere Excel-instanties of externe processen zoals antivirus/indexering).
    • Veilige paden:
      • Als het bestand in gebruik is, kunt u het niet overschrijven: Excel/Windows blokkeert dit. De code biedt de mogelijkheid om een kopie op te slaan met een automatisch achtervoegsel of om opnieuw om een nieuwe naam te vragen.
      • Als het bestand bestaat maar niet in gebruik is, kan SaveAs het overschrijven en zal Excel de prompt afhandelen.

    Optionele verfijningen

    • Gebruik SaveCopyAs als u het bestand wilt maken zonder de context van het actieve werkboek te wijzigen (ideaal voor sjablonen/macro's). In dit geval voert u newWB.SaveCopyAs altName uit en beslist u of u newWB open wilt houden.
    • Vermijd een wachtwoord op .xlsx als u alleen beveiliging tegen wijzigen wilt. Wachtwoord:= versleutelt voor openen. Als u alleen beveiliging tegen wijzigen wilt, gebruikt u WriteResPassword en ReadOnlyRecommended.
    • Fout 1004 afhandelen: u kunt SaveAs in On Error GoTo ErrTrap verpakken en een gebruiksvriendelijker bericht weergeven wanneer er een racecondition optreedt (het bestand wordt vergrendeld tussen controleren en opslaan).

    Ik hoop dat dit helpt. Neem gerust contact op als u nog andere vragen heeft.


    Als het antwoord nuttig is, klik dan op ‘Antwoord accepteren’ en geef het een positieve beoordeling. Als u nog vragen heeft over dit antwoord, klik dan op ‘Reageren’.

    Opmerking: volg de stappen in onze documentatie om e-mailmeldingen in te schakelen als u de bijbehorende e-mailmelding voor deze thread wilt ontvangen.

    Was dit antwoord nuttig?

    0 opmerkingen Geen opmerkingen

  2. Kai-H 32,935 Reputatiepunten Extern personeel Microsoft Moderator
    2025-11-19T11:17:36.85+00:00

    Hallo Henk G,

    Het is alweer een tijdje geleden en ik schrijf u om te vragen hoe het met deze kwestie staat.

    Heeft u de gegeven antwoorden al kunnen bekijken?

    Ik hoor graag of er nog nieuws is.

    Was dit antwoord nuttig?

    0 opmerkingen Geen opmerkingen

  3. Henk G 220 Reputatiepunten
    2025-11-24T10:14:55.3466667+00:00

    Ik ben erg druk geweest met andere dingen.

    Dit ziet er goed uit.

    Was dit antwoord nuttig?

    0 opmerkingen Geen opmerkingen

Uw antwoord

Antwoorden kunnen worden gemarkeerd als 'Geaccepteerd' door de auteur van de vraag en 'Aanbevolen' door moderators, zodat gebruikers het antwoord van de auteur kunnen weten.