Een familie van Microsoft-spreadsheetsoftware met hulpmiddelen voor het analyseren, in kaart brengen en communiceren van gegevens.
Ik ben erg druk geweest met andere dingen.
Dit ziet er goed uit.
Deze browser wordt niet meer ondersteund.
Upgrade naar Microsoft Edge om te profiteren van de nieuwste functies, beveiligingsupdates en technische ondersteuning.
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
Een familie van Microsoft-spreadsheetsoftware met hulpmiddelen voor het analyseren, in kaart brengen en communiceren van gegevens.
Ik ben erg druk geweest met andere dingen.
Dit ziet er goed uit.
(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
Optionele verfijningen
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.