Trying to access other files in same folder but getting files outside folder - excel

I'm trying to access all the other files in the same folder as the program but it wants to go to files in the entire directory. I get that's basically what I'm telling it to do but I'm still new to vba and don't know the syntax to accomplish what I want. Is there a way that I can get the current folder location from the program and have it go through all the files only in that folder?
Also I'd need a solution that doesn't use the Scripting.Object stuff since I'm running into issues with needing to downloading stuff for that and I feel uncomfortable requiring the people that will use this tool download things too especially since they'll be on secure .mil computers (as opposed to .com computers)
directory = ActiveWorkbook.Path 'Also tried CurDir()
fileName = Dir(directory & "*.xl??")
Do While fileName <> ""
...
fileName = Dir()
Loop

Try
ThisWorkbook.Path
MsgBox ThisWorkbook.Path ' Make sure its the right path...
and
Filename = Dir(directory & "\" & "*.xl??")

Related

Create new folder in the same folder where the current file is stored (in sharepoint)

I want to run the below VBA to create a new folder within the folder where the current file is stored. So far I have done this using the following simple VBA:
Sub Create_Folder()
MkDir Application.ThisWorkbook.Path & "\New Folder"
End Sub
Now, my company moved to sharepoint and when I run this VBA within a sharepoint folder I get runtime error 76.
I assume this is caused because ThisWorkbook.Path can not correctly identify the path anymore. Therefore, I checked how the path looks like:
https://company.sharepoint.com/sites/Finance1/Freigegebene Dokumente/Controlling/
In order to use this path I adjusted it in the VBA:
Sub Create_Folder()
WorkbookPath = ThisWorkbook.Path
WorkbookPath = "\\" & Replace(Split(WorkbookPath, "//")(1), "/", "\")
MkDir WorkbookPath & "\New Folder"
End Sub
However, I am still getting runtime error 76 when I try to create the new folder.
What is strange to me is that when I check the link in the windows explorer it loosk totally different to the link that I get with Application.ThisWorkbook.Path.
C:\Users\firstname.lastname\company\Controlling - Dokumente
Do you have any idea how I can solve this issue and create a new folder in the same folder where the current file is stored?

'Save As' of object '_workbook' failed

I am trying to save a workbook as xlsm, this is the code I use:
ThisWorkbook.SaveAs Filename:="path\workbook_name.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
I have done some testing, and It does in fact save in both a private folder and a public or shared folder
however when I save it in a shared folder I also get this:
Run-time error '1004' Method 'Save As' of object '_workbook' failed
why do I get error message when it is saved in a public/shared folder, or onedrive?
In your string containing path there is variable "path" i suppose. Then you should write it like this:
Dim path as String: path = "C:\Users\xxx\Desktop"
ThisWorkbook.SaveAs Filename:=path & "\workbook_name.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Or you can hardcode full path (but i recommend using variables - first example).
ThisWorkbook.SaveAs Filename:="C:\Users\xxx\Desktop\file.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Then when you can save it manually and you have permissions then i have no idea since i normally save files to shared folders and network drives... Maybe your specific path is wrong. It is best to save using servername and folders...
path = "\\servername\folder1\folder2\workbook_name.xlsm"
Because sometimes when you refefer to mapped drive for example X:\folder2 then you must ensure that all users have it mapped in same way (someone uses X someone uses R etc.). And if path is correct then only other way i can think of it is permission issue, but if you can save it manually then i have sadly no idea... :)

Why is folder creation macro causing Error Code 76?

I am using some very basic coding to create folders and subfolders automatically. I understand the code isn't elegant however others should be able to maintain it.
The goal is to create a named folder on the desktop with name subfolders. The code works fine on my computer but is throwing an error 6 on other computers. Can you assist?
[Business_Name] is a named field in the spreadsheet
MkDir Environ("Userprofile") & "\Desktop\" & [Business_Name]
MkDir Environ("Userprofile") & "\Desktop\" & [Business_Name] & "\1. Sales"
MkDir Environ("Userprofile") & "\Desktop\" & [Business_Name] & "\1. Sales\1. Accepted Quote and Contract"
Thanks
Your code problem may be strictly connected to the path as it is built...
Sometimes, when (on the other computers) is OneDrive installed, the Desktop folder path includes OneDrive after User profile folder. It will be good to check this aspect... The error message will be elocvent for such a case (Run-Time Error 76, instead of 6).
Try, please
Debug.Print Environ("Userprofile") & "\Desktop\" & [Business_Name]: Stop
and see what it returns in Immediate Window...

custom function in excel using vba that works in any matchine

I have created a custom function via vba in excel. If I use it in my computer, it works ok, but if I change the file to another computer (where this computer also has the created function), it does not work. I must change the path of the created function. Is there any way to not change the path everytime I copy the file into another computer?
='C:\Users\Usuario1\Documents\Complementos\BondsTIRMDuration.xlam'!TIrbonds($A2;F2;'C:\Users\Usuario1\Documents\Complementos\AsBusinessDay.xlam'!asbusinessday('C:\Users\Usuario1\Documents\Complementos\AsBusinessDay.xlam'!PrevBusinessDay(HOY())))*100
Solution 1: You could use a common paths in both computers
(for example: C:\work , C:\Work2)
Solution 2: You could put all files in the same path (C:\work), then you only need the to put the file name
='BondsTIRMDuration.xlam'!TIrbonds($A2;F2;'AsBusinessDay.xlam'!asbusinessday('AsBusinessDay.xlam'!PrevBusinessDay(HOY())))*100
Just save your add-in in the correct path on every computer.
It should be something like:
C:\Users\YOURNAME\AppData\Roaming\Microsoft\AddIns\
See Install and Use Excel Add-ins to determine the correct path.
If your add-in is installed correctly you should be able to run your user defined function without a path.
You can call special folder with application.
MsgBox Application.DefaultFilePath
This example will be: C:\Users\Usuario1\Documents
'Here are a few VBA path functions
MsgBox Application.Path
MsgBox Application.DefaultFilePath
MsgBox Application.TemplatesPath
MsgBox Application.StartupPath
MsgBox Application.UserLibraryPath
MsgBox Application.LibraryPath
You can too create wscrit object to call another paths, for example:
MsgBox CreateObject("Wscript.Shell").SpecialFolders("Desktop")
Example folders for Wscript.shell object:
AllUsersDesktop
AllUsersStartMenu
AllUsersPrograms
AllUsersStartup
Desktop
Favorites
Fonts
MyDocuments
NetHood
PrintHood
Programs
Recent
SendTo
StartMenu
Startup
Templates
And execute a macro like this,(allways have to use same directory):
Sub Macro()
AddIns.Add Filename:=Application.DefaultFilePath & "\Complement.xlam"
AddIns("Complement").Installed = True
End Sub

Excel VBA Dir() default path?

I am working through an exercise that uses Dir() to find out whether a file exists in the current directory (i.e. the same directory as the workbook I'm using). The code given - and apparently working in the video example - is like this:
IsThere = (Dir("SomeFile.xlsx") <> "")
When I run this code, IsThere returns False. I can work around it by using:
IsThere = (Dir(ActiveWorkbook.Path & "\SomeFile.xlsx") <> "")
but I want to know why Dir isn't looking by default in the current directory as expected.
I'm struggling to find any relevant advice on this. Most of the examples I've found of how to use Dir() are with the file path specified so they don't really shed any light on my problem. The closest I've found is this (obsolete) MSDN reference which says that:
To run correctly, the Dir function requires the Read and PathDiscovery flags of FileIOPermission to be granted to the executing code.
Trouble is, I don't really understand the linked advice in there on how to set PathDiscovery to 1.
As for StackOverflow, this is probably the closest to my problem - although this uses a specified path, and I am not referencing a network location. I note that the answer to this question seems to presume that Dir() should work in the way expected i.e. with a simple filename and not a fully specified path.
This has nothing to do with whatever the host application thinks it's directory is. You can always find out what directory Dir will default to by calling the CurDir function:
Debug.Print CurDir$
If you need to change it, call ChDir:
Debug.Print CurDir$
Debug.Print Dir$("*.*")
ChDir "C:\"
Debug.Print CurDir$
Debug.Print Dir$("*.*")
Think of it like sitting at a command prompt and typing dir or cd - it does exactly the same thing. Note that the current directory holds it's state between macro executions, so you can't rely on it being in some default location.
If you need a path relative to an open Workbook, use Workbook.Path if you need a path relative to the default path, use Application.Path. If you need to test for the existence of a file, don't use Dir at all - use the Scripting.FileSystemObject instead. You'll do yourself a huge favor if start thinking of the legacy file functions as deprecated.
Check the Excel Options --> Save --> Default File location to see what your default is. It won't by default use where the file is located.

Resources