Creating a folder in a network drive using vba - excel

I need to connect to a network drive and create a folder. I dont know the IP of the drive. Also I dont want to use the drive letter as this VBA will be used by many people on their PC.
I tried this :
Public Function create_folder()
Dim NetworkObject As Object
Dim FSO As Object
Dim Directory As Object
Dim Filename As Object
Dim ServerShare As String
ServerShare = "\\SSSXCXC\FOL_SAS\ASD123\"
Set NetworkObject = CreateObject("WScript.Network")
Set FSO = CreateObject("Scripting.FileSystemObject")
NetworkObject.MapNetworkDrive "", ServerShare, False
Set Directory = FSO.CreateFolder(ServerShare & "\AAA")
End Function
But I am getting path error.

I think you don't need to map the network drive to create a folder. If you have write access, the folder should be created.
Const SERVER_PATH As String = "\\SSSXCXC\FOL_SAS\ASD123\"
Dim folderPath As String
folderPath = SERVER_PATH & "AAA"
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(folderPath) Then .CreateFolder folderPath
End With

Function GetNetworkPath(ByVal DriveName As String) As String
Dim objNtWork As Object
Dim objDrives As Object
Dim lngLoop As Long
Set objNtWork = CreateObject("WScript.Network")
Set objDrives = objNtWork.enumnetworkdrives
For lngLoop = 0 To objDrives.Count - 1 Step 2
If UCase(objDrives.Item(lngLoop)) = UCase(DriveName) Then
GetNetworkPath = objDrives.Item(lngLoop + 1)
Exit For
End If
Next
End Function

I have a similar problem which I'll explain, and a working solution at the bottom (which can write to the network but not copy).
I would like to copy a folder on the network and rename it.
It's a folder with a nest of sub-folders we use as a template.
It looks like it should work from the Locals window, but the folder doesn't get created.
I assume it's a network rights problem
Sub CreateMajorResponseFile()
'creates a response folder with the app number as folder name
'declare road name as a variable
Dim Road As String
Dim AppNo As String
Dim Prefix As String
Dim FolderPath As String
Dim tbl As ListObject
Dim LastRow As Long
'enable code to use Scripting.FileSytemObject so it's easy to copy and rename a folder pt1
Dim FSO As Object
'pt2 of enable code to use Scripting.FileSytemObject so it's easy to copy and rename a folder
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim SourceFolder As String
Dim DestinationFolder As String
'set the folder you want to copy
SourceFolder = "S:my source folder"
'set the file path for the folder you want to copy to
DestinationFolder = "S:\my destination folder" & Road
'set the road variable to be 4 rows right of selected cell
Road = ActiveCell.Offset(0, 4).value
'set the AppNo the selected cell
AppNo = ActiveCell.value
AppNo = Left(AppNo, 6) & "-" & Right(AppNo, 5)
Prefix = Application.InputBox("Enter N followed by EITHER property number OR short name", "Give it a prefix", "N")
''create folder with file path to the road name folder
'MkDir "S:\my network path" & "\" & Road & "\" & Prefix & " " & AppNo & Suffix
FSO.CopyFolder Source:=SourceFolder, Destination:=DestinationFolder & "\" & Prefix & " " & AppNo
End Sub
But I have another piece of code that can create a new folder on the network without using file system objects. This is the code
Sub CreateResponseFile()
'creates a response folder with the app number as folder name
'declare road name as a variable
Dim Road As String
Dim AppNo As String
Dim Prefix As String
Dim Suffix As String
Dim FolderPath As String
'set the road variable to be 4 rows right of selected cell
Road = ActiveCell.Offset(0, 4).value
'set the AppNo the selected cell
AppNo = ActiveCell.value
AppNo = Left(AppNo, 6) & "-" & Right(AppNo, 5)
Prefix = Application.InputBox("Enter N followed by EITHER property number OR short name", "Give it a prefix", "N")
Suffix = Application.InputBox("Enter a space followed by e.g. C16 cycl parking or CEMP etc, if full app leave blank", "Give it a suffix", " C99EVCP")
'create folder with file path to the road name folder
MkDir "S:\my network path" & "\" & Road & "\" & Prefix & " " & AppNo & Suffix
End Sub
so it seems MkDir can work over a network where FSO copy cannot

Related

Unable to copy files (.pdf/.jpeg/.jpg) from one folder to another

Using 2010 Excel VBA - I need to use look up the image/pdf with the Branch Code as a part of its name at "C:\ECB Test\ECB IR COPY" and paste it at "C:\ECB Test\" RO if it exists. If it doesn't, the program needs to highlight the Branch Code.
(File Name Examples: 28-Kochi-ecb-sdwan completed.pdf, 23 eCB Kozhikode completed.pdf/0036.jpeg)
Having done this manually twice for two other excel sheets (4k+ cells), I decided to Frankenstein a module together and, well, it does not work and I have no idea why.
Sub Sort()
Const SRC_PATH As String = "C:\ECB Test\ECB IR COPY"
Const DEST_PATH As String = "C:\ECB Test"
Dim Row_Number As Integer
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Dim Folder_Name As String
Dim Branch_Code As String
Dim Final_Path As Variant
Dim File As String
For Row_Number = 3 To 2465
Branch_Code = Worksheets("WAN RFP").Cells(Row_Number, 2)
Folder_Name = Worksheets("WAN RFP").Cells(Row_Number, 5)
On Error Resume Next
File = Dir(SRC_PATH & "\*" & Branch_Code & "*")
Final_Path = Dir(DEST_PATH & "\" & Folder_Name & "\")
If (Len(File) > 0) Then
Call fso.CopyFile(File, Final_Path)
Else
Cells(Row_Number, 2).Interior.ColorIndex = 6
End If
On Error GoTo 0
DoEvents
Next Row_Number
End Sub
I think its unable to use the Branch Code variable as a wildcard, though I might as well have done something silly somewhere in the code. Can someone please help me out?
The problem is you are using the destination path instead of the source path:
File = Dir(DEST_PATH & "*" & Branch_Code & "*.*")
Change it to
File = Dir(SRC_PATH & "*" & Branch_Code & "*.*")

VBA Error 1004 Can't Find "File Name" When Trying To Open File

I am trying to open all Excel files (.xlsx) in a specified folder and extract information from each one to add to a master spreadsheet for a report.
I can't open the file. I get a
Run-time error '1004'
saying it couldn't find FILE.xlsx.
The file name is correct and matches the file name and extension (.xlsx).
The last line of the code isn't working.
Dim FileName As String
Dim Folder As String
Dim Month As String
Dim File As Variant
Month = MonthName(CurrentMonth)
Folder = "C:\Users\mpresley\Documents\Other\Ben\Forecast Summary\Forecast"
FolderName = Folder & Month & CurrentYear
Dim firstEmptyRow As Long
Dim attachmentFolder As String, StrFile As String, filenameCriteria As String
Dim attachmentWorkBook As Workbook
Dim copyRngToArray As Variant
'# Set file extension
filenameCriteria = "xlsx"
'set
StrFile = Dir(FolderName & "\*" & filenameCriteria)
Do While Len(StrFile) > 0
Set attachmentWorkBook = Workbooks.Open(StrFile)
Specify both the folder path and the file name:
Set attachmentWorkBook = Workbooks.Open(FolderName & "\" & StrFile)

Connecting two path strings to get the final path?

I'm trying to save excel file into a specific path.
So basically, when I click the button, I'm creating a folder, and want to save the file inside that folder.
The created folder has the current month as name. I'm trying to save into that current month folder.
'Create folder as Month Name. Save filename as date inside "month".
Dim sDate As String = DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss")
Dim sMonth As String = DateTime.Now.ToString("MMMM")
Dim sFolder = Application.StartupPath & "\Resources\Excel\"
My.Computer.FileSystem.CreateDirectory(sFolder & Format(sMonth))
Dim sfinal = Path.Combine(sFolder, sMonth)
xlSh.SaveAs(sfinal & Format(sDate) & ".xlsx")
xlApp.Workbooks.Close()
xlApp.Quit()
As it is, this code doesn't give me any errors. But instead of creating a folder named "March" <-current month and saving inside it, it saves the file in \Excel\ and it also creates folder in the same place.
you could use the following function (similar to .NET System.IO.Path.Combine)
Function PathCombine(path1 As String, path2 As String)
Dim combined As String
combined = path1
If Right$(path1, 1) <> Application.PathSeparator Then
combined = combined & Application.PathSeparator
End If
combined = combined & path2
PathCombine = combined
End Function
Hope this helps!
After long hours of excruciating pain, I've finally did it!
Apparently I was missing an "\"
Since "sMonth" became dynamic name, which later I wanted to use as path, and save files in that folder. I needed to simply put that "\" after sMonth, to tell it to save inside it.
Before I realize this... I've broken down, simplified the code as much as I could so I can logically connect the pieces. What I ended up with, is something slightly different. Now the SaveAS properly saves the file inside the new folder.
Dim sDate As String
sDate = DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss")
Dim sMonth As String
sMonth = DateTime.Now.ToString("MMMM")
Dim sFileName As String
sFileName = sDate + ".xlsx"
Dim sFolder As String
sFolder = Application.StartupPath & "\Resources\Excel\"
Dim sfinal As String
sfinal = (sFolder & sMonth & "\") '<- this thingie here o.O
My.Computer.FileSystem.CreateDirectory(sFolder & Format(sMonth))
xlSh.SaveAs(sfinal & Format(sFileName))
xlApp.Workbooks.Close()
xlApp.Quit()
Thanks for the help.
You don't appear to actually be setting the save path to the created directory. Instead, I believe you're appending the month to the beginning of the file name in the xlSh.SaveAs(sFinal & Format(sDate) & ".xlsx"). Basically (though I'm not sure of the specific command) you need to navigate to the folder you created after you create it. Probably something to the format of
My.Computer.FileSystem.ChangeDirectory(sFolder & Format(sMonth))
though I don't know that that specific command actually exists as I wrote it.
To those who have been wondering wtf I was doing with all this, here is the full sub. And if anyone needs something similar. Thanks for the support. Problem has been resolved.
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button.Click
Dim xlApp As Excel.Application
Dim xlSh As Excel.Worksheet
xlApp = New Excel.Application
xlApp.Workbooks.Add()
xlSh = xlApp.Workbooks(1).Worksheets(1)
'Items from listbox1 to be exported into excel, second row, second column.
Dim row As Integer = 2
Dim col As Integer = 2
For i As Integer = 0 To ListBox1.Items.Count - 1
xlSh.Cells(row, col) = ListBox1.Items(i)
row = row + 1
Next
row += 1
col = 1
'Items from listbox2 to be exported into excel, second row, third column.
Dim row2 As Integer = 2
Dim col2 As Integer = 3
For i As Integer = 0 To ListBox2.Items.Count - 1
xlSh.Cells(row2, col2) = ListBox2.Items(i)
row2 = row2 + 1
Next
row2 += 1
col2 = 1
'Create folder as Month Name. Save filename as date inside that folder.
'Make filename be yyyy-MM-DD_HH-mm-ss
Dim sDate As String
sDate = DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss")
'This will be used as name for the new folder.
Dim sMonth As String
sMonth = DateTime.Now.ToString("MMMM")
'Filename + extension.
Dim sFileName As String
sFileName = sDate + ".xlsx"
'This is the path.
Dim sFolder As String
sFolder = Application.StartupPath & "\Resources\Excel\"
'This is the path combined with sMonth to make the final path.
Dim sfinal As String
sfinal = (sFolder & sMonth & "\")
'Check if folder with the name sMonth already exists.
If Dir(sFolder, vbDirectory) = sMonth Then
'If it exist, then simply save the file inside the folder.
xlSh.SaveAs(sfinal & Format(sFileName))
Else
'If it doesn't exist:
'This is the creation of sMonth folder, inside "\excel\.
My.Computer.FileSystem.CreateDirectory(sFolder & Format(sMonth))
'This saves the excel file at path sfinal, with filename of sFileName
xlSh.SaveAs(sfinal & Format(sFileName))
End If
'Close everything.
xlApp.Workbooks.Close()
xlApp.Quit()
End Sub
I find this method to be much easier.
Create a FileSystemObject and use BuildPath Method, like so:
Set fs = CreateObject("Scripting.FileSystemObject")
skPath = fs.BuildPath(ActiveDocument.Path, "Survival Story of Sword King")
Attention: ActiveDocument.Path is current directory in Word and does not work in excel or other. for excel it would be ActiveWorkbook.Path
My point is some methods or namespace are application specific.

How do I check a directory for a file name given by an InputBox in VBA?

My code asks the user to input a file name. We'll say we have 5 text files in directory "C:\Users\aUser\Desktop\myFolder". These text files are named A, B, C, D, and E.
If the text file exists, then I would like to write over the contents with a script I've already made. If the text file does not exist, I would like to make one with the file name they inputted, and populate it [with the script I've already written].
Thanks for your help.
The way you explain it, it seems that the easiest workflow would be:
1) Delete the file if exists
Sub test()
Dim FSO As FileSystemObject
Dim sPath As String
sPath = "U:\Test.txt"
Set FSO = New FileSystemObject
If FSO.FileExists(sPath) Then
FSO.DeleteFile (sPath)
End If
End Sub
Copy the script (I assume also a txt file) into the path:
FileCopy "U:\Script", sPath
If you have the script in a string variable:
Set txtFile = FSO.CreateTextFile(sPath, True)
txtFile.WriteLine(sText)
FSO.Close
End Sub
If the script is contained in an array, you can loop through the array and produce multiple writelines.
Don't forget to reference the Microsoft Scripting Runtime library.
Something like this
locates the folder for the logged on user regardless of OS
checks that the user input file is contained in a master list (held by StrFiles)
then either creates a new file if it doesn't exist, or
provides a logic branch for you to add your overrwrite script
Sub
code
GetFiles()
Dim wsShell As Object
Dim objFSO As Object
Dim objFil As Object
Dim strFolder As String
Dim StrFile As String
Dim StrFiles()
StrFiles = Array("A.txt", "B.txt", "C.txt")
Set wsShell = CreateObject("wscript.shell")
strFolder = wsShell.specialFolders("Desktop") & "\myFolder"
StrFile = Application.InputBox("Please enter A.txt, B.txt", "File Selection", , , , , 2)
If IsError(Application.Match(StrFile, StrFiles, 0)) Then
MsgBox StrFile & " is invalid", vbCritical
Exit Sub
End If
If Len(Dir(strFolder & "\" & StrFile)) = 0 Then
'make file
Set objFSO = CreateObject("scripting.filesystemobject")
Set objFil = objFSO.createtextfile(strFolder & "\" & StrFile, 2)
objFil.Close
Else
'write over file
'add your code here
End If
End Sub

VBA/Excel - find path for saving a file, but only match a certain part of the path

I'd like to save a file in the following example folder:
C:\MainFolder\Subfolder1\Subfolder2\Subfolder3_A_abc_123
There are other subfolders in the folder where I'd like the file be saved, like:
Subfolder_B_xyz_456
Subfolder_C_rst_789
etc
The thing is that I want to find a folder on the the path all the way up to: "Subfolder3_", the "A" will be fetched from a range in a sheet and the "_abc_123", I do not want to match.
Does anyone have a clever FSO example or other creative sollution? I'm new to programming so any suggestion is appreciated.
Thanks on advance.
PythonStyle
Updated question to ho1:
This is the code:
Sub Create_WorkB_Input()
Dim wbBook1 As Workbook
Dim wbBook2 As Workbook
Dim shTemp1 As Worksheet
Dim shTemp2 As Worksheet
Dim shTemp_admin As Worksheet
Dim shTSSR_inp1 As Worksheet
Dim shTSSR_inp2 As Worksheet
Dim strVersion As String
Dim strPrep As String
Dim Datecr As Date
Dim strComment As String
Dim intBatch As Integer
Dim strSiteID As String
Dim strClusterID As String
Dim strPath As String
Dim fso As New FileSystemObject
Dim flds As Folders
Dim f As Folder
Set wbBook1 = Workbooks("Name_Input_TEMPLATE_v4.0.xls")
Set wbBook2 = Workbooks("Name_Input_To_xxx.xlsm")
Set shTemp1 = Workbooks("Name_Input_TEMPLATE_v4.0.xls").Sheets("TSSR_Input_sh1")
Set shTemp2 = Workbooks("Name_Input_TEMPLATE_v4.0.xls").Sheets("TSSR_Input_sh2")
Set shTSSR_inp1 = Workbooks("Name_Input_To_xxx.xlsm").Sheets("xxx")
Set shTSSR_inp2 = Workbooks("Name_Input_To_xxx.xlsm").Sheets("yyy")
Set shTemp_admin = Workbooks("Name_Input_TEMPLATE_v4.0.xls").Sheets("www")
shTSSR_inp1.UsedRange.Copy
shTemp1.Paste
shTSSR_inp2.UsedRange.Copy
shTemp2.Paste
intBatch = shTemp1.Range("AQ2").Value
strSiteID = shTemp1.Range("A2").Value
strClusterID = shTemp1.Range("B2").Value
strComment = InputBox(Prompt:="Insert comments.", Title:="INSERT COMMENTS", Default:="New site - batch " & intBatch & " ref email fr Me dato")
With shTemp_admin
.Range("A18").FormulaR1C1 = "4.0"
.Range("B18").Value = "John Doe"
.Range("C18").Value = Date
.Range("D18").Value = strComment
End With
strPath = "D:\Path_to_folder\folder1\folder2\folder3\folder4"
Set flds = fso.GetFolder(strPath & "\Folder5_Input_Batch_" & intBatch & "*")
For Each f In flds
If f.Name Like strPath Then
wbBook1.SaveAs Filename:="" + strPath + "\" + "TSSR_Input_" + strClusterID + "_" + strSiteID + "_v4.0.xls", _
FileFormat:=xlNormal, _
Password:="", _
WriteResPassword:="", _
ReadOnlyRecommended:=False, _
CreateBackup:=False
End If
Next
End Sub
I am getting error at this line :
Set flds = fso.GetFolder(strPath & "\Folder5_Input_Batch_" & intBatch & "*")
Could you please have a look at it?
The names of folders and workbooks are changed so they might not make any sense. Only the folder part is important.
Thanks in advance.
Rgds
P
You could just loop through all the subdirectories and for each directory you compare it with the path you want to find. Something like this pseudo code should work:
For each dir in SubDirectories
Dim lookingFor as String
lookingFor = "Subfolder3_" & yourVariable & "*"
If dir.Name Like lookingFor Then ' Note the use of the Like operator here so that it sees the * as a wildcard
' This is the right one
End If
Next
An other, similar, option would be to use regular expressions which are more powerful than Like, but I don't think you'd need that. However, just in case, you can find information about it here: How to Use Regular Expressions in Visual Basic
Nothing wrong with the posted solution. I just thought I would also post another alternative using the Dir() function, which should be a little faster - especially if you have a lot of subdirectories to search.
i.e.
Dim strFoundDir as String
strFoundDir=dir("C:\MainFolder\Subfolder1\Subfolder2\SubFolder3*" & SomeVariable & "*", vbDirectory)
if lenb(strFoundDir)>0 then
'Do the rest of your code
end if

Resources