I'm doing a check to make sure that my code is able to see my file before I move to the next step of my program. This is my code, but it always displays as the path not existing. Did I do something wrong?
Sub NewNameiLoop()
Dim i As Double
Dim NameStr As String
Dim NewNamePath As String
NameStr = Renamer.New_Name.Text
NewNamePath = Renamer.Path_Text.Text & "\" + NameStr & "-" & Right("00" & i, 3) & ".ipt"
Do While i < 99 'Counts with the file name up to -099
i = i + 1
If vbOK Then
MsgBox (Renamer.Path_Text.Text & "\" + NameStr & "-" & Right("00" & i, 3))
If Dir(NewNamePath) <> "" Then
MsgBox "Path Exists."
Else: MsgBox "Path does not exist."
End If
Else: Exit Sub
End If
Loop
End Sub
Other information:
This code is in the module NewNameLoop in the sub NewNameiLoop.
The form it goes to is called Renamer. The form calls NewNameiLoop when the user clicks "Apply" to rename some files. After they are renamed, they call this code to check for the file's existence.
The MsgBox displayed contains the full, correct path.
This is in Autodesk Inventor, not Excel! Thus far, the coding has been pretty much the same. No weird quirks or anything.
JPEGs of what is happening. As explained below, I AM able to access C:\ and things within C:. The first parts of my program make a whole new folder and copy a different folder's contents in to it. After that it goes to the original folder and renames all the files. So does that mean it is indeed a coding problem? No one seems to know.
The Dir will return nothing if:
1) The .ipt file does not exists or the file name is different from what you coded
2) No access to the folder
If you are not concern with the filename I suggest to leave the NewNamepath as Renamer.Path_Text.Text & "\" and do a file search in this path for the file you are looking for
Yes, apparently you can't do a 'Dir' on that folder. But you can use FileSystemObject.
Add a Project reference to "Microsoft Scripting Runtime"
Then adapt the following approach:
Dim oFSO As FileSystemObject
Set oFSO = New FileSystemObject
If oFSO.FileExists(NewNamePath) Then
Debug.Print "Found it"
Else
Debug.Print "Not Found"
End If
Set oFSO = Nothing
Related
Somewhere on the internet I found this code to easily save a .docx file out of a .dotx file into the desired folder:
Sub SaveFileInTheCorrectDirectory()
ActiveDocument.SaveAs2 "[the correct directory, put in manually by me in the VBA code]" & InputBox("Type the desired file name", "Save As")
End Sub
However, this code automatically overwrites an already existing file with the same name (and in the same directory, of course). I've tried looking for code to fix this, and found a few suggestions:
Trying to save word file, from excel vba, without over-writing any existing files
https://answers.microsoft.com/en-us/msoffice/forum/all/vba-macro-saveas-overights-exsiting-file-without/e6fce3b1-ee72-498d-8fe5-fbc3e0cdbf23
http://computer-programming-forum.com/1-vba/2fb545278f4311ff.htm
https://groups.google.com/g/microsoft.public.word.vba.customization/c/Q4W2CK4gQOg?pli=1
But I can't figure out how to implement them...
Could someone be so kind to assist me?
Thanks!
PS Is there added value to use "SaveAs2" instead of "SaveAs" or the other way around?
That's as simple as:
Dim StrName as String
StrName = InputBox("Type the desired file name", "Save As")
If Trim(StrName) = "" then Exit Sub
If Dir(StrPath & StrName & ".docx") = "" Then ActiveDocument.SaveAs2 StrPath & StrName & ".docx"
where StrPath & StrName are the path & name, respectively.
Note: I haven't added any code for what to do if the file exists because you haven't said what you want to do in that case. Post a new question if you need help with that.
I am trying to use VBA to open a .xls file in a specific directory but am unable to do so because of a VBA run-time error. I need to use a wildcard in the path because the filename changes slightly month-to-month, but it always begins with "CB947." I need to copy data from the CB947 workbook into my Master workbook. Here's what I have so far:
Dim dpath, sFound As String
dpath = "C:\Users\gbrown\OneDrive - My Company\REVPRO\Input Data\2018\January\"
Set Master = ThisWorkbook
sFound = Dir(dpath & "\CB947*.xls")
Debug.Print dpath & sFound
If (sFound <> "") Then
Workbooks.Open dpath & sFound
End If
When I get to the Debug.print command above, the Immediate window prints out the correct path and filename, so I know the script is locating the correct file. It just isn't able to open it. When I try and run the above code, I get the following error:
Is my DIR sytax incorrect or am I missing something else?
EDIT: here's what my Debug.Print command shows in the Immediate window:
C:\Users\gbrown\OneDrive - My Company\REVPRO\Input Data\2018\
January\CB947 (4).xls
Turn on Option Explicit
You can't declare variables that way, dpath is a variant
You have two slashes in your path
Let's add vbNormal to your Dir call, just in case
THIS WORKED FOR ME:
Dim dpath As String
Dim sFound As String
dpath = "C:\Users\gbrown\OneDrive - My Company\REVPRO\Input Data\2018\January\"
sFound = Dir(dpath & "CB947*.xls", vbNormal)
Debug.Print dpath & sFound
If (sFound <> "") Then
Workbooks.Open dpath & sFound
End If
NOTE: If this isn't working for you, then there might be a permissions issue. The workbook might be locked or unavailable to be opened for some filesystem reason.
I wanted to copy a local file to sharepoint library using VBA by clicking an image. Right now seems like I'm unable to check for Folder & Files on SharePoint.
As every time I ran the code(by clicking an image in excel), it returns unable to find the file in SharePoint. And stops at returning the MsgBox Sorry there's no such Folder......
I tried mapping drive, it works perfectly fine, but not an options because end-user need to map the drive by themselves.
So now I'm looking to connecting to SharePoint using the link.
If I copy the SharePointLink to IE & Chrome using \, it works fine. But if I uses /, IE is unable to find the link.
UPDATE
If I uses \ after few tries, IE, will open up the file path in NetWork. Chrome will show the file path on chrome page. Why is this happening?????
The authentication is using windows authentication, so not an issue.
This is my code
Sub imgClicked()
Dim SharePointLib As String
Dim MyPath As String
Dim folderPath As String
Dim objNet As Object
Dim FSO As Object
Dim copyPath As String
Dim copyFilePath As String
folderPath = Application.ThisWorkbook.path
MyPath = Application.ThisWorkbook.FullName
SharePointLib = "//company.com/sites/MS/10%20Mg%20Review/"
' create new folder to store the file
copyPath = folderPath + "\copyPath\"
If Not FolderExists(copyPath) Then
FolderCreate (copyPath)
ElseIf Not FolderExists(SharePointLib) Then
MsgBox "Sorry there's no such folder. Folder Path: " & vbNewLine & vbNewLine & SharePointLib & ""
Exit Sub
End If
fileName = "hello.xlsm"
'Copy current excel file and save at the new folder created
ThisWorkbook.SaveCopyAs copyPath & fileName
MsgBox "Save Copy As: " + copyPath & filseName & vbNewLine & vbNewLine & "The file will be uploaded to this address: " + SharePointLib & fileName
' Check whether the file exist in the directory
' If exist error message
' else copy the file from copyPath then paste at the SharePoint directory
If Not Dir(SharePointLib & fileName, vbDirectory) = nbNullString Then
MsgBox "Sorry file already exist!"
Else
Call FileCopy(copyPath & fileName, SharePointLib & fileName)
MsgBox "File has being successfuly created in SharePoint!"
End If
Set FSO = CreateObject("scripting.filesystemobject")
If Right(copyPath, 1) = "\" Then
copyPath = Left(copyPath, Len(copyPath) - 1)
End If
If FSO.FolderExists(copyPath) = False Then
MsgBox copyPath & " doesn't exist"
Exit Sub
End If
FSO.DeleteFolder copyPath
MsgBox "Folder has being deleted successfully!"
End Sub
Function for checking if folder exists
Function FolderExists(ByVal path As String) As Boolean
FolderExists = False
Dim FSO As New FileSystemObject
If FSO.FolderExists(path) Then FolderExists = True
End Function
Function for creating Folder
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim FSO As New FileSystemObject
try:
If FSO.FolderExists(path) Then
Exit Function
Else
On Error GoTo catch
FSO.CreateFolder path
Debug.Print "FolderCreate: " & vbTab & path
Exit Function
End If
catch:
MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
FolderCreate = False
Exit Function
End Function
Any help and suggestions are appreciated. Let me know if more info is needed. Thanks in advance.
Ensure the WebClient service is running. You can start the WebClient service through code, or you could set the startup type to automatic.
With the WebClient service running, your folder/file tests will work as expected.
Edit: Additionally, if you map the sharepoint url to a drive letter, Windows will start the WebClient service.
Sub mapPath(str_drive as string, str_path as string)
If Not Len(str_drive) = 1 Then Exit Sub
Dim wso As Object
Set wso = CreateObject("WScript.Network")
wso.MapNetworkDrive str_drive & ":", str_path, False
End Sub
I have an email message with an image attachment that I want to save with a VBA macro. The file name and the display name show French accents in the attachment name (e.g. "Événement.jpg").
Saving the attachment with Outlook VBA works:
Dim fso As Object
Dim sFileName As String
Dim oAttachment As Outlook.attachment
set fso = CreateObject("Scripting.FileSystemObject")
' Edit the folder location accordingly:
sFileName = "C:\Users\YOUR_ACCOUNT_HERE\Desktop\" & oAttachment.getFileName
oAttachment.SaveAsFile sFileName
I can see the file correctly named on the file system.
Trying to access this file within VBA later on fails. The following code always returns FALSE:
' Returns False
MsgBox "File [" & sFileName & "] exists? " & sfo.fileexists(sFileName), vbInformation
Dim bFileExists as Boolean
If lenB (Dir(sFileName) > 0 Then
bFileExists = True
Else
bFileExists = True
EndIf
' Also returns False
MsgBox "File [" & sFileName & "] exists? " & bFileExists, vbInformation
What am I doing wrong?
I eventually came upon a workaround, thanks to the MS-DOS "8.3" file naming legacy of Windows. Converting the file name to its short file name makes Dir() and Open() happy:
Dim sFileShortName As String
sFileShortName = fso.Getfile(sTempFileLocation).shortpath
bFileExists = (Dir(sFileShortName) <> "") ' Now returns True at last!
Now fso.FileExists(sFileShortName) as well as bFileExists (based on Dir()) return True and Open sFileShortName For Binary Access Read As lFileNum works as well.
I hope that this will be beneficial to others.
I was looking for any options on a browse for folder within Outlook VBA. Currently I have, from a previous search:
Dim save_to_folder As String
save_to_folder = InputBox("Search returned " & objRsts.Count & " messages._
Please input folder location")
olkMsg.SaveAs save_to_folder & "\" & strDateName & " " & strFileName & ".msg"
Where strDateName and strFileName are modified subjects and dates of the emails.
My problem is that I would like a browse option along with manually typing to prevent typos. I'm very new to VBA and need to auto-save emails very often, please let me know what my options are.
You could set up your code so you choose between InputBox and BrowseForFolder.
You could set these up separately.
I suggest you could use BrowseForFolder exclusively.
Dim oShell As Object
Set oShell = CreateObject("Shell.Application")
Dim save_to_folder As Object
Set save_to_folder = _
oShell.BrowseForFolder(0, "Please Select a Save Folder:", 1)
If save_to_folder Is Nothing Then Exit Sub
' Note: BrowseForFolder doesn't add a trailing slash
Sample code here Macro to move selected outlook emails