Why can't I get the workbook's directory? - excel

I'm trying to find the current directory of the workbook, since the location will change periodicly. But, the returned path is in the temporary folder and not where the file is located. I've tried it both of these ways.
folderPath = Replace(ThisWorkbook.FullName, templateBook, "")
OR
folderPath = ThisWorkbook.path
They both work the first time I run the macro, but when I close the workbook and move it I get the same problem.
NOTE: I'm using excel 2007.

I used the following code:
folderPath = CurDir("M") & "\" & Month & " " & Year
MkDir (folderPath)
I think it was not working the other ways because there is protection on the shared drive (M).

Related

Excel VBA Dir() Error when file type changes

I'm trying to better understand the Dir function. I have a Dir loop to take action on all .csv files in the directory, but when the loop comes across another file type, like .txt, it will error instead of moving on to the next .csv. item.
This is the relevant portion of my code.
strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"
strWorkbook = Dir(strSourceExcelLocation & "*.csv*")
Do While Len(strWorkbook) > 0
'Open the workbook
Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport)
'Get next workbook
strWorkbook = Dir
'Close Excel workbook without making changes
wbktoExport.Close False
Loop
So if there are only .csv files in the directory, then this works fine. When it comes across another file type, an error occurs.
The error is on line
strWorkbook = Dir
Run-time error 5: Invalid procedure call or argument
Am I missing something with the way I use the wildcards in the .csv at the beginning?
Thank you
Solved my issue.
The problem seems to have been because when I called another procedure, I had another Dir in that sub to create a new folder if one didn't already exist. So basically I had a Dir in a Dir, which apparently is bad.
I moved the folder creation part to the very beginning of my procedure, so it is executed before I begin the Dir for looping through all the CSV files.
Option Explicit
Sub Loop_Dir_for_Excel_Workbooks()
Dim strWorkbook As String, wbktoExport As Workbook, strSourceExcelLocation As String, fldr As String, strTargetPDFLocation As String, d As String
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\"
'***** Creating a folder to save the PDFs in. Naming the folder with today's date *****
d = Format(Date, "mm-dd-yyyy")
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\" & d & "\"
If Len(Dir(strTargetPDFLocation, vbDirectory)) = 0 Then MkDir strTargetPDFLocation
fldr = InputBox("Input the EXACT Folder Name that you want to create PDFs for")
strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"
'Search all Excel files in the directory with .xls, .xlsx, xlsm extensions
strWorkbook = Dir(strSourceExcelLocation & "*.csv")
Do While Len(strWorkbook) > 0
'Open the workbook
Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport, strTargetPDFLocation)
'Close Excel workbook without making changes
wbktoExport.Close False
'Get next workbook
strWorkbook = Dir
Loop
End Sub
Try to hardcode the path and give it a try again. Probably the error is something really small in the hardcoding. E.g., in the code below, replace C:\Users\username\Desktop\AAA\ with the path of the file. Then run it. Do not forget the last \. It should work:
Sub TestMe()
Dim workbookPath As String
workbookPath = Dir("C:\Users\username\Desktop\AAA\" & "*.csv")
Do While Len(workbookPath) > 0
Debug.Print workbookPath
workbookPath = Dir
Loop
End Sub

Get value from closed Excel workbook via HTTP link

I have a bunch of Excel workbooks that are stored on a shared online directory (kind of like Dropbox) in different folders. I am creating a master workbook to pull values from these Excel workbooks into a summary. While testing I've managed to create one that works if the workbooks are stored in my disk drives and I refer to their directories, but not via the HTTP links they are stored on.
I'm currently using the ExecuteExcel4Macro macro to retrieve values from closed workbooks on my computer and passing the directory as the argument. Some code for example which works if it's a directory on the hard drive:
Private Function GetValue(path, file, sheet, ref)
' Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
' Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
Sub TestGetValue()
p = "c:\XLFiles\Budget"
f = "Budget.xls"
s = "Sheet1"
a = "A1"
MsgBox GetValue(p, f, s, a)
End Sub
Is there any way to get this to work with direct HTTP links to Excel workbooks instead of directories? Downloading them all into my computer isn't really an option, unless I could somehow change it to download each workbook automatically, get the value and then delete it, or something like that?

ThisWorkbook Not Working in Excel 2018?

I have recently encountered a problem where a macro that used to work in previous versions of Excel has stopped functioning as intended. The macro, when functional, opens each file in a specific folder and copies some of its data and pastes it into another file which it opened.
Since this macro is run from within a file in the folder, it was previously programmed to not attempt to re-open the file, using the code below:
' Create a new workbook and set a variable to the first sheet.
' Set SummarySheet =
Workbooks.Open ("[Redacted]")
' agg_wkb_name = ActiveWorkbook
lrowcount = ActiveWorkbook.Worksheets("scheduled hours").UsedRange.Rows.Count
ActiveWorkbook.Worksheets("scheduled hours").Range("A2:bz" & lrowcount).Delete
' Modify this folder path to point to the files you want to use.
FolderPath = "[Redacted]"
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 2
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(FolderPath & "*.xl*")
' Loop until Dir returns an empty string.
Do While FileName <> ""
' Open a workbook in the folder
If FolderPath & FileName = ThisWorkbook.FullName Then
Set WorkBk = ThisWorkbook
Else
Set WorkBk = Workbooks.Open(FolderPath & FileName, , True)
End If
However, after our computers and programs were updated to Win10 and Excel 2016, this macro began attempting to also open the workbook running the file ('ThisWorkbook'). When you attempt to say "no, I don't want to re-open the file", it stops the Macro, and when you say "yes", Excel crashes.
I attempted to segregate the code, to pull the data from 'ThisWorkbook' differently than pulling it from the various other workbooks in the folder. The new section of code reads:
Do While FileName <> ""
If Not (FolderPath & FileName = ThisWorkbook.Path & ThisWorkbook.Name) Then
Set WorkBk = Workbooks.Open(FolderPath & FileName, , True)
End If
Unfortunately, the very same error still occurs. I'm at a loss - my best guess is that something changed in the way 'ThisWorkbook' functions between the last version of Excel and the current one.
So, it turns out that a system administrator had re-mapped the folder to a drive on my computer. I fixed it by not having the code look at the file location for comparison, only the name, since that's all that changes once you get into the folder.
If anyone ever runs into this, or has a similar situation where they are opening all files in a folder except the one that is currently open - don't bother with the filepath. Just use the name.

Excel VBA: How to point to relative directory (name of the file changes a bit everyday)?

The current code is:
Set Workbook = Workbooks.Open("Z:\test\bankinfo20180815.xls")
The file in the folder would change. For example: it was bankinfo20180814.xls yesterday, bankinfo20180815.xls today and bankinfo20180816.xls tomorrow. So I am wondering how I can specify in VBA code to point to the file that starts with "bankinfo"?
Try this:
MyFile = "Z:\test\bankinfo"
Set Workbook = Workbooks.Open(MyFile & "*.xls")
Hope this helps!
You can use a wildcard like *, but if there are multiple files, it can open a wrong file so a better method is to make sure you are opening the exact file.
Sub OpenMyWB()
sdir = "Z:\test\"
sFile = Dir(sdir & "bankinfo" & Format(Date, "yyyymmdd") & ".xls")
Set wb = Application.Workbooks.Open(sdir & sFile)
End Sub

Create a general path for shared file

I'm trying to use file dialogue to pick a file and save it to a folder but I can't figure out how to code a folder path and keep getting "Path not found error"
I'm not at all a coder, so please explain in plain English:)
Below is the piece of code I tried to use but didn't work.
ArchiveFolderPath = Environ("UserDomain") & "\" & Environ("username") & "\Desktop"
Full sub code from comment below:
Sub CreateCopyFile(FilePathToCopy As String)
Dim fso As Scripting.FileSystemObject
Dim FileToCopy As Scripting.File
Dim ArchiveFolderPath As String
'Create a new folder path
Set fso = New Scripting.FileSystemObject
ArchiveFolderPath = Environ("UserProfile") & "\Desktop\Archive"
'Create a new folder
If Not fso.FolderExists(ArchiveFolderPath) Then
fso.CreateFolder ArchiveFolderPath
End If
Set FileToCopy = fso.GetFile(FilePathToCopy)
FileToCopy.Copy ArchiveFolderPath & "\" & FileToCopy.name
Set fso = Nothing
End Sub
Try adding another backslash at the end of the word, "Desktop", and add two backslashes at the very beginning of the path. Like so:
ArchiveFolderPath = "\\" & Environ("UserDomain") & "\" & Environ("username") & "\Desktop\"
You need to put another \ at the end of Desktop and then make sure that you put the file name after it when you are saving.
So will look like ArchiveFolderPath = Environ("UserDomain") & "\" & Environ("username") & "\Desktop\"
Some of what you are looking for is going to depend on the operating system. In Windows 7, there is a Public Desktop that populates all user desktops and has fairly open file permissions. It is located at:
c:\Users\Public\Desktop
If that is where you want to put things then your code would be one of these,
ArchiveFolderPath = "c:\Users\Public\Desktop"
ArchiveFolderPath = Environ("PUBLIC") & "\Desktop"
If you wanted to point to the current users desktop then that would be one of these,
ArchiveFolderPath = "c:\Users\" & Environ("USERNAME") & "\Desktop"
ArchiveFolderPath = Environ("USERPROFILE") & "\Desktop"
The environment variable that you are using (`Environ("USERDOMAIN")) typically points to the computer name in a workgroup environment although it would be different in a structured Active Directory network.
Remember to use environment variables whenever possible to avoid variations in hard-coded paths between system operating versions. An XP machine's user profiles are not in the same place as a Windows 7 or Windows 8 machine.
A quick and easy way to get a list of the environment variables in the current session is to open a command prompt window and type SET then hit Enter.

Resources