Is there any way to overwrite an excel file when it is opened using vba code?
I think you can't overwrite a file that is open. This is a windows limitation and as far as I know it is not possible to do it.
So I guess you'll have to save it with a different name.
EDIT: unless you are the person that has the file open.
If you open the file via VBA code, just workbookname.save should work
You can overwrite a file that is open in read only mode. To achieve this you need to set the file's attributes to be read only (thus forcing everyone, who's opening it to have it open in read only mode).
This can be done either within the Windows OS (change the file's properties), or through VBA using the SetAttr function https://www.techonthenet.com/excel/formulas/setattr.php
From my own experimentation I reached the following code, which you can use as an example. Assuming you're attempting to save a copy of the currently open workbook to strFileLocation, which is a string variable holding the output file's path, where the file may or may not already exist:
' Verify that the file exists.
If Dir(strFileLocation) <> vbNullString Then
' For some reason the read only flag needs to be removed for VBA to be able to overwrite the file.
SetAttr strFileLocation, vbNormal
End If
' Do the actual (over)writing
ThisWorkbook.SaveCopyAs strFileLocation
' Set the read only flag once more
SetAttr strFileLocation, vbReadOnly
```
Related
As part of a larger macro Excel retrieves .dat files from a folder. After a crash and rebooting, the macro no longer works and seizes up upon trying to refresh.
There was also changes in security upon reboot where I had to enable all macros to be able to step though this current one.
I have double checked to make sure the path is correct and the files are still there.
Updated code and ended up crashing for unrelated memory issue. Fixed the memory problem and now won't run and is giving the same error code and message as before even with updated code. Current code which will run through the first loop but fails on the second.
If I am not mistaken, Dir just returns the filename found within that directory and not the full path to that file. What likely happened is your directory was initially set to F: so the macro used this as the default path when searching for the file. The best way to do this would be to store your directory in a constant string, and then append the two together. Something like this:
Const fPath as String = "F:YourPathHere\"
strFile = fPath & Dir(fPath & "*.dat")
Debug.Print strFile ' Just to make sure it is setting properly.
Currently I have a file name stored in string called filename. The file stored in the string is currently open. Issue is, this file could some times be opened in another instance of Visio.
I want to activate the file that is stored in filename string
My current method does not capture this - The code below only checks if the filename exists among the current/one instance of Visio.
For Each objDoc In objVisio.Documents
If objDoc.Name = filename Then
objDoc.activate
Exit for
End If
Next
How can I activate this file to bring it forward?
windows(filename & " - Microsoft Visio").activate
is not working either
I've tried
Dim objVisio as Visio.Application
Set objVisio = GetObject(filename).Application
which isn't working (maybe due to filename string only having the file name and not the entire file path as well)
Any other brute force methods available out there?
Any help is appreciated!
Try something like this:
objVisio.Application.Caption
Or
AppActivate "Microsoft Visio"
I guess another option is to look into this: https://msdn.microsoft.com/en-us/library/office/ff766749.aspx
I haven't worked extensively with Visio in VBA, so I am interested to see the true answer here.
I'm saving a excel file one share Point into text file. after the saving, I wanna check Dir(sharePointPath).
It will always return "" unless I manually refresh the corresponding folder.
the code would be like the following:
ActiveWorkbook.SaveAs sharePointPath, xlTextWindows
ActiveWorkbook.Close
While Dir(sharePointPath) = ""
MsgBox "not exist"
Wend
The reason I wanna check Dir(sharePointPath) is that I wanna open that file later
open sharePointPath for binary access read as
which always override the text file because open can't find the file.
what should I do to fix this problem?
EDIT:
sharePointPath = {server}\rule_books\Shared Documents\Rule books\NAME - Demo and Testing Client\Text Files\test.txt before saveAS and after close.
dir(sharePointPath) = "" before and after. occasionally dir(sharePointPath) = test.txt.
but if I wait for a while after close to excute dir(sharePointPath), it will return test.txt more often. i guess vba take some time to write and show the new file.
I gave up, and create a local tmp file on user's end machine for work around
Facing one issue....
Basically, I have a bouton on Word to launch a macro treatment. This treatment saves the open file, copies the open file from C:/ to Z:/, writes an XML file in Z:/, launches another treatment that will read both files in Z:/ and then, clears the files in Z:/.
C:/ is my local computer, Z:/ is a shared drive...
I managed to copy the file from C:/ to Z:/ with :
fsoObject.CopyFile ActiveDocument.Path & "\" & ActiveDocument.name, "Z:\" & ActiveDocument.name, True
Treatment goes well, but I'm completely unable to delete the file in Z:\ with this :
fsoObject.DeleteFile "Z:\*", True
I always get "Permission Denied"... Cannot delete it manually as well, except if I close ENTIRELY Word (and not only the file that was copied)...
Is there a way to avoid the file locking by Word ?
Thx !
Use a vba command to close the file after you have performed your operations. Then apply the delete command.
I have a VBA script used to process Word documents. The first thing the program does is to create an index of the documents in a defined set of folders. It then goes through the list processing each of the indexed documents.
The problem I am having is that it will sometimes decide that a particular document cannot be found, even though it previously indexed the document and a quick spot check shows the document to be in the correct place.
Can anyone shed some light on why VBA should display this behaviour?
The script is using the Dir$ function to index the files, and the Documents.Open function to open each word document for processing.
Sample code:
ChangeFileOpenDirectory (folderName)
inputFileName = Dir$(folderName & "*.doc")
Do While inputFileName <> ""
... call various functions here ...
inputFileName = Dir$
Loop
One of the functions called in the block has the following line:
Set currentDoc = Documents.Open(fileName:=docFileName, AddToRecentFiles:=False, Visible:=False)
This is the point at which the code is failing.
One of the most annoying things I have found is that recent files links are returned as the files themselves with Dir. You can use the FileSystemObject to check the file type.
I copy/paste your code and it works correctly.
However, it leaves all the files open (and hidden), and when you run it in another directory, additional files are opened and added to the open projects (take a look in the VBA editor).
My only guess is that after a while you're hitting the maximum allowable number of open files.
Try adding
currentdoc.Close
just before
inputFileName = Dir$
A few reasons, some duplicated from other answers:
If the path+ filename is long enough ... (you already answered in a comment)
If you are writing new files to same directory, Dir$ may get corrupted (happened to me)
If you have filenames with non-std chars (ex. "#")
Files locked by other processes
Files deleted while the macro is running
You may also try this code ...
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(file) Then ....
First enable the Microsoft Scripting reference in the VBE