I am trying to check all of the permissions that I can so that people can choose any file and before it fails later on in the program they can get an error message that directly responds to why they cannot save to that location. The two that work right now that I have covered are "No Folder Selected," and "This File does NOT exist". Saying that it is readonly is not working and if anyone has any helpful tips that would be greatly appreciated or any ideas of more checks that I could do about the files. I am testing it using the program files file on my computer.
Sub CreateFile()
Dim BaseDirectory As String
Dim FS As FileSystemObject
Set FS = New FileSystemObject
BaseDirectory = GetFolder()
If (BaseDirectory = vbNullString) Then
MsgBox "No Folder Selected", vbExclamation, "Error"
GoTo EndProgram
End If
'Not Working
With FS.GetFolder(BaseDirectory)
If (.Attributes And ReadOnly) Then
MsgBox .Name & " is readonly!"
GoTo EndProgram
End If
End With
If Len(Dir(BaseDirectory)) = 0 Then
MsgBox "This file does NOT exist."
GoTo EndProgram
End If
EndProgram:
End Sub
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
I'm expecting this to say .Name is readonly!, but it does not work at .attributes and readonly. It just says This file does NOT exist
Here is a function that checks if the current user has write access to a folder. It works by creating a temp file in that folder for writing, if it's able to create it then it will return true. Otherwise, this function will return false.
'CHECK TO SEE IF CURRENT USER HAS WRITE ACCESS TO FOLDER
Public Function HasWriteAccessToFolder(ByVal FolderPath As String) As Boolean
'#example: HasWriteAccessToFolder("C:\Program Files") -> True || False
'MAKE SURE FOLDER EXISTS, THIS FUNCTION RETURNS FALSE IF IT DOES NOT
Dim Fso As Scripting.FileSystemObject
Set Fso = New Scripting.FileSystemObject
If Not Fso.FolderExists(FolderPath) Then
Exit Function
End If
'GET UNIQUE TEMP FilePath, DON'T WANT TO OVERWRITE SOMETHING THAT ALREADY EXISTS
Do
Dim Count As Integer
Dim FilePath As String
FilePath = Fso.BuildPath(FolderPath, "TestWriteAccess" & Count & ".tmp")
Count = Count + 1
Loop Until Not Fso.FileExists(FilePath)
'ATTEMPT TO CREATE THE TMP FILE, ERROR RETURNS FALSE
On Error GoTo Catch
Fso.CreateTextFile(FilePath).Write ("Test Folder Access")
Kill FilePath
'NO ERROR, ABLE TO WRITE TO FILE; RETURN TRUE!
HasWriteAccessToFolder = True
Catch:
End Function
Leverage the function? I'm using VBS (not VBA) but someone may still find this a useful observation. If you run the fso commands on a path that doesn't exist or perms issue it will return the function and error code, use that to determine if the user has access to that folder:
'VBS Example:
Function TestDirectory(FullDirPath)
'Purpose: test creation, if path doesn't exist or permissions issue, function will return error code
strDir = fso.GetAbsolutePathName(FullDirPath)
strDir = strDir & "\_randfoldercrtplsdelthis"
fso.CreateFolder strDir
If fso.FolderExists(strDir) Then
fso.DeleteFolder strDir, TRUE
End If
End Function
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Set Shell = CreateObject("WScript.Shell")
FilePath = "C:\Restricted Start Menu Locked\"
If TestDirectory(FilePath) <> 0 Then
WScript.Echo "Folder Access Denied? Error = " & Err.Number
Else
WScript.Echo "Woot!"
End If
Related
I have a piece of code that checks if an excel file opened or not by someone and display that user's username if it is opened. It was working fine, but recently it is throwing some error as shown in picture. But the error occurs only sometimes and not always. Anyone knows why?
Sub TestFileOpened()
Dim Folder As String
Dim FName As String
Dim fileOpenedOrNot As String
fileOpenedOrNot = "\\122.00.00.000\shared\Admin Confidential\Admin_Planner Database\Admin\Templates and Files\~$Running Numbers and ComboBox Lists.xlsx"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(fileOpenedOrNot) Then
fileInUse = True
MsgBox "Database is opened and using by " & GetFileOwner(fileOpenedOrNot) & ". Please wait a few seconds and try again", vbInformation, "Database in Use"
Else
fileInUse = False
End If
End Sub
Function GetFileOwner(strFileName)
Set objWMIService = GetObject("winmgmts:")
Set objFileSecuritySettings = _
objWMIService.Get("Win32_LogicalFileSecuritySetting='" & strFileName & "'")
intRetVal = objFileSecuritySettings.GetSecurityDescriptor(objSD)
If intRetVal = 0 Then
GetFileOwner = objSD.Owner.Name
Else
GetFileOwner = "Unknown"
End If
End Function
The following is the line that throwing error
objWMIService.Get("Win32_LogicalFileSecuritySetting='" & strFileName & "'")
Update 1
After further checks, I noticed there were no temp file ~$Running Numbers and ComboBox Lists.xlsx created although that file is opened. Basically objFSO.FileExists(fileOpenedOrNot) setting to true and going into that if condition. But when it calls the GetFileOwner function, it is not seeing the file and probably that is why have the error.
Like I mentioned, this code was working earlier without issues, but all of a sudden having such problem. Anyone knows why there is no such temp file created?
Check if this method works for you. Looks like it works for me better than yours but still it throws me Predefined\Administrators as owner on the network instead of the correct user name.
Option Explicit
Public Sub test()
Const fileOpenedOrNot As String = "\\122.00.00.000\shared\Admin Confidential\Admin_Planner Database\Admin\Templates and Files\~$Running Numbers and ComboBox Lists.xlsx"
Dim objFSO As FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(fileOpenedOrNot) Then
Dim objFile As Object
Set objFile = objFSO.GetFile(fileOpenedOrNot)
MsgBox GetFileOwner(objFile.ParentFolder & "\", objFile.Name)
End If
End Sub
Public Function GetFileOwner(ByVal fileDir As String, ByVal fileName As String) As String
Dim securityUtility As Object
Set securityUtility = CreateObject("ADsSecurityUtility")
Dim securityDescriptor As Object
Set securityDescriptor = securityUtility.GetSecurityDescriptor(fileDir & fileName, 1, 1)
GetFileOwner = securityDescriptor.Owner
End Function
I'm relatively new with VBA and currently working on a macro that will change from PC to PC, for test purposes I'm using the direct path:
Sub VIP()
'Define Folder Paths & Workbooks
Workbooks.Open ("C:\Users\j.lopez\Documents\AdHoc Reports\Serrano\Daily VIP Report Master.xlsx")
to open the workbooks, but eventually that path will change, so i was thinking to make the user select the folder path with:
Application.FileDialog(msoFileDialogFolderPicker)
But im lost, how can i properly:
1.- Ask for a user to select the folder containing the necessary files for the macro to work with
2.- Trap that path
3.- Replace it in the WorkBooks.Open
1. Ask for a user to select the folder containing the necessary files for the macro to work with:
I would recommend you to use FolderDialog and Show the Dialog to the user, and let him/her choose the folder. Next, check whether the required files exist in the selected directory. Use System.IO.File.Exists(<path>)=<boolean> .
2. Trap that path:
Just after validating the folder path, you can save the folder path in a variable.
Then do an assignment statement,
Let's say you created a variable 'path', so, path = path & "\" & <file_name> .
And there you have it, stored in 'path'.
3. Replace it in the WorkBooks.Open:
Then use the following code:
Workbooks.Open ("C:\Users\j.lopez\Documents\AdHoc Reports\Serrano\" & path)
Selecting file or folder with Browse File Option with VBA
' To Select File
sub select_file()
selected_file = Application.GetOpenFilename(, , "Select File", , False)
End sub
' To Select Folder
Sub selectfolder()
zhr_folder = GetFolder()
End sub
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = ""
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Post that you can combine both file and folder names to adapt your needs
Source: https://play.google.com/store/apps/details?id=com.vbausefulcodes.dp
EDIT-
This code was adapted to my needs, and i found it on this YouTube Video
Dim diaFolder As FileDialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
fle = diaFolder.SelectedItems(1)
Range("A15") = fle
Set diaFolder = Nothing
'Opening WorkBooks
Workbooks.Open (fle & "\Daily Sports VIP Report.xlsx")
video for Reference
- https://www.youtube.com/watch?v=Y4PG2qr9tRM
I am having difficulty figuring out how to put the Folder Path in Cell C49. I'd like to have the Path there for the User to understand where they are searching and if they have to change said Path.
I got this VBA code from,
http://learnexcelmacro.com/wp/2016/12/how-to-open-file-explorer-in-vba/
Private Sub cmd_button_BROWSEforFolder_Click()
On Error GoTo err
Dim fileExplorer As FileDialog
Set fileExplorer = Application.FileDialog(msoFileDialogFolderPicker)
'To allow or disable to multi select
fileExplorer.AllowMultiSelect = False
With fileExplorer
If .Show = -1 Then 'Any folder is selected
[folderPath] = .SelectedItems.Item(1)
ThisWorkbook.Sheets("Home").Range("C49") = .SelectedItems.Item(1)
Else ' else dialog is cancelled
MsgBox "You have cancelled the dialogue"
[folderPath] = "" ' when cancelled set blank as file path.
End If
End With
err:
Exit Sub
End Sub
I've tried rearranging the location of,
ThisWorkbook.Sheets("Home").Range("C49") = .SelectedItems.Item(1)
and tried changing
.SelectedItems.Item(1)
to,
[folderPath]
with no prevail.
what am I missing?
all I need is the path to be displayed above the txtbox and if it needs to be changed then the User used the button to redirect the search. (this button will not initiate the search Macro)
Private Sub cmd_button_BROWSEforFolder_Click()
On Error GoTo err
Dim fileExplorer As FileDialog
Set fileExplorer = Application.FileDialog(msoFileDialogFolderPicker)
Dim folderPath As String
'To allow or disable to multi select
fileExplorer.AllowMultiSelect = False
With fileExplorer
If .Show = -1 Then 'Any folder is selected
folderPath = .SelectedItems.Item(1)
Else ' else dialog is cancelled
MsgBox "You have cancelled the dialogue"
folderPath = "NONE" ' when cancelled set blank as file path.
End If
End With
err:
ThisWorkbook.Sheets("Home").Range("C49") = folderPath
End Sub
I have script that printing specific file, but it's getting hard to make over 150 .vbs files for each document to be printed,
is there any way to have pop-out window where i can type file name, then script find it in folder and print it with 20 copies.
I have PDF, WORD and Excel files
this is what i have now for them
Dim AppExcel
Set AppExcel = CreateObject("Excel.application")
AppExcel.Workbooks.Open"directory\filename.xlsx"
AppExcel.Visible = True
AppExcel.ActiveWindow.SelectedSheets.PrintOut,,20
Appexcel.Quit
Set appExcel = Nothing
filename = "\\MCSERVER01\Data\Forms\Vehicle inspection forms\daily vehicle inspection form.pdf"
Set sh = CreateObject("WScript.Shell")
sh.Run "sumatrapdf.exe -print-to-default """ & filename & """", 0, True
Dim AppWord
Set AppWord = CreateObject("Word.application")
AppWord.Documents.Open"\\MCSERVER01\Data\Forms\DODD\SMALL CAR DRIVERS\Akira Litman.docx"
AppWord.Visible = True
AppWord.ActiveDocument.PrintOut
AppWord.Quit
Set appWord = Nothing
Perhaps you can make use of an input box
Dim fileToPrint As String
fileToPrint = InputBox("Enter file name to print")
I got some help from my old friend, but now i can't get another part working
set fso = CreateObject("Scripting.FileSystemObject")
call main
sub main
InputName = InputBox("ENTER YOUR NAME")
if instr(InputName, ".") = 0 then
msgbox("DON'T NEED THIS AT ALL!!!!!")
exit sub
end if
'msgbox(mid(InputName, instr(InputName, ".")+1))
select case mid(InputName, instr(InputName, ".")+1)
case "xlsx"
call printExcel(InputName)
end select
end sub
sub printExcel(fileName)
Dim AppExcel, path
Set AppExcel = CreateObject("Excel.application")
path = "\MCSERVER01\Data\Forms\Access2Care\WHEELCHAIR DRIVERS\"
if fso.FileExists(path & fileName) then
AppExcel.Workbooks.Open path & fileName
AppExcel.Visible = false
AppExcel.ActiveWindow.SelectedSheets.PrintOut,,20
Appexcel.Quit
Set appExcel = Nothing
else
X=MsgBox ("Wrong File Name Or File Doesn't Exist" ,0+16, "Please Re-Enter Your Full Name")
end if
end sub
so the issue i have now is that i have to type in file extension to make it work otherwise im getting msgbox with "don't need this"
how i can get rid of that msg and just have default extension as xlsx xsl
I have this code. It is supposed to check if a file exists and open it if it does. It does work if the file exists, and if it doesn't, however, whenever I leave the textbox blank and click the submit button, it fails. What I want, if the textbox is blank is to display the error message just like if the file didn't exist.
Runtime-error "1004"
Dim File As String
File = TextBox1.Value
Dim DirFile As String
DirFile = "C:\Documents and Settings\Administrator\Desktop\" & File
If Dir(DirFile) = "" Then
MsgBox "File does not exist"
Else
Workbooks.Open Filename:=DirFile
End If
something like this
best to use a workbook variable to provide further control (if needed) of the opened workbook
updated to test that file name was an actual workbook - which also makes the initial check redundant, other than to message the user than the Textbox is blank
Dim strFile As String
Dim WB As Workbook
strFile = Trim(TextBox1.Value)
Dim DirFile As String
If Len(strFile) = 0 Then Exit Sub
DirFile = "C:\Documents and Settings\Administrator\Desktop\" & strFile
If Len(Dir(DirFile)) = 0 Then
MsgBox "File does not exist"
Else
On Error Resume Next
Set WB = Workbooks.Open(DirFile)
On Error GoTo 0
If WB Is Nothing Then MsgBox DirFile & " is invalid", vbCritical
End If
I use this function to check for file existence:
Function IsFile(ByVal fName As String) As Boolean
'Returns TRUE if the provided name points to an existing file.
'Returns FALSE if not existing, or if it's a folder
On Error Resume Next
IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory)
End Function
For checking existence one can also use (works for both, files and folders):
Not Dir(DirFile, vbDirectory) = vbNullString
The result is True if a file or a directory exists.
Example:
If Not Dir("C:\Temp\test.xlsx", vbDirectory) = vbNullString Then
MsgBox "exists"
Else
MsgBox "does not exist"
End If
A way that is clean and short:
Public Function IsFile(s)
IsFile = CreateObject("Scripting.FileSystemObject").FileExists(s)
End Function
Function FileExists(ByRef strFileName As String) As Boolean
' TRUE if the argument is an existing file
' works with Unicode file names
On Error Resume Next
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
FileExists = objFSO.FileExists(strFileName)
On Error GoTo 0
End Function
To make the function run faster, objFSO can be made a global variable and the code can be modified and saved in a module like this:
Option Explicit
Dim objFSO As Object
Function FileExists(ByRef strFileName As String) As Boolean
' TRUE if the argument is an existing file
' works with Unicode file names
On Error Resume Next
If objFSO Is Nothing Then Set objFSO = CreateObject("Scripting.FileSystemObject")
FileExists = objFSO.FileExists(strFileName)
On Error GoTo 0
End Function
For strFileName to be a unicode string, you can, for example, either get it from a cell value or define it in a special way, as Excel's VBE doesn't save string constants in Unicode. VBE does support Unicode strings already saved in string variables. You're gonna have to look this up for further details.
Hope this helps somebody ^_^
Maybe it caused by Filename variable
File = TextBox1.Value
It should be
Filename = TextBox1.Value
Speed of Various FileExists Methods
I needed to check file existence for many of my projects, so I wanted to determine the fastest option. I used the micro timer code (see Benchmarking VBA Code) to run the File Exist functions below the table against a local folder with 2865 files to see which was faster. Winner used GetAttr. Using FSO method for Test 2 was a bit faster with the object defined as a global than not, but not as fast as the GetAttr method.
------------------------------------------------------
% of Fastest Seconds Name
------------------------------------------------------
100.00000000000% 0.0237387 Test 1 - GetAttr
7628.42784145720% 1.8108896 Test 2 - FSO (Obj Global)
8360.93687615602% 2.0522254 Test 2 - FSO (Obj in Function)
911.27399562739% 0.2163246 Test 3 - Dir
969.96844814586% 0.2302579 Test 4 - Dir$
969.75108156723% 0.2302063 Test 5 - VBA.Dir
933.82240813524% 0.2216773 Test 6 - VBA.Dir$
7810.66612746275% 1.8541506 Test 7 - Script.FSO
Function FileExistsGA(ByVal FileSpec As String) As Boolean
' Karl Peterson MS VB MVP
Dim Attr As Long
' Guard against bad FileSpec by ignoring errors
' retrieving its attributes.
On Error Resume Next
Attr = GetAttr(FileSpec)
If Err.Number = 0 Then
' No error, so something was found.
' If Directory attribute set, then not a file.
FileExistsGA = Not ((Attr And vbDirectory) = vbDirectory)
End If
End Function
Function FSOFileExists(sFilePathNameExt As String) As Boolean
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
FSOFileExists = fso.FileExists(sFilePathNameExt)
Set fso = Nothing
End Function
Function FileExistsDir(sFilePathNameExt As String) As Boolean
If Len(Dir(sFilePathNameExt)) > 0 Then FileExistsDir = True
End Function
Function FileExistsDirDollar(sFilePathNameExt As String) As Boolean
If Len(Dir$(sFilePathNameExt)) > 0 Then FileExistsDirDollar = True
End Function
Function FileExistsVBADirDollar(sFilePathNameExt As String) As Boolean
If Len(VBA.Dir$(sFilePathNameExt)) > 0 Then FileExistsVBADirDollar = True
End Function
Function FileExistsVBADir(sFilePathNameExt As String) As Boolean
If Len(VBA.Dir(sFilePathNameExt)) > 0 Then FileExistsVBADir = True
End Function
Public Function IsFileSFSO(s)
IsFileSFSO = CreateObject("Scripting.FileSystemObject").FileExists(s)
End Function
I realize that this does not fully answer the OP, but is provides information on which of the answers provided seems to be most efficient.
I'll throw this out there and then duck.
The usual reason to check if a file exists is to avoid an error when attempting to open it. How about using the error handler to deal with that:
Function openFileTest(filePathName As String, ByRef wkBook As Workbook, _
errorHandlingMethod As Long) As Boolean
'Returns True if filePathName is successfully opened,
' False otherwise.
Dim errorNum As Long
'***************************************************************************
' Open the file or determine that it doesn't exist.
On Error Resume Next:
Set wkBook = Workbooks.Open(fileName:=filePathName)
If Err.Number <> 0 Then
errorNum = Err.Number
'Error while attempting to open the file. Maybe it doesn't exist?
If Err.Number = 1004 Then
'***************************************************************************
'File doesn't exist.
'Better clear the error and point to the error handler before moving on.
Err.Clear
On Error GoTo OPENFILETEST_FAIL:
'[Clever code here to cope with non-existant file]
'...
'If the problem could not be resolved, invoke the error handler.
Err.Raise errorNum
Else
'No idea what the error is, but it's not due to a non-existant file
'Invoke the error handler.
Err.Clear
On Error GoTo OPENFILETEST_FAIL:
Err.Raise errorNum
End If
End If
'Either the file was successfully opened or the problem was resolved.
openFileTest = True
Exit Function
OPENFILETEST_FAIL:
errorNum = Err.Number
'Presumabley the problem is not a non-existant file, so it's
'some other error. Not sure what this would be, so...
If errorHandlingMethod < 2 Then
'The easy out is to clear the error, reset to the default error handler,
'and raise the error number again.
'This will immediately cause the code to terminate with VBA's standard
'run time error Message box:
errorNum = Err.Number
Err.Clear
On Error GoTo 0
Err.Raise errorNum
Exit Function
ElseIf errorHandlingMethod = 2 Then
'Easier debugging, generate a more informative message box, then terminate:
MsgBox "" _
& "Error while opening workbook." _
& "PathName: " & filePathName & vbCrLf _
& "Error " & errorNum & ": " & Err.Description & vbCrLf _
, vbExclamation _
, "Failure in function OpenFile(), IO Module"
End
Else
'The calling function is ok with a false result. That is the point
'of returning a boolean, after all.
openFileTest = False
Exit Function
End If
End Function 'openFileTest()
Here is my updated code. Checks to see if version exists before saving and saves as the next available version number.
Sub SaveNewVersion()
Dim fileName As String, index As Long, ext As String
arr = Split(ActiveWorkbook.Name, ".")
ext = arr(UBound(arr))
fileName = ActiveWorkbook.FullName
If InStr(ActiveWorkbook.Name, "_v") = 0 Then
fileName = ActiveWorkbook.Path & "\" & Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, ".") - 1) & "_v1." & ext
End If
Do Until Len(Dir(fileName)) = 0
index = CInt(Split(Right(fileName, Len(fileName) - InStr(fileName, "_v") - 1), ".")(0))
index = index + 1
fileName = Left(fileName, InStr(fileName, "_v") - 1) & "_v" & index & "." & ext
'Debug.Print fileName
Loop
ActiveWorkbook.SaveAs (fileName)
End Sub
You should set a condition loop to check the TextBox1 value.
If TextBox1.value = "" then
MsgBox "The file not exist"
Exit sub 'exit the macro
End If
Hope it help you.