I wrote a macro as an add-in, and I need to get the path of the current worksheet on which it is being executed. How do I do this? How do I get the file path (just the directory)?
Use Application.ActiveWorkbook.Path for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName for the path with the workbook name.
Always nice to have:
Dim myPath As String
Dim folderPath As String
folderPath = Application.ActiveWorkbook.Path
myPath = Application.ActiveWorkbook.FullName
If you want to get the path of the workbook from where the macro is being executed - use
Application.ThisWorkbook.Path
Application.ActiveWorkbook.Path can sometimes produce unexpected results (e.g. if your macro switches between multiple workbooks).
The quickest way
path = ThisWorkbook.Path & "\"
I had the same problem and I built a solution that I'm going to share. Below is the function in VBA for Excel GetLocalPath(), which gets the local path of the ActiveWorkbook:
`Function GetLocalPath() As String
Dim sRowPath As String
Dim sLocalPath As String
Dim iFindhttp As Integer
sRowPath = Application.ActiveWorkbook.Path
If LCase(Left(sRowPath, 4)) = "http" Then
Dim fso As New FileSystemObject
sLocalPath = fso.GetAbsolutePathName(sRowPath)
iFindhttp = InStr(LCase(sLocalPath), "\http")
sLocalPath = Left(sLocalPath, iFindhttp - 1)
Set fso = Nothing
Else
sLocalPath = sRowPath
End If
GetLocalPath = sLocalPath
End Function`
Related
I have found this VBA code and it works to remove the known password on one Excel workbook just fine.
Sub testPasswordRemoval()
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:="C:\Temp\Book2.xlsm", Password:="pw")
wb.Password = ""
wb.SaveAs "C:\Temp\NewBook.xlsm"
End Sub
But, I have tried various tutorials and videos (many folks offering this) but none of them work to loop through a folder of .xlsx files (all with the same known password) and remove that same password.
I am not a VBA person, but have spent about 16 hours over the past three days trying to crack the code on this one. I have found several examples of looping over files in a directory, but none that enabled me to put the above code into them and loop and remove passwords.
Try this code, read the comments, and adjust it to fit your needs
Code:
Public Sub RemovePassLoopThroughFiles()
Dim targetWorkbook As Workbook
Dim filePath As String
Dim folderPath As String
Dim folderWildcard As String
Dim currentFileName As String
Dim currentFileExtension As String
Dim newFileName As String
Dim newfileNameSuffix As String
Dim currentPassword As String
Dim newPassword As String
' Adjust next lines to fit your needs
folderPath = "C:\Temp\" ' With slash at the end
folderWildcard = "*.xls*" ' You can change the suffix to open specific files
newfileNameSuffix = "_NoPassword"
currentPassword = "pw"
newPassword = ""
' Get the file path concat folder and wildcards
filePath = Dir(folderPath & folderWildcard)
Do While Len(filePath) > 0
' Open the workbook and set reference
Set targetWorkbook = Workbooks.Open(Filename:=filePath, Password:=currentPassword)
' Get current file extension
currentFileExtension = Right(filePath, Len(filePath) - InStrRev(filePath, "."))
' Get filename no extension
currentFileName = Left(filePath, InStrRev(filePath, ".") - 1)
' Build new fileName
newFileName = currentFileName & newfileNameSuffix & "." & currentFileExtension
' Set new password
targetWorkbook.Password = newPassword
' Save new file
targetWorkbook.SaveAs folderPath & newFileName
'Debug.Print filePath
filePath = Dir
targetWorkbook.Close True
Set targetWorkbook = Nothing
Loop
End Sub
Let me know if it works.
I'm trying to write a code that will refresh all workbooks starting with 'FY' in a folder. With the current code, the first two workbooks refresh, but when it comes to the third workbook, I get this error:
Sorry, we couldn't find FY20 11-15.xlsm\FY20 1-5.xlsm. Is it possible it was moved, renamed or deleted?"
The path to the workbook is "C:\Documents\Database\Sales".
Here's the code:
Sub refreshdata()
Dim file As String
Dim book As String
file = Application.ThisWorkbook.Path
book = Dir(file & "\FY*.xlsm")
Do While file <> ""
Dim wb As Workbook
Set wb = Workbooks.Open(file & "\" & book)
Call Refresh
wb.Close savechanges:=True
file = Dir
Loop
End Sub
You named your variables not clearly and file contains actually a path file = Application.ThisWorkbook.Path therefore you mixed everything up. Get your variable names more meaningful! Make sure your variables are well named after what content they contain or you confuse yourself.
Sub refreshdata()
Dim Path As String
Path = Application.ThisWorkbook.Path
Dim FileName As String
FileName = Dir(Path & "\FY*.xlsm")
Do While FileName <> vbNullString
Dim wb As Workbook
Set wb = Workbooks.Open(Path & "\" & FileName)
Call Refresh
wb.Close SaveChanges:=True
FileName = Dir
Loop
End Sub
What was wrong?
Here file = Dir you set your file variable which actually was the path to filename. And in the next iteration of the loop Set wb = Workbooks.Open(file & "\" & book) is twice a filename, the new filename in file and the old in book.
I have most of the codes but cannot run it. Some basic info is that my username is nywongab, I want it as a text file and the text file placed on the desktop.
Thanks
Sub createsth()
Dim abbyFilesystem As filesystemobject
Dim abbyfile As File
Set abbyFilesystem = CreateObject("scripting.filesystemobject")
Set abbyfile =_
abbyFilesystem.createtextfile("C:\Users\nywongab\Desktop"_
& ".txt")_
Dim result As String
result = "A"
abbyfile.write (result)
End Sub
Not quite clear the question.. though from the subject you have a problem with writing to file. From the code is obviously not working, but you were close.
If you are trying to get the username or the desktop path more dynamically, you can use Environ like so:
Sub createsth()
Dim pathDesktop As String
pathDesktop = Environ("USERPROFILE") & "\Desktop\"
Dim pathSave As String
pathSave = pathDesktop & Environ("USERNAME") & ".txt"
Dim abbyFileSystem As Object
Set abbyFileSystem = CreateObject("Scripting.FileSystemObject")
Dim abbyFile As Object
Set abbyFile = abbyFileSystem.CreateTextFile(pathSave)
Dim result As String
result = "A"
abbyFile.Write result
abbyFile.Close
End Sub
I'm trying to run a macro that will take a folder path I've provided and then take the file in that folder and make the file name the variable. That file name variable will then be used as part of a VLookup to get data from a cell within that file. Below is the code I've found so far, but I haven't been able to make it work:
Dim FilePath As String
FilePath = "____________________"
Set wbCodeBook = ThisWorkbook
With Application.FileSearch
.NewSearch
'Change path to suit
.LookIn = FilePath
.FileType = msoFileTypeExcelWorkbooks
'Optional filter with wildcard
.filename = "*AD*.xlsm*"
End With
I get Object doesn't support this action at the Application.FileSearch part of the code. I also don't know how I can take that code above and make the output the variable.
Is there any way to do this?
Do you mean something like this ?
Public Function GetFileName() As String
Dim sFilePath As String
Dim sFileName As String
'----------------
sFilePath = "____________________"
sFileName = "*AD*.xlsm*"
GetFileName = Dir(sFilePath & sFileName, vbNormal)
End Function
If you put it a module, you can then call it in a cell using =GetFileName().
I have written below piece of code to access a file and copy content from one file to the other. I am using excel 2007.
Sub copypaste()
Dim strFolder As String
Dim strFileName As String
Dim wb As Workbook
strFolder = "C:\Users\user\Desktop\sample\"
strFileName = Dir(strFolder & "*.xlsx")
Dim eRow
Dim a As Variant
Dim b As Variant
Do While Len(strFileName) > 0
**Set wb = Workbooks.Open(strFileName)**
a = Cells(7, 7)
b = Range("D11:F11")
ActiveWorkbook.Close
Worksheets("sheet1").Cells(7, 7) = a
Worksheets("sheet1").Cells(7, 8) = b
strFileName = Dir
Loop
End Sub
Although the file exists in the folder I get the error while opening the file. While in debug mode the variable strFileName contains the file name but still the file is not opening. I am getting the error at line "Set wb = Workbooks.Open(strFileName)"
Thanks in advance for your help!!
Workbooks.Open requires the full path to the workbook. I suspect you want:
Set wb = Workbooks.Open(strFolder & strFileName)
You need to replace all \ by double \\ in your path
Or add # in front of you string.
It is cause \ is the character for escape strings, like \n \s and so on so letter after a \ is transformed.
Try to print your path, you'll see what append.
EDIT
May also try :
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),");
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
As (gone) user user496736 stated you need to have a full path
But most of the time your path will be very long and cumbersome to type or you will not know it in advance, so the help of ActiveWorkbook.Path
Exemple with readonly just for information
Dim Alloc_WB As Workbook
Dim FileStr As String
FileStr = ActiveWorkbook.Path & "\" & "my_file.xlsx"
'workbook should be closed at start of code. Otherwise you get an error msg asking to re-open the Workbook
Set Alloc_WB = Workbooks.Open(Filename:=FileStr, ReadOnly:=True)
'...
'Other actions here...
'...
With Alloc_WB
.Close
End With