Prompt Folder Open via VBA - excel

I am new to VBA and dont have that much knowledge about coding, Need kind support to open the folder via dialog box instead of giving the source folder path manually in the VBA code (Const FolderA = "Folder Path"). Code works fine with inputting manual path inside the vba code(code copied)
Public Sub MoveFiles()
Const colA = 1
Const colB = 2
Const colC = 3
Const FolderA = "H:\My Drive\Appreciation Certification\Sep 21 2022\QR Code\" ' source folder
Const srcSheet = "Source"
Dim xlS As Excel.Worksheet
Dim xlW As Excel.Workbook
Dim RN As Long ' row number
Dim fName As String
Dim fPath As String
' ready
Set xlW = ActiveWorkbook
Set xlS = xlW.Sheets(srcSheet)
RN = 2
fName = Trim(xlS.Cells(RN, colA).Text)
' run thru ColA until hit a blank
On Error Resume Next ' expect problems if no target Dir
While fName <> ""
' if it hasn't aready been moved
If Trim(xlS.Cells(RN, colC).Text) = "" Then
' got one.
' Get the path. Ensure trailing backslash
fPath = Trim(xlS.Cells(RN, colB).Text)
If Right(fPath, 1) <> "\" Then fPath = fPath & "\"
' if the target already exists, nuke it.
If Dir(fPath & fName) <> "" Then Kill fPath & fName
' move it
FileCopy FolderA & fName, fPath & fName
DoEvents
' report it
If Err.Number <> 0 Then
xlS.Cells(RN, colC).Value = "Failed: Check target Dir"
Err.Clear
Else
xlS.Cells(RN, colC).Value = Now()
End If
End If
' ready for next one
RN = RN + 1
fName = Trim(xlS.Cells(RN, colA).Text)
Wend
MsgBox "All files moved!!"
End Sub

Related

Select Folder Picker VBA stops and does not continue the code

I am trying to select a folder and then assign that path to my file Variant. However, the code stops after the folder is selected and does not go to the next step. What can be wrong? The next step would be 'If selected_folder <> "" Then' but it just stops and debugger goes back to Sub.
Sub sheetCompare2()
Application.ScreenUpdating = False
Dim i As Integer
Dim WS_Count As Integer
Dim mDirs As String
Dim path As String
Dim OutFile As Variant, SrcFile As Variant
Dim file As Variant
Dim wb As Workbook
Dim datevar As Variant
Dim datevar2 As Variant
Dim selected_folder As String
Set wb = ThisWorkbook
WS_Count = ActiveWorkbook.Worksheets.Count
OutFile = ActiveWorkbook.Name
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a Folder"
If Application.FileDialog(msoFileDialogFolderPicker).Show = -1 Then
selected_folder = .SelectedItems(1)
End If
End With
If selected_folder <> "" Then
file = Dir(selected_folder)
End If
While (file <> "")
path = selected_folder + file
Workbooks.Open (path)
SrcFile = ActiveWorkbook.Name
datevar = Right(file, 9)
datevar2 = Left(datevar, 4)
....'and so on
End Sub
Please, try changing this part of the code:
If selected_folder <> "" Then
file = Dir(selected_folder)
End If
While (file <> "")
path = mDirs + file
Workbooks.Open (path)
SrcFile = ActiveWorkbook.Name
datevar = Right(file, 9)
datevar2 = Left(datevar, 4)
'....'and so on
with:
If selected_folder <> "" Then
File = Dir(selected_folder & "\" & "*.xls*")
End If
Do While File <> ""
path = selected_folder & "\" & File
Workbooks.Open (path)
SrcFile = ActiveWorkbook.Name
datevar = Right(File, 9)
datevar2 = left(datevar, 4)
File = Dir
'...
Loop
In order to make Dir return a file name, you must set an extension. At least *.* for iterate between all files. But, wanting to open the files in Excel, it is good to use "*.xls*", as the above code does.
Then, the path of the file to be open should be built as above.
Your code does not show how you redefine File in order to make the loop working. You maybe have File = Dir before the loop end. If not, I added...

Search for a string and move files containing string from source folder to destination folder

I have large number of .csv files in a folder and each file has few separation codes in them. Separation code usually will be 5 digit code eg: B82A6.
I have to copy files with a certain separation code and move them to a destination folder.
I am new to VBA. I've been searching for code to modify it to my use.
Sub Test()
Dim R As Range, r1 As Range
Dim SourcePath As String, DestPath As String, SeperationCode As String
SourcePath = "C:\Users\hr315e\Downloads\Nov_03_2019\"
DestPath = "C:\Users\hr315e\Downloads\Target\"
Set r1 = Range("A1", Range("A" & Rows.Count).End(xlUp))
For Each R In r1
SeperationCode = Dir(SourcePath & R)
Do While SeperationCode <> ""
If Application.CountIf(r1, SeperationCode) Then
FileCopy SourcePath & SeperationCode, DestPath & SeperationCode
R.Offset(0, 1).Value = SeperationCode
Else
MsgBox "Bad file: " & SeperationCode & " ==>" & SeperationCode & "<== "
End If
SeperationCode = Dir(SourcePath & "B82A6" & R.Value & "B82A6")
Loop
Next
End Sub
So, here's the code that should work for you.
As you can see, this is a version of code which I linked to you with small updates:
Sub GoThroughFilesAndCopy()
Dim BrowseFolder As String, DestinationFolder As String
Dim FileItem As Object
Dim oFolder As Object
Dim FSO As Object
Dim TempFileName As String
Dim CheckCode As String
Application.ScreenUpdating = False
' selecting the folder with files
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select the folder with files"
.Show
On Error Resume Next
Err.Clear
BrowseFolder = .SelectedItems(1)
If Err.Number <> 0 Then
MsgBox "You didn't select anything!"
Application.ScreenUpdating = True
Exit Sub
End If
On Error GoTo 0
End With
' or you may hardcode it (data from your post):
'BrowseFolder = "C:\Users\hr315e\Downloads\Nov_03_2019\"
' selecting the destination folder
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select the the destination folder"
.Show
On Error Resume Next
Err.Clear
DestinationFolder = .SelectedItems(1)
If Err.Number <> 0 Then
MsgBox "You didn't select anything!"
Application.ScreenUpdating = True
Exit Sub
End If
On Error GoTo 0
End With
' or you may hardcode it (data from your post):
'DestinationFolder = "C:\Users\hr315e\Downloads\Target\"
CheckCode = "Some string" ' this is you check code
Set FSO = CreateObject("Scripting.FileSystemObject") ' creating filesystem object
Set oFolder = FSO.getfolder(BrowseFolder) ' creating folder object
For Each FileItem In oFolder.Files 'looking through each file in selected forlder
TempFileName = ""
If UCase(FileItem.Name) Like "*.CSV*" Then 'try opening only .csv files
TempFileName = BrowseFolder & Application.PathSeparator & FileItem.Name ' getting the full name of the file (with full path)
If CheckTheFile(TempFileName, CheckCode) Then ' if the file passes the checking function
If Dir(DestinationFolder & Application.PathSeparator & FileItem.Name) = "" Then 'if the file doesn't exist in destination folder
FileCopy Source:=TempFileName, Destination:=DestinationFolder & Application.PathSeparator & FileItem.Name ' it is copied to destination
Else ' otherwise, there are to options how to deal with it further
'uncomment the part you need below:
' this will Overwrite existing file
'FSO.CopyFile Source:=TempFileName, Destination:=DestinationFolder & Application.PathSeparator & FileItem.Name
' this will get new name for file and save it as copy
'FileCopy Source:=TempFileName, Destination:=GetNewDestinationName(FileItem.Name, DestinationFolder)
End If
End If
End If
Next
Application.ScreenUpdating = True
End Sub
'////////////////////////////////////////////////////////////////////////
Function CheckTheFile(File As String, Check As String) As Boolean
Dim TestLine As String
Dim TestCondition As String
TestCondition = "*" & Check & "*" ' this is needed to look for specific text in the file, refer to Like operator fro details
CheckTheFile = False
Open File For Input As #1 ' open file to read it line by line
Do While Not EOF(1)
Line Input #1, TestLine ' put each line of the text to variable to be able to check it
If TestLine Like TestCondition Then ' if the line meets the condition
CheckTheFile = True ' then function gets True value, no need to check other lines as main condition is met
Close #1 ' don't forget to close the file, beacuse it will be still opened in background
Exit Function ' exit the loop and function
End If
Loop
Close #1 ' if condiotion is not found in file just close the file, beacuse it will be still opened in background
End Function
'////////////////////////////////////////////////////////////////////////
Function GetNewDestinationName(File As String, Destination As String) As String
Dim i As Integer: i = 1
Do Until Dir(Destination & Application.PathSeparator & "Copy (" & i & ") " & File) = "" ' if Dir(FilePath) returns "" (empty string) it means that the file does not exists, so can save new file with this name
i = i + 1 ' incrementing counter untill get a unique name
Loop
GetNewDestinationName = Destination & Application.PathSeparator & "Copy (" & i & ") " & File ' return new file name
End Function
Basically, there is one sub, which is mostly copy-paste from linked topic, and two simple functions.

Rename specific sheet from specific folder sub folders

I have several excel files in folder & want to rename only specific sheets of every file in the folder which contains
viz. GTLB, SALARY, GROC
Every file has a single sheet of above characters, other sheets have different names.
So, if sheet name contains above characters then change it to GROCERY.
thanks in advance
Try using this it will loop through the folder try finding files (excel files) and try looking for the strings in files that have been specified and if match found change the name.
Sub LoopThroughFiles()
'loops through all files in a folder
Dim MyObj As Object, MySource As Object, file As Variant
Dim wbk As Workbook
Dim path As String
Dim st As String
file = Dir("H:\TestCopy\testing\") 'file name
path = "H:\TestCopy\testing\" 'directory path
While (file <> "")
Set wbk = Workbooks.Open("H:\TestCopy\testing\" & file)
MsgBox "found " & file
' path = path & file 'path and filename
Call newloopTrhoughBooks
wbk.Save
wbk.Close
' Call loop_through_all_worksheets(path)
file = Dir
Wend
End Sub
Sub newloopTrhoughBooks()
Dim book As Workbook, sheet As Worksheet, text As String, text1 As String
Dim logic_string As String
Dim logic_string2 As String
Dim logic_string3 As String
logic_string = "GTLB"
logic_string2 = "SALARY"
logic_string3 = "GROC"
For Each book In Workbooks
text = text & "Workbook: " & book.Name & vbNewLine & "Worksheets: " & vbNewLine
For Each sheet In book.Worksheets
text = text & sheet.Name & vbNewLine
text1 = sheet.Name
If StrComp(logic_string, text1) = 1 Or StrComp(logic_string2, text1) = 1 Or StrComp(logic_string3, text1) = 1 Then 'compare file name
ActiveSheet.Name = text1
ActiveSheet.Name = "Change1"
End If
Next sheet
text = text & vbNewLine
Next book
MsgBox text
End Sub
Sub RenameSheets()
Dim MyFolder As String
Dim MyFile As String
Dim wbname As String
MyFolder = "E:\SSS\File Name"
MyFile = Dir(MyFolder & "\*.xls")
Application.ScreenUpdating = False
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
With ActiveWorkbook
wbname = "GROCERY"
'For giving filename to sheet1
'Left(.Name, InStr(.Name, ".") - 1)
For Each sheet In ActiveWorkbook.Sheets
If LCase(sheet.Name) Like "*salary*" Or LCase(sheet.Name) Like "*gtlb*" Or LCase(sheet.Name) Like "*groc*" Then
MsgBox "Found! " & sheet.Name
.Sheets(sheet.Name).Name = wbname
.Close savechanges:=True
End If
Next
'.Sheets(1).Name = wbname
'.Close savechanges:=True
End With
MyFile = Dir
Loop
Application.ScreenUpdating = True
End Sub

VBA copying all the Excel files in a folder to a single file causes runtime error

I am attempting to use VBA to open all the excel files in a directory (in this case c:\temp) and put all the files datasheets in one large file. Each new sheet is named with the filename plus the name of the sheet on the original document. The code that I have copies the first file's first sheet and even names it correctly, but then fails with a Run-time error 1004: Application defined or object defined error on the second sheet when I try to set the name. Anyone have any suggestions on how to fix.
Sub MergeAllWorkbooks()
Dim FolderPath As String
Dim FileName As String
' Create a new workbook
Set FileWorkbook = Workbooks.Add(xlWBATWorksheet)
' folder path to the files you want to use.
FolderPath = "C:\Temp\"
' 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
Set WorkBk = Workbooks.Open(FolderPath & FileName)
Dim currentSheet As Worksheet
Dim sheetIndex As Integer
sheetIndex = 1
Windows(WorkBk.Name).Activate
For Each currentSheet In WorkBk.Worksheets
currentSheet.Select
currentSheet.Copy Before:=Workbooks(FileWorkbook.Name).Sheets(sheetIndex)
FileWorkbook.Sheets(sheetIndex).Name = FileName & "-" & currentSheet.Name
sheetIndex = sheetIndex + 1
Next currentSheet
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Use Dir to get the next file name.
FileName = Dir()
Loop
End Sub
Replace
FileWorkbook.Sheets(sheetIndex).Name = FileName & "-" & currentSheet.Name
with (I separated it out for readability)
sWSName = FileName & "-" & currentSheet.Name
sWSName = NameTest(sWSName)
sWSName = TestDup(sWSName)
FileWorkbook.Sheets(sheetIndex).Name = sWSName
You will need to define the sWSName.
Below are the modified functions I have previously used.
Function NameTest(sName As String) As String
NameTest = sName
aSpecChars = Array("\", "/", "*", "[", "]", ":", "?")
For Each c In aSpecChars
NameTest = Replace(NameTest, c, "")
Next c
If Len(sName) > 31 Then NameTest = Left(sName, 31)
End Function
Function TestDup(sWSName As String) As String
TestDup = sWSName
For Each ws In Worksheets
Debug.Print ws.Name
If sWSName = ws.Name Then TestDup = TestDup(Left(sWSName, Len(sWSName) - 1))
Next ws
End Function
If posting this code (or to this extent) is out of line please let me know as I am still coming to terms with the level of effort require versus reasonable response.

Change from absolute to relative workbook reference in Excel VBA

I have written an Excel VBA macro that compiles all the information from various spreadsheets that are located in a specific folder and compiles them into one 'Master' Excel workbook.
This currently works fine when using it on my computer, but I would like to adjust the code so that I can place the 'Master' spreadsheet and the folder containing the individual spreadsheet (the ones to be compiled) on a network drive, so that anyone can use it.
I am fairly new to VBA and coding in general so I have a strong feeling there is probably an easy solution to fix my issue.
I have attached my current macro that runs the absolute reference.
'Summary: Open all Excel files in a specific folder and merge data
' into one master sheet (stacked)
Dim fName As String, fPath As String, fPathDone As String, OldDir As String
Dim LR As Long, NR As Long
Dim wbData As Workbook, wbkNew As Workbook
'Setup
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Set wbkNew = ThisWorkbook
wbkNew.Activate
Sheets("Master").Activate
If MsgBox("Import new data to this report?", vbYesNo) = vbNo Then Exit Sub
If MsgBox("Clear the old data first?", vbYesNo) = vbYes Then
Cells.Clear
NR = 1
Else
NR = Range("A" & Rows.Count).End(xlUp).Row + 1
End If
fPath = "C:\Folder-that-Excel-workbooks-are-located-in"
On Error Resume Next
MkDir fPathDone
On Error GoTo 0
OldDir = CurDir
ChDir fPath
fName = Dir("*.xlsx")
Do While Len(fName) > 0
If fName <> wbkNew.Name Then
Set wbData = Workbooks.Open(fName)
LR = Range("C" & Rows.Count).End(xlUp).Row
If NR = 1 Then
Range("C5:F" & LR).EntireRow.Copy _
wbkNew.Sheets("Master").Range("A" & NR)
Else
Range("C5:F" & LR).EntireRow.Copy _
wbkNew.Sheets("Master").Range("A" & NR)
End If
wbData.Close False
NR = Range("C" & Rows.Count).End(xlUp).Row + 1
fName = Dir
End If
Loop
ErrorExit:
ActiveSheet.Columns.AutoFit
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
ChDir OldDir
One quick and dirty solution would be putting the path to the workbook folder somewhere into the master workbook.
Put the other workbooks on a network share that is available to all computers you are sharing your excel sheet with. Use a UNC path like this:
\\ComputerName\SharedFolder\Resource
You can then set fPath in your code to the cells value.
A better way would be putting the path into a settings file in the same folder as the master workbook and reading the path when running the macro:
Dim tmpArray() As String
Dim s As String
Dim strPath as String
Open ThisWorkbook.Path & "\settings.ini" For Input As #1
Do While Not EOF(1)
Line Input #1, s
If VBA.Left(s, 11) = "excelfolder" Then
tmpArray = Split(s, "=")
strPath = tmpArray(1)
End If
Loop
Close #1
Your ini file would look like this:
excelfolder=\\ComputerName\SharedFolder\Resource

Resources