Initial Excel Workbook Path - vba

I have an excel spread sheet which, after 30 seconds, saves itself as a new file on the desktop so the original file is not edited. I want the path of the original file, so i add -
"ActiveWorkbook.Path"
But, this doesnt work correctly now, as when the file is saved as a new name after 30 seconds, it takes the
"ActiveWorkbook.Path"
of the newley named file, which in this case is the desktop.
Is there anyway in getting the Path to the initial file, before it got saved ?

I would try to store it in a variable at the start of the code:
Dim originalPath As String
originalPath = ActiveWorkbook.Path
Then, you can refer back to it as needed.

Related

Access Data From Already Open But Not Saved Excel File In Separate Instance

I have two excel files in separate instances of excel. I want to take data from one instance of excel to another. This seemed simple as I know that path of the file that I want to pull data from. However, the file I want to pull data from is used by a separate program where it opens up the file I want to pull from (a template), populates it, but does not save it. So each time this external program is running it is using the file I want to pull data from but since it never saves it I am having a hard time pulling data from the template file. I have used the getObject() function which successfully pulls data from the file as I know the file path but the fields are of course empty as when the external program used the file, it only filled in the data but never saves it. How can I do what I am asking?
Building on Scotts suggestion
Since you know the full path and name of the other workbook, use GetObject to reference it
Use .SaveCopyAs to save it
Open the saved copy in the local instance
This code goes in the file running in your instance of Excel
Sub Demo()
Dim wbRemote As Workbook
Dim wbLocal as Workbook
' Get reference to the workbook running in the other instance of Excel
Set wbRemote = GetObject("C:\data\Temp\TemplateBook.xlsx")
' Save a copy
wbRemote.SaveCopyAs "C:\data\Temp\Temp.xlsx"
' remove reference
Set wbRemote = Nothing
' open copy in this instance
Set wbLocal = Application.Workbooks.Open("C:\data\Temp\Temp.xlsx")
' work with object wbLocal
' ...
End Sub

Adding a macro file to an XLSX/XLSM file using Packaging

I'm using System.IO.Packaging to build simple Excel files. One of our customers would like to have an autorun macro that updates data and recalcs the sheet.
Pulling apart existing sheets I can see that all you need to do is add the vbaProject.bin file and change a few types in the _rels. So I made the macro in one file, extracted the vbaProject.bin, copied it into another file, and presto, there's the macro.
I know how to add package parts when they are in XML format, like the sheets or the workbook itself, but I've never added a binary file and I can't figure it out. Has anyone done this before?
Ok I got it. Following TnTinMn's suggestion:
Open a new workbook and type in your macro. Change the extension to
zip, open it, open the xl folder and copy out the vbaProject.bin
to somewhere easy to find.
In your .Net code, make a new Part and add it to the Package as
'xl/vbaProject.bin'. Copy over byte-for-byte from the
vbaProject.bin you extracted above. It will be compressed as you
add the bytes.
Then you have to add a relationship to the workbook that points to
your new file. You can find those relationships in
xl/_rels/workbook.xml.rels.
You also have to add a content type entry at the root of the
document, which goes into the [Content Types].xls. This happens automatically when you use the ContentType parameter of CreatePart
And finally, change the extension to .xlsm or .xltm
I'm extracting the following from many places in my code, so this is pseudo...
'the package...
Dim xlPackage As Package = Package.Open(WBStream, FileMode.Create)
'start with the workbook, we need the object before we physically insert it
Dim xlPartUri As URI = PackUriHelper.CreatePartUri(New Uri(GetAbsoluteTargetUri("/", "xl/workbook.xml"), UriKind.Relative)) 'the URI is relative to the outermost part of the package, /
Dim xlPart As PackagePart = xlPackage.CreatePart(xlPartUri, "application/vnd.ms-excel.sheet.macroEnabled.main+xml", CompressionOption.Normal)
'add an entry in the root _rels folder pointing to the workbook
xlPackage.CreateRelationship(xlPartUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "xlWorkbook") 'it turns out the ID can be anything unique
'now that we have the WB part, we can make our macro relative to it
Dim xlMacroUri As URI = PackUriHelper.CreatePartUri(New Uri(GetAbsoluteTargetUri("/xl/workbook.xml", "vbaProject.bin"), UriKind.Relative))
Dim xlMacroPart as PackagePart = xlPackage.CreatePart(xlPartUri, "application/vnd.ms-office.vbaProject", CompressionOption.Normal)
'time we link the vba to the workbook
xlParentPart.CreateRelationship(xlPartUri, TargetMode.Internal, "http://schemas.microsoft.com/office/2006/relationships/vbaProject", "rIdMacro") 'the ID on the macro can be anything as well
'copy over the data from the macro file
Using MacroStream As New FileStream("C:\yourdirectory\vbaProject.bin", FileMode.Open, FileAccess.Read)
MacroStream.CopyTo(xlMacroPart.GetStream())
End Using
'
'now write data into the main workbook any way you like, likely using new Parts to add Sheets

VBA not working in 2016 as it did in 2013: suggested file name (InitialFileName) not showing up

I have a code to export an Excel tab and save it as a new file with a preset file name. The user has the option to review the file name before saving. This is what I have been using:
InitialName = SaveString & UniqueString
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName)
If fileSaveName <> False Then
Export.SaveAs (fileSavename)
End If
SaveString is the save folder, and UniqueString is the specific file name, which changes each month. The user clicks Export, the tab is prepared, and the Save As folder pops up in the correct folder with the suggested file name. As long as the user hits "Save," then the exported tab is saved in the SaveString folder with the UniqueString name (with .xlsx already included in UniqueString).
Since upgrading to Office 2016, the UniqueString suggested file name no longer shows up. The Save As pop-up still opens in the SaveString folder, but there is no suggested file name. If the user isn't careful to manually add .xlsx to the end of the file name, then the file type is an unusable "File."
I've opened Excel 2013 in a virtual setting and run the code side-by-side, and it works perfectly in the older version. Does anyone have insight as to why this change happened, and how to correct it?
It appears that you now need to include a file filter that matches the initial name you provide, so the following will possibly work:
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
FileFilter:="Excel Files (*.xlsx),*.xlsx")

Macro broke after re-boot - Excel unable to locate external text files

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.

External file properties not updated - VBA

I have a macro that reads out external file properties like date created. The file from where I read is stored on a server. Unfortunately the date returned is not the correct one when running the macro the first time. Only when I open the file or when I run the macro several times, the correct updated date created is returned.
Does anyone have an idea how to solve that issue except from opening the file or looping through until the date is correct?
Here is the code:
strFilename = "<FILENAME>"
Workbooks.Open strFilename
Workbooks("strFilename").Close
Set oFS = CreateObject("Scripting.FileSystemObject")
lastcreatedLTVfile = CDate(Format(oFS.GetFile(strFilename).DateCreated, "dd.mm.yyyy"))
Do you want DateCreated or do you actually want DateLastModified? In your question you say "correct updated date" so I guess you should be using DateLastModified.