Finding Duplicates & Putting them in Master Folder - excel

My code renames folders based on what is in first column:
Dim sFolder As String
Option Explicit
Sub addPrefix()
Dim strfile As String
Dim filenum As String
Dim strOldDirName
Dim strNewDirName
strfile = Dir(sFolder)
Dim old_name, new_name As String
Dim i As Long
With ThisWorkbook.Worksheets("data")
For i = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
strOldDirName = sFolder & ThisWorkbook.Worksheets("data").Cells(i, 2).Value
strNewDirName = sFolder & ThisWorkbook.Worksheets("data").Cells(i, 1).Value & " " & ThisWorkbook.Worksheets("data").Cells(i, 2).Value
Name strOldDirName As strNewDirName
Next i
End With
End Sub
and then I check for duplicates on Column C (email column). If they are a duplicate I move them to their 'master' folder (which is just the first of the duplicates found). Upon this, it adds the suffix ' - MASTER' on to the folder.
Here is the code to move duplicates:
Sub moveDuplicates()
' This will find duplicates and move them into a master folder. It'll will then delete the row
Dim masterID
Dim masterPlatform
Dim objFileSystem
Dim FromPath As String
Dim ToPath As String
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Dim masterOldFolderName
Dim masterNewFolderName
Dim masterSuffix
Dim LastRow As Long, i As Long
Dim rngWhole As Range, rngSplit As Range
masterID = 0
masterPlatform = 0
masterSuffix = " - MASTER"
masterOldFolderName = ""
masterNewFolderName = ""
With ThisWorkbook.Worksheets("data")
LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
Set rngWhole = .Range("C1:C" & LastRow)
.Range("E" & 1).Value = rngWhole
For i = 1 To LastRow
If WorksheetFunction.CountIf(rngWhole, .Range("C" & i).Value) > 1 Then
Set rngSplit = .Range("C1:C" & i)
If WorksheetFunction.CountIf(rngSplit, .Range("C" & i).Value) = 1 Then
masterID = .Range("B" & i).Value
masterPlatform = .Range("A" & i).Value
'' Renme master folders with subfix of "- MASTER"
masterOldFolderName = sFolder & masterPlatform & " " & masterID
masterNewFolderName = sFolder & masterPlatform & " " & masterID & masterSuffix
Name masterOldFolderName As masterNewFolderName
'' End of renaming
'.Range("D" & i).Value = "MASTER " & masterID
Else
'.Range("D" & i).Value = "CHILD " & masterID & " This folder: " & .Range("B" & i).Value
'MOVING FOLDER
FromPath = sFolder & .Range("A" & i).Value & " " & .Range("B" & i).Value '<< Change
ToPath = sFolder & masterPlatform & " " & masterID & masterSuffix & "\" '<< needs the slash to go into the folder
.Range("H" & i).Value = "From: " & FromPath
.Range("I" & i).Value = "From: " & ToPath
'Check if source and target folder exists
If objFileSystem.FolderExists(FromPath) = True And objFileSystem.FolderExists(ToPath) = True Then
objFileSystem.MoveFolder Source:=FromPath, Destination:=ToPath
lblStatus.Caption = "Moving " & FromPath & " To " & ToPath
Rows(i).EntireRow.Delete
lblStatus.Caption = " Deleting " & .Range("A" & i).Value & " " & .Range("B" & i).Value
'MsgBox "Source folder has moved to target folder"
Else
'MsgBox "Either source or target folder does not exist"
End If
' END OF MOVING FOLDER
' ROW GETS DELETED
End If
'.Range("C" & i).Interior.ColorIndex = 3
End If
Next i
End With
End Sub
My script works to a certain degree:
But it just puts everything into the first 'MASTER' folder
Here is my sheet:
I then call this from a button:
' Open the select folder prompt
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then ' if OK is pressed
sFolder = .SelectedItems(1) & "\"
End If
End With
If sFolder <> "" Then ' if a file was chosen
Me.txtFolderPath.Text = sFolder
'' calls functions
addPrefix
moveDuplicates
Sheet_SaveAs ' saves output
end sub
Is the reason it is not performing as expected due to I am calling it wrongly?
Full code: https://www.dropbox.com/s/k06b5hydc4v7bpn/so-files.zip?dl=0
(code can be run from developer> forms> userform1)
DEBUGGING:
I think the problem seems to arise here when debugging:
'' Renme master folders with subfix of "- MASTER"
masterOldFolderName = sFolder & masterPlatform & " " & masterID
masterNewFolderName = sFolder & masterPlatform & " " & masterID & masterSuffix
Name masterOldFolderName As masterNewFolderName
'' End of renaming
I am not sure if this is because it is in the wrong place (which I assume)

Related

Macro that export complete row data based on column name to new excel file getting error in that

Sub ExportCreatePOD()
'File names to be created as " & " " & "-" & " " & "POL" & " " & "-" & " " & Format(Now()," MM-DD-YYYY ")"
Dim RngSourceData As Range
Dim RngTarget As Range
Dim RngRange01 As Range
Dim RngRange02 As Range
Dim StrCarrierColumnHeader As String
Dim StrSavePath As String
Dim StrMultipleFileMessage As String
Dim DblCarrierColumnRelativeColumn As Double
Dim DblCounter01 As Double
Dim DblCounter02 As Double
Dim WkbSource As Workbook
Dim WkbTarget As Workbook
'Turning off screen updating.
Application.ScreenUpdating = False
'Setting variables.
Set WkbSource = ActiveWorkbook
Set RngSourceData = WkbSource.Sheets("POD").UsedRange
StrCarrierColumnHeader = "Carrier"
StrSavePath = "C:Path\" '=== Path for POD files Change the Path (where you want to export the POD files)
On Error Resume Next
DblCarrierColumnRelativeColumn = Excel.WorksheetFunction.Match(StrCarrierColumnHeader, RngSourceData.Rows(1), 0)
If Err <> 0 Then
MsgBox "The range " & RngSourceData.Rows(1).Address(False, False) & " contains no column headed " & StrCarrierColumnHeader & ". The subroutine is terminated", vbCritical, "Error"
Application.ScreenUpdating = True
Exit Sub
End If
On Error GoTo 0
Set RngRange01 = RngSourceData.Columns(DblCarrierColumnRelativeColumn).Resize(RngSourceData.Rows.Count - 1).Offset(1, 0)
DblCounter01 = 0
For Each RngTarget In RngRange01.Cells
If Excel.WorksheetFunction.CountIf(RngSourceData.Parent.Range(RngRange01.Cells(1, 1), RngTarget), RngTarget.Value) = 1 Then
'Cheking if any file dedicated to the given carrier already exists for today.
If Dir(StrSavePath & RngTarget.Value & " " & "-" & " " & "POD" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & ".xlsx") = "" Then
'If no such file exists, it is created and saved.
Set WkbTarget = Workbooks.Add
WkbTarget.SaveAs StrSavePath & RngTarget.Value & " " & "-" & " " & "POD" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & ".xlsx"
Else
'Is it does exist, the name is "shifted".
DblCounter02 = 2
Do Until Dir(StrSavePath & RngTarget.Value & " " & "-" & " " & "POD" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & "(" & DblCounter02 & ")" & ".xlsx") = ""
DblCounter02 = DblCounter02 + 1
Loop
'Carrier and relative file are copied in StrMultipleFileMessage.
StrMultipleFileMessage = StrMultipleFileMessage & vbCrLf & RngTarget.Value & " in " & RngTarget.Value & " " & "-" & " " & "POD" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & "(" & DblCounter02 & ")" & ".xlsx"
Set WkbTarget = Workbooks.Add
WkbTarget.SaveAs StrSavePath & RngTarget.Value & " " & "-" & " " & "POD" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & "(" & DblCounter02 & ")" & ".xlsx"
End If
'Setting RngRange02 to target the range in the new file where RngSourceData will be copied.
Set RngRange02 = WkbTarget.Sheets(1).Range("A1").Resize(RngSourceData.Rows.Count, RngSourceData.Columns.Count)
With RngRange02
'Copying values.
RngSourceData.Copy RngRange02
'Filtering the range to clear the list of unwanted data.
.AutoFilter Field:=DblCarrierColumnRelativeColumn, Criteria1:="<>" & RngTarget.Value
.Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).ClearContents
.Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).ClearFormats
'Removing the filter.
.AutoFilter
'Rename Sheet
Sheets("Sheet1").Name = "POD"
'Autofit
Sheets("POD").UsedRange.Columns.AutoFit
'Sorting the range to compact the data.
With .Parent.Sort
.SortFields.Clear
.SortFields.Add Key:=RngRange02.Columns(DblCarrierColumnRelativeColumn), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
.SetRange RngRange02
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
'Saving and closing WkbTarget.
WkbTarget.Close SaveChanges:=True
End If
'Setting DblCounter01.
DblCounter01 = DblCounter01 + 1
Next
'Enabling screen updating.
Application.ScreenUpdating = True
'Reporting if any carrier had its data reported in a "twin" file.
If StrMultipleFileMessage <> "" Then
StrMultipleFileMessage = "The following carriers had already one or more dedicated files at the given path. Their data were saved accordingly to this list:" & vbCrLf & vbCrLf & StrMultipleFileMessage
MsgBox StrMultipleFileMessage, , "Multiple dedicated files"
End If
End Sub
I created a macro that split data based on column name "Carrier" into a new excel file. I have 2 tabs named POL and POD for which I created 2 sets of codes that split data from these tabs based on the column name and created a new excel file, my code for tab POL is working but not for POD. I neither get any error it just executes and create a file but does not paste any data of the POD tab.
Main Excel File which has Macro codes Problem in Tab POD
In this above screen, you can see the POD tab has so much data that macro should create a new file based on column name "Carrier". When I execute the macro it create a new file but there is no data in it meaning the data does not get captured in the newly created POD file. I am pasting the output as follows.
Wrong Output
If you see in the above image no data is captured in the newly created file.
I will paste my complete code below the codes for both the tabs POL and POD. Please guide is there any easy way to cut short the codes that read both POL and POD tabs and create/splits the data into a new excel file based on the column named carrier. However, at present, the problem is with the codes within "
Sub ExportCreatePOD()"
My Complete Codes :-
'--------------------------------Create POL POD XL Sheets---------------------------
Sub ExportCreatePOL()
'File names to be created as " & " " & "-" & " " & "POL" & " " & "-" & " " & Format(Now()," MM-DD-YYYY ")"
Dim RngSourceData As Range
Dim RngTarget As Range
Dim RngRange01 As Range
Dim RngRange02 As Range
Dim StrCarrierColumnHeader As String
Dim StrSavePath As String
Dim StrMultipleFileMessage As String
Dim DblCarrierColumnRelativeColumn As Double
Dim DblCounter01 As Double
Dim DblCounter02 As Double
Dim WkbSource As Workbook
Dim WkbTarget As Workbook
Application.ScreenUpdating = False
Set WkbSource = ActiveWorkbook
Set RngSourceData = WkbSource.Sheets("POL").UsedRange
StrCarrierColumnHeader = "Carrier"
StrSavePath = "C:Path\" '===Path where excel files will be created Change the Path (where you want to export the POL files)
'Setting DblCarrierColumnRelativeColumn to determine what column within RngSourceData _
contains the StrCarrierColumnHeader. If no such column is found, the subroutine is terminated.
On Error Resume Next
DblCarrierColumnRelativeColumn = Excel.WorksheetFunction.Match(StrCarrierColumnHeader, RngSourceData.Rows(1), 0)
If Err <> 0 Then
MsgBox "The range " & RngSourceData.Rows(1).Address(False, False) & " contains no column headed " & StrCarrierColumnHeader & ". The subroutine is terminated", vbCritical, "Error"
Application.ScreenUpdating = True
Exit Sub
End If
On Error GoTo 0
Set RngRange01 = RngSourceData.Columns(DblCarrierColumnRelativeColumn).Resize(RngSourceData.Rows.Count - 1).Offset(1, 0)
DblCounter01 = 0
For Each RngTarget In RngRange01.Cells
If Excel.WorksheetFunction.CountIf(RngSourceData.Parent.Range(RngRange01.Cells(1, 1), RngTarget), RngTarget.Value) = 1 Then
If Dir(StrSavePath & RngTarget.Value & " " & "-" & " " & "POL" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & ".xlsx") = "" Then
Set WkbTarget = Workbooks.Add
WkbTarget.SaveAs StrSavePath & RngTarget.Value & " " & "-" & " " & "POL" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & ".xlsx"
Else
'Is it does exist, the name is "shifted".
DblCounter02 = 2
Do Until Dir(StrSavePath & RngTarget.Value & " " & "-" & " " & "POL" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & "(" & DblCounter02 & ")" & ".xlsx") = ""
DblCounter02 = DblCounter02 + 1
Loop
'Carrier and relative file are copied in StrMultipleFileMessage.
StrMultipleFileMessage = StrMultipleFileMessage & vbCrLf & RngTarget.Value & " in " & RngTarget.Value & " " & "-" & " " & "POL" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & "(" & DblCounter02 & ")" & ".xlsx"
Set WkbTarget = Workbooks.Add
WkbTarget.SaveAs StrSavePath & RngTarget.Value & " " & "-" & " " & "POL" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & "(" & DblCounter02 & ")" & ".xlsx"
End If
'Setting RngRange02 to target the range in the new file where RngSourceData will be copied.
Set RngRange02 = WkbTarget.Sheets(1).Range("A1").Resize(RngSourceData.Rows.Count, RngSourceData.Columns.Count)
With RngRange02
'Copying values.
RngSourceData.Copy RngRange02
'Filtering the range to clear the list of unwanted data.
.AutoFilter Field:=DblCarrierColumnRelativeColumn, Criteria1:="<>" & RngTarget.Value
.Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).ClearContents
.Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).ClearFormats
'Removing the filter.
.AutoFilter
'Rename sheet1
Sheets("Sheet1").Name = "POL"
'Autofit
Sheets("POL").UsedRange.Columns.AutoFit
'Sorting the range to compact the data.
With .Parent.Sort
.SortFields.Clear
.SortFields.Add Key:=RngRange02.Columns(DblCarrierColumnRelativeColumn), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
.SetRange RngRange02
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
'Saving and closing WkbTarget.
WkbTarget.Close SaveChanges:=True
End If
'Setting DblCounter01.
DblCounter01 = DblCounter01 + 1
Next
'Enabling screen updating.
Application.ScreenUpdating = True
'Reporting if any carrier had its data reported in a "twin" file.
If StrMultipleFileMessage <> "" Then
StrMultipleFileMessage = "The following carriers had already one or more dedicated files at the given path. Their data were saved accordingly to this list:" & vbCrLf & vbCrLf & StrMultipleFileMessage
MsgBox StrMultipleFileMessage, , "Multiple dedicated files"
End If
End Sub
Sub ExportCreatePOD()
'File names to be created as " & " " & "-" & " " & "POL" & " " & "-" & " " & Format(Now()," MM-DD-YYYY ")"
Dim RngSourceData As Range
Dim RngTarget As Range
Dim RngRange01 As Range
Dim RngRange02 As Range
Dim StrCarrierColumnHeader As String
Dim StrSavePath As String
Dim StrMultipleFileMessage As String
Dim DblCarrierColumnRelativeColumn As Double
Dim DblCounter01 As Double
Dim DblCounter02 As Double
Dim WkbSource As Workbook
Dim WkbTarget As Workbook
'Turning off screen updating.
Application.ScreenUpdating = False
'Setting variables.
Set WkbSource = ActiveWorkbook
Set RngSourceData = WkbSource.Sheets("POD").UsedRange
StrCarrierColumnHeader = "Carrier"
StrSavePath = "C:Path\" '=== Path for POD files Change the Path (where you want to export the POD files)
On Error Resume Next
DblCarrierColumnRelativeColumn = Excel.WorksheetFunction.Match(StrCarrierColumnHeader, RngSourceData.Rows(1), 0)
If Err <> 0 Then
MsgBox "The range " & RngSourceData.Rows(1).Address(False, False) & " contains no column headed " & StrCarrierColumnHeader & ". The subroutine is terminated", vbCritical, "Error"
Application.ScreenUpdating = True
Exit Sub
End If
On Error GoTo 0
Set RngRange01 = RngSourceData.Columns(DblCarrierColumnRelativeColumn).Resize(RngSourceData.Rows.Count - 1).Offset(1, 0)
DblCounter01 = 0
For Each RngTarget In RngRange01.Cells
If Excel.WorksheetFunction.CountIf(RngSourceData.Parent.Range(RngRange01.Cells(1, 1), RngTarget), RngTarget.Value) = 1 Then
'Cheking if any file dedicated to the given carrier already exists for today.
If Dir(StrSavePath & RngTarget.Value & " " & "-" & " " & "POD" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & ".xlsx") = "" Then
'If no such file exists, it is created and saved.
Set WkbTarget = Workbooks.Add
WkbTarget.SaveAs StrSavePath & RngTarget.Value & " " & "-" & " " & "POD" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & ".xlsx"
Else
'Is it does exist, the name is "shifted".
DblCounter02 = 2
Do Until Dir(StrSavePath & RngTarget.Value & " " & "-" & " " & "POD" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & "(" & DblCounter02 & ")" & ".xlsx") = ""
DblCounter02 = DblCounter02 + 1
Loop
'Carrier and relative file are copied in StrMultipleFileMessage.
StrMultipleFileMessage = StrMultipleFileMessage & vbCrLf & RngTarget.Value & " in " & RngTarget.Value & " " & "-" & " " & "POD" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & "(" & DblCounter02 & ")" & ".xlsx"
Set WkbTarget = Workbooks.Add
WkbTarget.SaveAs StrSavePath & RngTarget.Value & " " & "-" & " " & "POD" & " " & "-" & " " & Format(Now(), " MM-DD-YYYY ") & "(" & DblCounter02 & ")" & ".xlsx"
End If
'Setting RngRange02 to target the range in the new file where RngSourceData will be copied.
Set RngRange02 = WkbTarget.Sheets(1).Range("A1").Resize(RngSourceData.Rows.Count, RngSourceData.Columns.Count)
With RngRange02
'Copying values.
RngSourceData.Copy RngRange02
'Filtering the range to clear the list of unwanted data.
.AutoFilter Field:=DblCarrierColumnRelativeColumn, Criteria1:="<>" & RngTarget.Value
.Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).ClearContents
.Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).ClearFormats
'Removing the filter.
.AutoFilter
'Rename Sheet
Sheets("Sheet1").Name = "POD"
'Autofit
Sheets("POD").UsedRange.Columns.AutoFit
'Sorting the range to compact the data.
With .Parent.Sort
.SortFields.Clear
.SortFields.Add Key:=RngRange02.Columns(DblCarrierColumnRelativeColumn), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
.SetRange RngRange02
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
'Saving and closing WkbTarget.
WkbTarget.Close SaveChanges:=True
End If
'Setting DblCounter01.
DblCounter01 = DblCounter01 + 1
Next
'Enabling screen updating.
Application.ScreenUpdating = True
'Reporting if any carrier had its data reported in a "twin" file.
If StrMultipleFileMessage <> "" Then
StrMultipleFileMessage = "The following carriers had already one or more dedicated files at the given path. Their data were saved accordingly to this list:" & vbCrLf & vbCrLf & StrMultipleFileMessage
MsgBox StrMultipleFileMessage, , "Multiple dedicated files"
End If
End Sub
Since you are copying all the data, filtering and then deleting unwanted records I suspect the problem is with the data. Try this more direct approach of copying only what you want.
Option Explicit
Sub ExportCreateBoth()
Call ExportCreateFile("POD")
Call ExportCreateFile("POL")
End Sub
Sub ExportCreateFile(ws_name As String)
Const COL_NAME = "Carrier"
Const SAVEPATH = "C:\temp\so\" ' ouput folder
Dim wb As Workbook, wbOut As Workbook
Dim ws As Worksheet, wsOut As Worksheet
Dim rng As Range, r As Long
Dim iCol As Integer, iLastCol As Integer, iLastRow As Long
Dim filename As String, msg As String
Set wb = ActiveWorkbook
Set ws = wb.Sheets(ws_name)
iLastCol = ws.Cells(1, Columns.Count).End(xlToLeft).Column
Set rng = ws.Range("A1").Resize(1, iLastCol).Find(COL_NAME)
If rng Is Nothing Then
msg = "The range " & ws.Rows(1).Address() & " contains no column headed " _
& COL_NAME & ". The subroutine is terminated"
MsgBox msg, vbCritical
Exit Sub
End If
' carrier column
iCol = rng.Column
iLastRow = ws.Cells(Rows.Count, iCol).End(xlUp).Row
Set rng = ws.Range("A1").Resize(iLastRow, iLastCol)
' create list of unique values
Dim dict, key
Set dict = CreateObject("Scripting.Dictionary")
For r = 2 To iLastRow
key = Trim(ws.Cells(r, iCol))
If Len(key) > 0 Then dict(key) = 1
Next
' create workbooks for each carrier
Application.ScreenUpdating = False
For Each key In dict.keys
' create output workbook
filename = GetFileName(SAVEPATH, key, ws_name, msg)
Set wbOut = Workbooks.Add
Set wsOut = wbOut.Sheets(1)
wsOut.Name = ws_name
' copy filtered data
rng.AutoFilter Field:=iCol, Criteria1:=CStr(key)
rng.SpecialCells(xlCellTypeVisible).Copy _
wsOut.Range("A1")
wsOut.UsedRange.Columns.AutoFit
wbOut.SaveAs filename
wbOut.Close False
rng.AutoFilter
Next
Application.ScreenUpdating = True
If Len(msg) > 0 Then
msg = "The following carriers had already one or more " & _
"dedicated files at the given path. " & _
"Their data were saved accordingly to this list:" & msg & vbCrLf
MsgBox msg, vbExclamation, "Multiple dedicated files"
End If
MsgBox dict.Count & " files created for " & ws_name, vbInformation
End Sub
Function GetFileName(folder, carrier, str, ByRef msg) As String
Const EXT = ".xlsx"
Dim mdy As String, filename As String, s As String, n As Integer
mdy = Format(Now(), " MM-DD-YYYY ")
filename = folder & carrier & " - " & str & " - " & mdy
s = filename & EXT
n = 1
Do Until Dir(s) = ""
s = filename & "(" & n & ")" & EXT
n = n + 1
Loop
If n > 1 Then
msg = msg & vbLf & carrier & " in " & s
End If
GetFileName = s
End Function

What is causing my code to have 1004 runtime error

I know this code is a mess but it's been at least working with no errors for weeks. The directories of all the files in question exist.
'''
Sub NEW_PO()
'''''''''''''''''''''''''''''''''''Declare Variables''''''''''''''''''''''''''''''''''''''''''''
Dim disc As String
Dim New_Data_Column As Long 'last date ordered column (number)
Dim NewPO_num As String 'New_Data_Column - 10 (needs leading "0" for single digits)
Dim Job_Num As String '= C2
Dim Cost_Code As String '= Active sheet name
Dim lastCol As String 'last date ordered column (Letter)
Dim sht As Worksheet
Dim lastRow As Long 'last row of description column
Set sht = ActiveSheet
''''''''''''''''''''''Find last row and column(letter)''''''''''''''''''''''''''''''''''''''''''
New_Data_Column = Cells(8, Columns.count).End(xlToLeft).Column
lastCol = Split(Columns(Range("A8").End(xlToRight).Column).Address(, False), ":")(1)
lastRow = sht.Cells(sht.Rows.count, 3).End(xlUp).Row
'''''''''''''''''''''''''''''Check for Data'''''''''''''''''''''''''''''''''''''''''''''''''''''
If WorksheetFunction.CountA(Range(lastCol & "11:" & lastCol & lastRow)) = 0 Then
MsgBox "Error! Please enter data to continue."
Exit Sub
ElseIf WorksheetFunction.CountA(Range(lastCol & "10")) = 0 Then
MsgBox "Error! Please enter date to continue."
Range(lastCol & "10").Select
Exit Sub
Else
''''''''''''''''''''''''''''''''Propmt for description of PO''''''''''''''''''''''''''''''''''''
disc = InputBox("Please enter a description for this Purchase Order.", "New Purchase Order")
If disc = "" Then
MsgBox "You Must Enter A Description!"
Exit Sub
End If
''''''''''''''''''''''''''''''''''Set Cost Code''''''''''''''''''''''''''''''''''''''''''''''''
Cost_Code = sht.name
'''''''''''''''''''''''''''''''''Set Job Number''''''''''''''''''''''''''''''''''''''''''''''''
Job_Num = sht.Cells(2, 4).Text 'as text to keep formatting
'''''''''''''''''''''''''''''Set New Purchase Order Number'''''''''''''''''''''''''''''''''''''
sht.Range("A4").Value = sht.Range("A4").Value + 1
If sht.Range("A4").Value < 10 Then
NewPO_num = "0" & sht.Range("A4").Value
Else
NewPO_num = sht.Range("A4").Value
End If
''''''''''''Open PO Template and save as PO number & Copy PO to S/R Log''''''''''''''''''''
Dim sPath As String
sPath = Application.ThisWorkbook.path
Dim i As Integer
Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim wkb2 As Workbook
Dim sht2 As Worksheet
Dim lastPO_row As Long
Dim lastSR_row As Long
Dim wkb3 As Workbook
Dim sht3 As Worksheet
Dim sht4 As Worksheet
Application.ScreenUpdating = False
Set wkb1 = ThisWorkbook
Set wkb2 = Workbooks.Open(sPath & "\1 CONSTRUCTION\Purchase Orders\Purchase Order Template.xlsm")
Set wkb3 = Workbooks.Open(sPath & "\1 CONSTRUCTION\RECEIVED MATERIALS\SR Log.xlsx")
Set sht1 = wkb1.Sheets(Cost_Code)
Set sht2 = wkb2.Sheets("Sheet1")
Set sht3 = wkb3.Sheets("Sheet1")
Set sht4 = wkb2.Sheets("Job Addresses")
'''
This is where the error is occurring. Normally it would save the template as specified with no problems. I have deleted the code and written it in notepad and pasted it back into excel and it still gives an error. I've tried on multiple computers with the same result. I even uninstalled and reinstalled office and still not working.
'''
wkb2.SaveAs (sPath & "\1 CONSTRUCTION\Purchase Orders\" & Cost_Code & "\" & Job_Num & "-" & NewPO_num
& "-" & Cost_Code & " " & disc & ".xlsm")
wkb3.SaveAs (sPath & "\1 CONSTRUCTION\RECEIVED MATERIALS\" & Cost_Code & "\" & Job_Num & "-" &
NewPO_num & "-" & Cost_Code & " " & disc & ".xlsx")
sht2.name = Job_Num & "-" & NewPO_num & "-" & Cost_Code & " " & disc
lastPO_row = sht2.Cells(sht.Rows.count, 3).End(xlUp).Row + 1
lastSR_row = sht3.Cells(sht.Rows.count, 1).End(xlUp).Row + 1
''''''''''''Copy relevant entries to PO sheet and Shipping/Receiving Log'''''''''''''''''''
For i = 11 To lastRow
If sht1.Cells(i, New_Data_Column).Value <> "" Then
sht1.Range(lastCol & i).Copy
sht2.Range("A" & lastPO_row).PasteSpecial xlPasteValues
sht3.Range("D" & lastSR_row).PasteSpecial xlPasteValues
sht1.Range("B" & i & ":C" & i).Copy
sht2.Range("B" & lastPO_row & ":C" & lastPO_row).PasteSpecial xlPasteValues
sht3.Range("A" & lastSR_row & ":B" & lastSR_row).PasteSpecial xlPasteValues
lastPO_row = lastPO_row + 1
lastSR_row = lastSR_row + 1
End If
Next
sht2.Range("E6").Value = wkb1.Sheets("PM Dashboard").Range("O3").Value
sht2.Range("E7").Value = Job_Num & "-" & NewPO_num & "-" & Cost_Code
sht2.Range("E8").Value = Dashboard.Sheets("PM Dashboard").Range("Y2").Value
'add this job's address to list of addresses on PO
sht4.Range("A7").Value = wkb1.Sheets("PM Dashboard").Range("O3").Value & vbNewLine _
& wkb1.Sheets("PM Dashboard").Range("AP3").Value & vbNewLine & wkb1.Sheets("PM
Dashboard").Range("AP4").Value
wkb2.Save
sht3.Range("C1").Value = Job_Num & "-" & NewPO_num & "-" & Cost_Code & " " & disc
wkb3.Save
wkb3.Close
'''''''''''''''''''''copy over last column and hide previous'''''''''''''''''''''
sht1.Columns(New_Data_Column).Copy
sht1.Columns(New_Data_Column + 1).PasteSpecial Paste:=xlPasteFormats
sht1.Range(lastCol & "8:" & lastCol & "9").Copy
sht1.Range(lastCol & "8:" & lastCol & "9").Offset(0, 1).PasteSpecial Paste:=xlPasteValues
Call HIDE
wkb1.Save
Application.ScreenUpdating = True
End If
End Sub
'''

File path when & "\" - Runtime Error 76 Path not found

The file path doesn't work when:
Path = Sheets("Sheet1").Range("C2").Value & "\"
The file path in C2 doesn't include \ at the end
Sub Make_Folders_And_SubFolders()
Dim GPath, GName, UName, UGroup As String
Dim UserID, Groups, G, U As Range
Dim Gcounter, Ucounter As Integer
GPath = Sheets("Sheet1").Range("C2").Value & "\"
On Error GoTo Finish
If Len(GPath) = 0 Or Right(GPath, 1) <> "\" Then
Finish:
MsgBox "Please, check if:" & vbNewLine _
& "1- Folder Path is empty." & vbNewLine _
& "2- or "" \ "" is missing at the end of the path." & vbNewLine _
& "3- or Path does not exist.", vbCritical
Exit Sub
End If
Set Groups = Sheets("Sheet1").Range(Cells(5, "P"), Cells(Rows.Count, "P").End(xlUp))
Set UserID = Sheets("Sheet1").Range(Cells(5, "Q"), Cells(Rows.Count, "Q").End(xlUp))
For Each G In Groups
GName = Trim(G.Value) & "_Group"
If Len(Dir(GPath & GName, vbDirectory)) > 0 Then
GoTo Nxt1
Else
MkDir GPath & GName
Gcounter = Gcounter + 1
End If
Nxt1:
Next G
For Each U In UserID
UName = Trim(U.Value)
UGroup = Trim(U.Offset(0, 1).Value) & "_Group"
If Len(Dir(GPath & UGroup & "\" & UName, vbDirectory)) > 0 Then
GoTo Nxt2
Else
MkDir GPath & UGroup & "\" & UName
Ucounter = Ucounter + 1
End If
Nxt2:
Next U
If Gcounter + Ucounter = 0 Then
MsgBox "All Folders exist, " & vbNewLine & "No folder to be created"
Else
MsgBox "Job Done !!" & vbNewLine _
& "Group Folders created: = " & Gcounter & vbNewLine _
& "User ID Folders created: = " & Ucounter, _
Title:="Foders Created Count"
End If
End Sub
May I suggest for file operations and path building use a FileSystemObject. It absolutely negates the need to have \ on the end of paths, as it is smart enough to add it when needed. Specifically, the fso.BuildPath() method was designed to suit this exact need.
Public Sub CombinePathTest()
Dim path As String, fn As String
path = fso.GetParentFolderName(Sheets("Sheet1").Range("C2").Value)
fn = fso.BuildPath(path, Uname)
End Sub
From the documentation, you can see there are a lot of helpful functions that take the stress out of building paths, opening files, creating or deleting, or check for existence.
and by defining as a reference, and adding a global fso object you have access to Intellisense while writing code
Try the following. Note that I haven't touched anything from For Each G In Groups to the end.
Sub FileOperation()
Dim GPath As String, GName As String, UName As String, UGroup As String
Dim UserID As Range, Groups As Range, G As Range, U As Range
Dim Gcounter As Long, Ucounter As Long
Dim pSep As String: pSep = Application.PathSeparator
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = wb.Worksheets("Sheet1")
GPath = ws.Range("C2").Value
If Len(GPath) = 0 Then
MsgBox "Path is empty.", vbCritical
Exit Sub
End If
If Right(GPath, 1) <> pSep Then
GPath = GPath & pSep
End If
Set Groups = ws.Range(ws.Cells(5, "P"), ws.Cells(Rows.Count, "P").End(xlUp))
Set UserID = ws.Range(ws.Cells(5, "Q"), ws.Cells(Rows.Count, "Q").End(xlUp))
For Each G In Groups
GName = Trim(G.Value) & "_Group"
If Len(Dir(GPath & GName, vbDirectory)) > 0 Then
GoTo Nxt1
Else
MkDir GPath & GName
Gcounter = Gcounter + 1
End If
Nxt1:
Next G
For Each U In UserID
UName = Trim(U.Value)
UGroup = Trim(U.Offset(0, 1).Value) & "_Group"
If Len(Dir(GPath & UGroup & "\" & UName, vbDirectory)) > 0 Then
GoTo Nxt2
Else
MkDir GPath & UGroup & "\" & UName
Ucounter = Ucounter + 1
End If
Nxt2:
Next U
If Gcounter + Ucounter = 0 Then
MsgBox "All Folders exist, " & vbNewLine & "No folder to be created"
Else
MsgBox "Job Done !!" & vbNewLine _
& "Group Folders created: = " & Gcounter & vbNewLine _
& "User ID Folders created: = " & Ucounter, _
Title:="Foders Created Count"
End If
End Sub

how make folders base on value of rows

firstly i want to write a macro for going through of every row so if valuse of item is more than 10 creat a folder base on values of that rows.in addition without a duplicate folder !
for example if there is item20 then create a folder with this name 20_NT25153_29.9 then another rows
i wanna to add this sentence ,i know my code is very simple but i am new in VBA hence need more help :)
Sub loopthrough()
With Worksheets("Output_" & Date)
fName5 = .Range("d").Value
fName1 = .Range("B").Value
fName2 = .Range("c").Value
fName4 = "_"
BrowseForFolder = CurDir()
End With
For Each cell In ActiveWorkbook.Worksheets
If cell.Range("B").Value > "10" Then
BrowseForFolder1 = BrowseForFolder & "\" & fName1 & fName2 & fName5
MkDir BrowseForFolder1
End If
Next cell
End Sub
You could use this code:
Sub Macro1()
Dim lLastRow As Long
Dim sPath As String, sNewFolder As String
sPath = CurDir()
lLastRow = Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To lLastRow
If Range("B" & i).Value > 10 Then
sNewFolder = Range("B" & i).Value & "_" & Range("C" & i).Value & "_" & Range("D" & i).Value
If Dir(sPath & "\" & sNewFolder, vbDirectory) = "" Then
MkDir (sPath & "\" & sNewFolder)
End If
End If
sNewFolder = vbNullString
Next
End Sub
Fisrt of all I check for the last row index based on A column, not to loop through whole worksheet.
In a loop I've used a Dir() function with vbDirectory parameter which returns empty string when folder does not exists & in that case it creates a folder.
Is this what you're after?
Folder name is column B value _ column C value _ column D value ?
Sub loopthrough()
Dim cell As Range, fName4
BrowseForFolder = CurDir()
fName4 = "_"
With Worksheets("Output_" & Date)
For Each cell In .Range("B1", .Range("B" & Rows.Count).End(xlUp))
If cell.Value > 10 Then
BrowseForFolder1 = BrowseForFolder & "\" & cell.Value & fName4 & cell.Offset(, 1).Value & fName4 & cell.Offset(, 2).Value
MkDir BrowseForFolder1
End If
Next cell
End With
End Sub
it works for somebody need same as me
Sub Macro1()
Dim lLastRow As Long
Dim sPath As String, sNewFolder As String
sPath = CurDir()
lLastRow = workbooks(sFilename).Sheets(1).Range("A:A").SpecialCells(xlCellTypeLastCell).Row
Workbooks(sFilename).Sheets(1).Activate
For i = 2 To lLastRow
If Workbooks(sFilename).Sheets(1).Cells(i, 2).Value >= 10 Then
sNewFolder = ActiveSheet.Range("B" & i).Value & "_" & ActiveSheet.Range("C" &
i ).Value & "_" & ActiveSheet.Range("D" & i).Value
If Dir(sPath & "\" & sNewFolder, vbDirectory) = "" Then
MkDir (sPath & "\" & sNewFolder)
End If
End If
sNewFolder = vbNullString
Next
End Sub

Hyperlinks.add changes hyperlink unwanted

I have used hyperlinks.add several times now and never had any problems with it.
Now I added a line of code: SourceBook.Sheets(ESN & "_SV" & SV).Hyperlinks.Add Anchor:=Range("A" & i), _
Address:=ToPath & NewName to my base code (which you can find under here). This should add a link to the newly created document.
The problem is that excel always says it cannot open the file. The link I enter via code is right, as I copied it with debug.print and it opened the file without a problem.
It came to my attention that the hyperlink I added was modified by excel when I hold my mouse over the hyperlink. I wonder how this is possible.
A second problem I encounterd is that when I enter the hyperlink manually and navigate manually to the file to make sure it takes the right file, excel still modifies my link and says "cannot open specified file".
Anyone an idea what might go wrong here? Thanks!
Code:
`Application.ScreenUpdating = False
Dim i, j, FSO As Object, SV, ESN, PartName, ToPath, FromPath, NewName, MsgBoxAnswer, TargetBook As Workbook, SourceBook As Workbook
Dim OS, PN, SN, ProjectNumber, Customer, StartDate, EndDate, LastRowCMM
ESN = ActiveWorkbook.ActiveSheet.Range("G2").Value
SV = ActiveWorkbook.ActiveSheet.Range("K2").Value
ProjectNumber = ActiveWorkbook.ActiveSheet.Range("A3").Value
Customer = ActiveWorkbook.ActiveSheet.Range("G3").Value
Set FSO = CreateObject("scripting.filesystemobject")
PGB.Min = 0
PGB.Value = 0
PGB.Max = 22
'Create main folder
If SV <> 1 Then
SV = "(SV " & SV & ")"
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV
Else
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN
End If
If FSO.folderexists(ToPath) = True Then
MsgBoxAnswer = MsgBox("Folder already created.", vbExclamation, "Folder exists.")
Exit Sub
End If
FSO.createfolder (ToPath)
'Create all Excel files & fill them in
For i = 6 To 27
FromPath = "U:\tmo\VANMOLLE\Fiches constat\Template fiches constat LEAP.xlsm"
If SV <> 1 Then
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV & "\"
Else
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & "\"
End If
FSO.copyfile Source:=FromPath, Destination:=ToPath
NewName = "#" & ESN & "_" & ActiveWorkbook.ActiveSheet.Range("A" & i) & ".xlsm"
If SV <> 1 Then
FromPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV & "\Template fiches constat LEAP.xlsm"
Else
FromPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & "\Template fiches constat LEAP.xlsm"
End If
Name FromPath As ToPath & NewName
Set SourceBook = ThisWorkbook
Set TargetBook = Workbooks.Open(ToPath & NewName)
TargetBook.Sheets("Sheet1").Activate
PartName = SourceBook.ActiveSheet.Range("A" & i).Value
OS = SourceBook.ActiveSheet.Range("D" & i).Value
PN = SourceBook.ActiveSheet.Range("B" & i).Value
SN = SourceBook.ActiveSheet.Range("C" & i).Value
If SN = "" Then SN = "N/A"
StartDate = SourceBook.ActiveSheet.Range("G" & i).Value
EndDate = SourceBook.ActiveSheet.Range("H" & i).Value
'check for right CMM
'LastRowCMM = TargetBook.Sheets("Révision CMM").Range("B6").End(xlDown).Row
'For j = 1 To LastRowCMM
'If PartName = TargetBook.Sheets("Révision CMM").Range("A" & j).Value Then ActiveWorkbook.ActiveSheet.Range("A23").Value = ActiveWorkbook.Sheets("Révision CMM").Range("B" & j).Value
'Next j
TargetBook.ActiveSheet.Range("B9").Value = PartName
TargetBook.ActiveSheet.Range("B10").Value = OS
TargetBook.ActiveSheet.Range("B11").Value = "# " & ESN
TargetBook.ActiveSheet.Range("B12").Value = PN
TargetBook.ActiveSheet.Range("B13").Value = SN
TargetBook.ActiveSheet.Range("E9").Value = StartDate
TargetBook.ActiveSheet.Range("E10").Value = EndDate
TargetBook.ActiveSheet.Range("B14").Value = ProjectNumber
TargetBook.ActiveSheet.Range("B15").Value = Customer
TargetBook.ActiveSheet.PageSetup.PrintArea = "$A$1:$E$39"
TargetBook.Close True
'Add hyperlink
SourceBook.Sheets(ESN & "_SV" & SV).Hyperlinks.Add Anchor:=Range("A" & i), _
Address:=ToPath & NewName
Application.Wait (Now + TimeValue("00:00:01"))
Progress.PGB.Value = i - 5
Progress.Lbl.Caption = "File " & i - 5 & " of 22 copied."
Next i
Application.ScreenUpdating = True`
First thing first - declare each variable explicitly. E.g.:
Dim i as Long, j as Long, FSO As Object, SV as String, ESN as String and etc.
The way in your code - Dim i, j, SV, ESN, PartName, ToPath they are declared as variant.
Second thing second - try something really very small to debug further. E.g. write this small piece:
Sub TestMe()
With Worksheets(1)
.Hyperlinks.Add anchor:=.Range("A1"), Address:="C:\Users\UserName\Desktop\test.docx"
End With
End Sub
and check whether it works. If it doesn't, debug further, check whether cells are locked or anything similar.

Resources