I am trying to write a code that takes a .xls file and modifies the values in it after which saves it in a set location with a set filename that may always change based on the "NewSaveName" string but it gives me an error "Close' of object '_Workbook' failed" and I can't figure out why. Sometimes it works and sometimes it doesn't. The code I have written:
Workbooks("FormatSketch_DesignTable").Close SaveChanges:=True, Filename:="E:\FORMAT\Temp\" & SaveName & ".xls"
Could someone, please, help me solve this one?
Related
I have vba that works great to open a file based of a partial criteria met. but when I have multiple files open the file opening by the below VBA remains open when done and I am having trouble how to call that workbook back to close it seeing it opens off partial parameters being met. in quick summary the opencopy (opens a file), then in another vba I copy that data, and pastes it into another workbook (done in another VBA) when done i want to bring that workbook back up and just close it. if i do activeworkbook.close it closes the workbook i'm working on which i don't want. Help im stuck!
Sub OpenCopy()
Dim sPath As String
Dim sPartial As String
Dim sFName As String
sPath = "C:\" ' <<<<< change accordingly
sPartial = "AAA_" & Year(Now) & IIf(Len(Month(Now)) = 1, "0" & Month(Now), Month(Now)) &
IIf(Len(Day(Now)) = 1, "0" & Day(Now), Day(Now)) & "*.txt"
sFName = Dir(sPath & sPartial)
If Len(sFName) > 0 Then
Workbooks.OpenText sPath & sFName
Else
MsgBox "File not found.", vbExclamationEnd If
End Sub
Your problem is in "the other VBA". Try to force your project to comply with the rules by which VBA works.
That would mean to acknowledge that there is only one VBA. That VBA has procedures. You can call these procedures manually (which you probably do, and which leads you to talk of "the other VBA") or you can create a Main procedure that calls them for you, one after the other. The advantage of this would be that you can declare objects and variables in the Main which could be made available to all procedures, passed as arguments.
So, you would open a file, finding it by an abbreviated description of its name. You would assign this file to a variable, say File1, and now you could refer to it from anywhere in your project to read or copy from and to close it. You never need to know its name because you refer to it by the variable name to which it was assigned. VBA will assure that the name is unique.
As an alternative, you could of course take the file's complete name from the file after it was opened and then close the file by its complete name. In fact, the Dir function in your code does provide the complete name. So you could take it from there even before the file is opened. As I said, the problem is that the name would be in "the other VBA", an idea that isn't supported by VBA.
But, presuming that you want to continue with your piecemeal approach at least for the moment, wouldn't you be able to identify the file by the same partial details that led you to find it in the first place? I presume that the names of files you have open at the same time would differ in the "AAA" part. So, If Instr(ActiveWorkbook.Name, "AAA") = 1 Then would identify a file. You could loop through all open workbooks with For Each Wb In Application.Workbooks and check each name. You may have to add an input box to enter "AAA" another time because your different "VBAs" can't be made to talk to each other.
By the way, your beautiful partial string could be simplified using VBA's Format function. Try this.
sPartial = "AAA_" & format(date, "yyyymmdd")
This is not the first time I ask this question, but I have slightly altered the details to hopefully make it clearer. Here is one version of the code I have tried:
Private Sub OpenWbsInPath(zPath As String)
Dim zFile As String
zPath = IIf(Right$(zPath, 1) = "\", zPath, zPath & "\") ' Ensure zPath ends with "\".
zFile = Dir(zPath & "*.xls*") ' "xxxx\*.xls*". OK.
Do While zFile <> ""
Workbooks.Open Filename:=zPath & zFile ' Fails with error 1004 on 2nd iteration.
DoEvents ' Makes no difference.
zFile = Dir() ' Next filename. Path also OK.
Loop
End Sub
I have also tried a similar procedure using CreateObject("Scripting.FileSystemObject"). In all approaches I have tried so far, including one in which I created an array of file names first and then tried to open each file individually, the first file opens OK, then the next file fails to open with error 1004.
The really strange thing is that in an older version of the program, all the files open OK. I have even tried copying the identical code, but it still doesn't work in the new location. I am running out of ideas - do I need to create a temporary folder for each workbook before I open it? Seems crazy.
I've run your code, and can confirm it works fine, if the files can be opened, and fails with error 1004 if they can't.
Possible reasons that a file can't be opened include
it's corrupt, or.
it's already open.
A file can't be open if:
you or your code opened it already (is the file containing the code also in the folder?),
someone else has it open (is the folder shared?),
another instance of Excel has it open (check task manager for extra instances).
Can you manually open the file the code fails on? Add a Debug.Print zFile before the Open to see what file fails
I recorded a macro in excel to make some formatting changes to spreadsheets. I’m planning to run it every time I open a new export to begin working with it. I’d also like my macro to rename the file, based on the original name but adding more words.
For example:
Old file name: Sales.xls
New file name: 2019.07.10 Export Sales Backup.xlsx
The original file name will be different every time (“Sales”, “Mailing”, etc.), so I need the code to be based on the old name and not just dub everything Sales. The folder will always be the same—the file will always come from Desktop and get saved to Desktop.
I’ve read some questions about renaming but I can’t figure out how to parse the original file name to separate out the file path and only keep the bit I need. I’ve also seen questions that are about a batch rename, but I want to do this as part of an existing excel macro that I’ll already be running anyway. I’ve already read through these forums and figured out how to add the date and change the file format.
My current code says:
Sub Test()
FName = "C:\Users\Grace\Desktop\" & Format(Date, "yyyy.mm.dd") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=FName, _
FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
End Sub
I don't know where to start with trying to keep the original file name. Any help would be appreciated.
I am building a utility to grab data from specific files and transfer that data to another file. The source files all have the same naming convention which includes an identical string that can be used to differentiate them from other files in a directory. The intent is to use that string with wildcards to open the file and pull the required data.
I thought I had Workbook.Open working with wildcards yesterday, after consulting this StackOverflow post and this entry in the Office Dev Center, but today I try running my test code and VBA claims not to find the file (though the text suggests otherwise).
There is not much to go wrong in my test code:
Dim strFilePath As String
strFilePath = "C:\...\KMMacros\DeepLinkTransferFromSabaForm\"
Dim strFileName As String
strFileName = "*SabaEntryForm.xlsx"
Workbooks.Open FileName:=Dir$(strFilePath & strFileName), ReadOnly:=True
The error reads
'TEST_KM6.7-3_BRSTA_SabaEntryForm.xlsx' could not be found. Check the
spelling of the file name, and verify that the file location is
correct.
and debug highlights
Workbooks.Open FileName:=Dir$(strFilePath & strFileName), ReadOnly:=True
Because the error specifically mentions the file I expected to open, and because my code does not give the specific file name, it seems like VBA has found the file, even though the error states otherwise.
How can VBA be finding the name of the file and then claim that it cannot find it? What am I doing wrong?
Dir() only returns the filename, not the whole path, so if your current directory is different from the folder you pass to Dir then you will have this problem.
Dim strFilePath As String
strFilePath = "C:\...\KMMacros\DeepLinkTransferFromSabaForm\"
Dim strFileName As String
strFileName = "*SabaEntryForm.xlsx"
Workbooks.Open FileName:=strFilePath & Dir$(strFilePath & strFileName), _
ReadOnly:=True
My issue is this.
I read in a series of filenames using a wildcard, so that the end of the filename is unknown, and the extension is either .xls or .xlsx. So, the wildcard is something like :
beginningOfFilename_*.xls*
I then want to take each file, after I have manipulated it, and save it with the same name, but as a .csv (comma seperated value file). In vba for excel, can I just specify the format and it will take care of the extension, or do I have to somehow pull off the( unknown) extension, and append .csv
If the second case is neccessary how would you approach this problem, I don't know where to start, since part of the filename is unknown, and I am not sure how to manipulate strings in vba.
I'm a VBA beginner.
Any help will be appreciated, thanks.
The line you want is :
Mid(sFile, 1, InStrRev(sFile, ".")) & "csv"
Where sFile is the file name with any extension.
Split(sFile, ".")(0) & ".csv"
where sFile is the filename
To get a path and name of your file without extension use.
Dim StrFileName as string
StrFileName= split(ThisWorkbook.fullName,".xls")(0)
Now save your Csv using StrFileName content.
[]´s