This is the entire code that goes from importing an Excel document to creating folders using an Excel spreadsheet.
Sub Update_JL()
Dim wsJL As Worksheet 'Open Orders
Dim wsJOD As Worksheet 'Jobs Data
Dim wsJAR As Worksheet 'JL Archive
Dim wbBK1 As Workbook
Dim wbBK2 As Workbook
Dim wsBOR As Worksheet
Dim lastrow As Long, fstcell As Long, strCompany As String, strPart As String, strPath As String, strFile As String
Dim cell As Range, newFolder As String, PhotoDir As String
Set wsJL = Sheets("Open Orders")
Set wsJOD = Sheets("Jobs Data")
Set wsJAR = Sheets("JL Archive")
Set wbBK1 = ThisWorkbook
Set wbBK2 = ActiveWorkbook
Application.ScreenUpdating = False ' Prevents screen refreshing.
Application.Calculation = xlCalculationManual
With wsJOD
.Columns("A:Q").Clear
wsJL.Range("B2:I2").Copy wsJOD.Range("A1")
.Range("I1").Formula = "=COUNTIFS('Open Orders'!$B:$B,$A1,'Open Orders'!$D:$D,$C1)"
.Range("J1").Formula = "=IF(I1,""Same"",""Different"")"
End With
strFile = Application.GetOpenFilename()
Set wbBK2 = Application.Workbooks.Open(strFile)
Set wsBOR = Sheets(Replace(wbBK2.Name, ".csv", ""))
lastrow = wsBOR.Range("C" & Rows.Count).End(xlUp).Row
wsBOR.Range("B6:E" & lastrow).Copy wsJOD.Range("A2")
wsBOR.Range("G6:H" & lastrow).Copy wsJOD.Range("E2")
wsBOR.Range("L6:L" & lastrow).Copy wsJOD.Range("G2")
wsBOR.Range("N6:N" & lastrow).Copy wsJOD.Range("H2")
wbBK2.Close
lastrow = wsJOD.Range("A" & Rows.Count).End(xlUp).Row
wsJOD.Range("I1:J1").Copy wsJOD.Range("I2:J" & lastrow)
wsJOD.Range("I2:J" & lastrow).Calculate
lastrow = wsJL.Range("B" & Rows.Count).End(xlUp).Row
wsJL.Range("P2:R2").Copy wsJL.Range("P3:R" & lastrow)
wsJL.Range("P3:R" & lastrow).Calculate
With Intersect(wsJL.UsedRange, wsJL.Columns("Q"))
.AutoFilter 1, "<>Same"
With Intersect(.Offset(2).EntireRow, .Parent.Range("B:U"))
.Copy wsJAR.Cells(Rows.Count, "B").End(xlUp).Offset(1)
.EntireRow.Delete
End With
.AutoFilter
End With
lastrow = wsJOD.Range("A" & Rows.Count).End(xlUp).Row
With Intersect(wsJOD.UsedRange, wsJOD.Range("J2:J" & lastrow))
.AutoFilter 1, "<>Different"
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
wsJOD.Range("A2:H" & lastrow).Copy wsJL.Cells(Rows.Count, "B").End(xlUp).Offset(1)
wsJOD.Columns("A:Q").Clear
lastrow = wsJL.Range("B" & Rows.Count).End(xlUp).Row
wsJL.Range("J3:K3").Copy wsJL.Range("J4:K" & lastrow)
wsJL.Range("B3:N3").Copy
wsJL.Range("B4:N" & lastrow).Borders.Weight = xlThin
wsJL.Range("B4:N" & lastrow).Font.Size = 11
wsJL.Range("B4:N" & lastrow).Font.Name = "Calibri"
wsJL.Range("J3:K" & lastrow).Calculate
'Sort PO Tracking
With wsJL
.Sort.SortFields.Clear
'Sort Reds
.Sort.SortFields.Add(.Range("K3:K" & lastrow), _
xlSortOnIcon, xlAscending, , xlSortNormal).SetIcon Icon:=ActiveWorkbook. _
IconSets(4).Item(1)
.Sort.SortFields.Add Key:=Range( _
"K3:K" & lastrow), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
'Sort Yellows
.Sort.SortFields.Add(.Range("J3:J" & lastrow), _
xlSortOnIcon, xlAscending, , xlSortNormal).SetIcon Icon:=ActiveWorkbook. _
IconSets(4).Item(2)
'Sort Greens
.Sort.SortFields.Add(.Range("J3:J" & lastrow), _
xlSortOnIcon, xlAscending, , xlSortNormal).SetIcon Icon:=ActiveWorkbook. _
IconSets(4).Item(3)
.Sort.SortFields.Add Key:=Range( _
"J3:J" & lastrow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With .Sort
.SetRange wsJL.Range("B2:U" & lastrow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
lastrow = wsJL.Range("B" & Rows.Count).End(xlUp).Row
wsJL.Range("B3:N" & lastrow).Select
wsJL.Range("B3:N" & lastrow).VerticalAlignment = xlCenter
wsJL.Range("A1").Select
End With
With wsJL
strCompany = CleanName(Range("C3")) ' assumes company name starts in C
strPart = CleanName(Range("D3")) ' assumes part in D
strPath = wbBK1.path & Application.PathSeparator & "Photos" & Application.PathSeparator
If Not FolderExists(strPath & strCompany) Then
'company doesn't exist, so create full path
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strCompany & Application.PathSeparator & strPart) Then
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
End If
End If
Range("J:M").Calculate
End With
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
MsgBox "Open Orders Updated!"
End Sub
The functions:
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim fso As New FileSystemObject
If FolderExists(path) Then
Exit Function
Else
On Error GoTo DeadInTheWater
fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
Exit Function
End If
DeadInTheWater:
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
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 CleanName(strIn As String) As String
'will clean part # name so it can be made into valid folder name
'may need to add more lines to get rid of other characters
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Global = True
.Pattern = "[,\/\*\.\\""""]+"
CleanName = .Replace(strIn, vbNullString)
End With
End Function
(source: kaboomlabs.com)
As you see above C3 should be cleaned up. I don't have the folder protected or locked. I created the folder yesterday in hopes to get it working.
Code and information here: CreateFolder Sheet and scripts
Try changing your code to
If Not FolderExists(strPath & strCompany) Then
'Company doesn't exist, so first create company folder and then part folder
FolderCreate strPath & strCompany
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strCompany & Application.PathSeparator & strPart) Then
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
End If
End If
EDIT:
replace this bit:
If Not FolderExists(strPath & strCompany) Then
'company doesn't exist, so create full path
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strCompany & Application.PathSeparator & strPart) Then
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
End If
End If
No Problem
The issue is that the way you are creating folders will only allow you to create one at a time. So you need to build the path up, maybe something like:
Function CreatePath(path As String) As Boolean
Dim pPath As String
Dim x as long
Dim arr
arr = Split(path, "\")
For x = LBound(arr) To UBound(arr)
If x = 0 Then
pPath = arr(x)
Else
pPath = pPath & "\" & arr(x)
End If
If Len(Dir(pPath, vbDirectory)) = 0 Then MkDir pPath
Next x
If Len(Dir(pPath, vbDirectory)) > 0 Then CreatePath = True
End Function
Which will create a path of any depth.
Ok, it with an old script I have, added more stuff to the workbook cell wise, but it works the way I need it too.
Here is the code:
Dim baseFolder As String, newFolder As String
lastrow = wsJL.Cells(Rows.Count, "B").End(xlUp).Row
wsJL.Range("S2:U2").Copy wsJL.Range("S3:U" & lastrow)
Range("J3:M" & lastrow).Calculate
Range("S3:U" & lastrow).Calculate
baseFolder = wbBK1.path & Application.PathSeparator & "Photos" & Application.PathSeparator
'folders will be created within this folder - Change to sheet of your like.
If Right(baseFolder, 1) <> Application.PathSeparator Then _
baseFolder = baseFolder & Application.PathSeparator
For Each cell In Range("S3:S" & lastrow) 'CHANGE TO SUIT
'Company folder - column S
newFolder = baseFolder & cell.Value
If Len(Dir(newFolder, vbDirectory)) = 0 Then MkDir newFolder
'Part number subfolder - column T
newFolder = newFolder & Application.PathSeparator & cell.Offset(0, 1).Value
If Len(Dir(newFolder, vbDirectory)) = 0 Then MkDir newFolder
Next
End With
I have in S and T is this:
S
=TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($C2,",","")," "," "),".",""),"/","-"),"""",""),"*",""))
T
=TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($D2,",","")," "," "),".",""),"/","-"),"""",""),"*",""))
This trims the end of all the cells of any blank spaces that we don't see, and cleans up the cells so it's accurate and possible to have a folder created in it.
Related
I'm new to VBA and I've been trying to create a macro where we have a list of cost centres (total of 385) and the idea behind it is to go through them one by one through a slicer. After each value was selected it will be PDFed then move to the next one. First time I ran it it worked for the first 20 then it crashed my excel, then the second time it ran 24 and crashed again, so on and so forth. The crash itself doesn't bring any error messages it just closes down excel.
I've used both with and without display alerts and screenupdate however the same result.
Any help is much appreciated.
My code below:
Sub Macro_test1()
Dim strGenericFilePath As String: strGenericFilePath = "C:\Users\"
Dim strYear As String: strYear = Year(Date) & "\"
Dim strMonth As String: strMonth = MonthName(Month(Date)) & "\"
Dim strDay As String: strDay = Format(Date, "dd.mm.yyyy") & "\"
Dim IntSliceCount As Integer
Dim IntLoop As Integer
Dim SliceLoop As Integer
Dim Slice As SlicerItem
Dim sC As SlicerCache
Set sC = ActiveWorkbook.SlicerCaches("Slicer_CostCentre")
'Application.DisplayAlerts = False
'Application.ScreenUpdating = False
'This reminds the user to only select the first slicer item
If sC.VisibleSlicerItems.Count <> 1 Or sC.SlicerItems(1).Selected = False Then
MsgBox "Please only select first cost centre from slicer in 'Summary+Air' tab"
Exit Sub
End If
For i = 1 To sC.SlicerItems.Count
'Do not clear filter as it causes to select all of the items (sC.ClearManualFilter)
sC.SlicerItems(i).Selected = True
If i <> 1 Then sC.SlicerItems(i - 1).Selected = False
'Debug.Print sI.Name
'Add export to PDF code here
With sheet1.PageSetup
.PrintArea = sheet1.Range("A1:V91" & lastRow).Address
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
sheet2.Range("F7") = sC.SlicerItems(i).Name
' Check for year folder and create if needed
If Len(Dir(strGenericFilePath & strYear, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear
End If
' Check for month folder and create if needed
If Len(Dir(strGenericFilePath & strYear & strMonth, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear & strMonth
End If
' Check for date folder and create if needed
If Len(Dir(strGenericFilePath & strYear & strMonth & strDay, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear & strMonth & strDay
End If
' Save File
sheet1.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:= _
strGenericFilePath & strYear & strMonth & strDay & sheet2.Range("F7").Text & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
'Application.DisplayAlerts = True
'Application.ScreenUpdating = True
End Sub
I'm working on macro for MacBook for separating codes that we paste in file.
After running codes should show up in a folder on my desktop called Tour Codes.
However, file is not getting saved and macro shows error.
I've tried multiple adjustments and changing location of file but the problem remains.
I would appreciate any suggestions.
Sub create_files()
Application.ScreenUpdating = False
Dim iName, iPath
iName = GetUserNameMac
'Get Path and Workbook Name
'iPath = ActiveWorkbook.Path
iPath = "Macintosh HD:Users:" & iName & ":Desktop:Tour Codes"
Sheets("Data").Select
...
'create files
Dim r1, ddate, gate, id, cap, firstrow, rowcount, newcode
r1 = 2
firstrow = 2
...
Application.DisplayAlerts = False
'save file
ChDir "Macintosh HD:Users:" & iName & ":Desktop:Tour Codes"
ActiveWorkbook.SaveAs Filename:= _
iPath & ":" & id & "_" & Format(ddate, "yyyy-mm-dd") & "_" & gate & "_" & firstrow & ".csv", _
FileFormat:=xlCSV, CreateBackup:=False
'ActiveWorkbook.SaveAs iPath & ":" & merchWk
'ActiveWorkbook.SaveAs iPath & "/" & merchWk
Windows("Gate 1 codes macro.xlsm").Activate
'copy rows to file
'Rows(firstrow & ":" & firstrow + rowcount - 2).Select
Range(Cells(firstrow, 1), Cells(firstrow + rowcount - 2, 1)).Select
Selection.Copy
Windows(id & "_" & Format(ddate, "yyyy-mm-dd") & "_" & gate & "_" & firstrow & ".csv").Activate
'Cells(2, 1).Select
Cells(1, 1).Select
ActiveSheet.Paste
'Columns("A:E").EntireColumn.AutoFit
Columns("A:A").EntireColumn.AutoFit
'save file
Cells(1, 1).Select
ActiveWorkbook.Save
ActiveWindow.Close
Application.DisplayAlerts = True
Windows("Gate 1 codes macro.xlsm").Activate
firstrow = r1 - 1
r1 = firstrow
Loop Until r1 > lastrow
End Sub
Function GetUserNameMac() As String
Dim sMyScript As String
sMyScript = "set userName to short user name of (system info)" & vbNewLine & "return userName"
GetUserNameMac = MacScript(sMyScript)
End Function
VBA errors out on these lines:
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
I'm trying to copy a lot of workbooks into a summary workbook, I've gotten the below code to do the job so far.
Option Explicit
Const FOLDER_PATH = "Folderpath\" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
'=============================================
'Process all Excel files in specified folder
'=============================================
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long 'output row
rowTarget = Sheets("Status").Cells(Rows.Count, "AK").End(xlUp).Row + 1
'check the folder exists
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
'reset application settings in event of error
'On Error GoTo errHandler
'Application.ScreenUpdating = False
'set up the target worksheet
Set wsTarget = Sheets("Status")
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
Set wsSource = wbSource.Worksheets("Side 1-Forside") 'EDIT IF NECESSARY
'import the data
With wsTarget
.Activate
wsSource.Range("C14").Copy
.Range("A" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("C15").Copy
.Range("B" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("C13").Copy
.Range("C" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("I11").Copy
.Range("J" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("I10").Copy
.Range("K" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("C40").Copy
.Range("L" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("E40").Copy
.Range("M" & rowTarget).Select
ActiveSheet.Paste Link:=True
wsSource.Range("I9").Copy
.Range("H" & rowTarget).Select
ActiveSheet.Paste Link:=True
'optional source filename in the last column
.Range("AK" & rowTarget).Value = sFile
End With
'close the source workbook, increment the output row and get the next file
wbSource.Close SaveChanges:=False
rowTarget = rowTarget + 1
sFile = Dir()
Loop
'errHandler:
'On Error Resume Next
'Application.ScreenUpdating = True
'tidy up
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
End Sub
Private Function FileFolderExists(strPath As String) As Boolean
If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
End Function
However is it possible to grab the data as a link instead of a "dead" value? So if it gets changed in one of the many workbooks, I just have to refresh the summary workbook?
Bonusquestion: Is it possible to check for duplicates in this bit: .Range("AK" & rowTarget).Value = sFile and only add if the values isn't there already and the new values should add from the last empty row below row 5?
You could copy the source range and then use Special Paste › Paste Link in the destination workbook. It pastes a formula linking to the source workbooks copied range.
This short YouTube video should illustrate it best.
You could also do that with VBA if necessary e.g:
wsSource.Range("C14").Copy
.Range("A" & rowTarget).Select
ActiveSheet.Paste Link:=True
It seems like we need to .Select first and use ActiveSheet.Paste otherwise the link pasting fails, even if that looks like a bad practice, but the below direct referencing the range won't work!
wsSource.Range("C14").Copy
.Range("A" & rowTarget).Paste Link:=True 'fails with error 438
But because you are linking the values now with a formula you probably need to do that only once and therefore don't need the VBA solution anymore, because it is easier to do it once by hand.
Note:
be aware that these workbooks are linked by a formula then. If you move the source workbook into another location the link will break (if the destination workbook is not within the same location and copied as well). This comes with all the downsides of linked workbooks.
//edit
With wsTarget
.Activate
.Range("A" & rowTarget).Select
wsSource.Range("C14").Copy
.Paste Link:=True
.Activate
.Range("B" & rowTarget).Select
wsSource.Range("C15").Copy
.Paste Link:=True
Alternative solution to the one suggested by Peh, both work, though the one below is not as flexible but hardcoded instead. Thought I would share.
Option Explicit
Const FOLDER_PATH = "Folderpath\" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
'=============================================
'Process all Excel files in specified folder
'=============================================
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long 'output row
rowTarget = Sheets("Status").Cells(Rows.Count, "AK").End(xlUp).Row + 1
'check the folder exists
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
'reset application settings in event of error
'On Error GoTo errHandler
'Application.ScreenUpdating = False
'set up the target worksheet
Set wsTarget = Sheets("Status")
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
'import the data
With wsTarget
'optional source filename in the last column
.Range("AK" & rowTarget).Value = sFile
.Range("A" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$C$14"
.Range("B" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$C$15"
.Range("C" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$C$13"
.Range("J" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$I$11"
.Range("K" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$I$10"
.Range("L" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$C$40"
.Range("M" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$E$40"
.Range("H" & rowTarget).Value = "=" & "'" & FOLDER_PATH & "[" & .Range("AK" & rowTarget).Value & "]" & "Side 1-Forside" & "'" & "!$I$9"
End With
'close the source workbook, increment the output row and get the next file
rowTarget = rowTarget + 1
sFile = Dir()
Loop
'errHandler:
'On Error Resume Next
'Application.ScreenUpdating = True
'tidy up
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
End Sub
Private Function FileFolderExists(strPath As String) As Boolean
If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
End Function
Try this AddIn. It will do exactly what you want.
https://www.rondebruin.nl/win/addins/rdbmerge.htm
The code has been updated, and I am getting an error, even after checking Microsoft Scripting RunTime off to be active. Below is the error:
Option Explicit
Sub Update_JL()
Dim wsJL As Worksheet 'Jobs List
Dim wsJD As Worksheet 'Jobs Data
Dim wsJAR As Worksheet 'JL Archive
Dim lastrow As Long, fstcell As Long
Dim strCompany As String, strPart As String, strPath As String
Set wsJL = Sheets("Jobs List")
Set wsJD = Sheets("Jobs Data")
Set wsJAR = Sheets("JL Archive")
With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableEvents = False
End With
With Intersect(wsJL.UsedRange, wsJL.Columns("Q"))
.AutoFilter 1, "<>Same"
With Intersect(.Offset(2).EntireRow, .Parent.Range("B:O"))
.Copy wsJAR.Cells(Rows.Count, "B").End(xlUp).Offset(1)
.EntireRow.Delete
End With
.AutoFilter
End With
With wsJD
'Clean empty cells in Column C
lastrow = Range("B" & Rows.Count).End(xlUp).Row + 1
Range("C5:C" & lastrow).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End With
With Intersect(wsJD.UsedRange, wsJD.Columns("Q"))
ActiveSheet.Range("P:Q").Calculate
.AutoFilter 1, "<>Different"
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
With wsJD
.AutoFilterMode = False
Intersect(.UsedRange, .Columns("G")).Cut .Range("F1")
Intersect(.UsedRange, .Columns("H")).Cut .Range("G1")
Intersect(.UsedRange, .Columns("L")).Cut .Range("H1")
Intersect(.UsedRange, .Columns("N")).Cut .Range("I1")
Intersect(.UsedRange, .Range("B:I")).Copy wsJL.Cells(Rows.Count, "B").End(xlUp).Offset(1)
End With
With wsJL
lastrow = wsJL.Cells(Rows.Count, "B").End(xlUp).Row
wsJL.Range("R1:Y1").Copy
wsJL.Range("B3:I" & lastrow).PasteSpecial xlPasteFormats
lastrow = wsJL.Cells(Rows.Count, "J").End(xlUp).Row + 1
fstcell = wsJL.Cells(Rows.Count, "I").End(xlUp).Row
wsJL.Range("Z1:AG1").Copy wsJL.Range("J" & fstcell & ":Q" & lastrow)
wsJL.Range("S2:X2").Copy wsJL.Range("P" & fstcell & ":T" & lastrow)
lastrow = wsJL.Cells(Rows.Count, "B").End(xlUp).Row
wsJL.Range("J:Q").Calculate
Range("B3:N" & lastrow).Sort key1:=Range("F3" & lastrow), order1:=xlAscending
End With
With wsJAR
lastrow = wsJAR.Cells(Rows.Count, "O").End(xlUp).Row
wsJAR.Range("R2:T2").Copy wsJAR.Range("R3:T" & lastrow)
wsJAR.Range("M1").Copy wsJAR.Range("M3:M" & lastrow)
End With
With wsJL
strCompany = Range("C3") ' assumes company name in C3
strPart = CleanName(Range("D3")) ' assumes part in D1
strPath = CleanName(Range("Lists!$G$2"))
If Not FolderExists(strPath & strCompany) Then
'company doesn't exist, so create full path
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strCompany & Application.PathSeparator & strPart) Then
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
End If
End If
Range("J:M").Calculate
End With
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.EnableEvents = True
End With
End Sub
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim fso As New FileSystemObject
If Functions.FolderExists(path) Then
Exit Function
Else
On Error GoTo DeadInTheWater
fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
Exit Function
End If
DeadInTheWater:
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
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 CleanName(strName As String) As String
'will clean part # name so it can be made into valid folder name
'may need to add more lines to get rid of other characters
CleanName = Replace(strName, "/", "")
CleanName = Replace(CleanName, "*", "")
CleanName = Replace(CleanName, ".", "")
End Function
The error is here so far, for this is as far as the script has allowed me to go. The error is:
Compile Error: Variable not defined
The code is below, the place of contention is here between the *. If **Functions**.FolderExists(path) Then
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim fso As New FileSystemObject
If Functions.FolderExists(path) Then
Exit Function
Else
On Error GoTo DeadInTheWater
fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
Exit Function
End If
DeadInTheWater:
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
You just had the code a little off.
each new function should go below the sub, as it is a separate procedure that gets called from the sub. Worth reading up on functions and sub and calling them from one another.
I've reorganized below. Hopefully, will be a little more clear and clean.
Option Explicit
Sub Update_JL()
Dim wsJL As Worksheet 'Jobs List
Dim wsJD As Worksheet 'Jobs Data
Dim wsJAR As Worksheet 'JL Archive
Dim lastrow As Long, fstcell As Long
Dim strCompany As String, strPart As String, strPath As String
Set wsJL = Sheets("Jobs List")
Set wsJD = Sheets("Jobs Data")
Set wsJAR = Sheets("JL Archive")
With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableEvents = False
End With
With Intersect(wsJL.UsedRange, wsJL.Columns("Q"))
.AutoFilter 1, "<>Same"
With Intersect(.Offset(2).EntireRow, .Parent.Range("B:O"))
.Copy wsJAR.Cells(Rows.Count, "B").End(xlUp).Offset(1)
.EntireRow.Delete
End With
.AutoFilter
End With
With wsJD
'Clean up step 1
lastrow = Range("B" & Rows.Count).End(xlUp).Row + 1
Range("C5:C" & lastrow).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
'Blow away rows that are useless
lastrow = Range("B5").End(xlDown).Row
Range("P5:Q5").Copy wsJD.Range("P6:Q" & lastrow)
wsJD.UsedRange.Copy Sheets.Add.Range("A1")
End With
With Intersect(ActiveSheet.UsedRange, ActiveSheet.Columns("Q"))
ActiveSheet.Range("P:Q").Calculate
.AutoFilter 1, "<>Different"
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
With ActiveSheet
ActiveSheet.Range("P:Q").Calculate
.AutoFilterMode = False
Intersect(.UsedRange, .Columns("G")).Cut .Range("F1")
Intersect(.UsedRange, .Columns("H")).Cut .Range("G1")
Intersect(.UsedRange, .Columns("L")).Cut .Range("H1")
Intersect(.UsedRange, .Columns("N")).Cut .Range("I1")
Intersect(.UsedRange, .Range("B:I")).Copy wsJL.Cells(Rows.Count, "B").End(xlUp).Offset(1)
.Delete
End With
With wsJL
lastrow = wsJL.Cells(Rows.Count, "B").End(xlUp).Row
wsJL.Range("R1:Y1").Copy
wsJL.Range("B3:I" & lastrow).PasteSpecial xlPasteFormats
lastrow = wsJL.Cells(Rows.Count, "J").End(xlUp).Row + 1
fstcell = wsJL.Cells(Rows.Count, "I").End(xlUp).Row
wsJL.Range("Z1:AG1").Copy wsJL.Range("J" & fstcell & ":Q" & lastrow)
wsJL.Range("S2:X2").Copy wsJL.Range("P" & fstcell & ":T" & lastrow)
lastrow = wsJL.Cells(Rows.Count, "B").End(xlUp).Row
wsJL.Range("J:Q").Calculate
Range("B3:N" & lastrow).Sort key1:=Range("F3" & lastrow), order1:=xlAscending
End With
With wsJAR
lastrow = wsJAR.Cells(Rows.Count, "O").End(xlUp).Row
wsJAR.Range("R2:T2").Copy wsJAR.Range("R3:T" & lastrow)
wsJAR.Range("M1").Copy wsJAR.Range("M3:M" & lastrow)
End With
With wsJL
strCompany = Range("C3") ' assumes company name in C3
strPart = CleanName(Range("D3")) ' assumes part in D1
strPath = CleanName(Range("Lists!$G$2"))
If Not FolderExists(strPath & strCompany) Then
'company doesn't exist, so create full path
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strCompany & Application.PathSeparator & strPart) Then
FolderCreate strPath & strCompany & Application.PathSeparator & strPart
End If
End If
Range("J:M").Calculate
End With
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.EnableEvents = True
End With
End Sub
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim fso As New FileSystemObject
If FolderExists(path) Then
Exit Function
Else
On Error GoTo DeadInTheWater
fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
Exit Function
End If
DeadInTheWater:
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
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 CleanName(strName As String) As String
'will clean part # name so it can be made into valid folder name
'may need to add more lines to get rid of other characters
CleanName = Replace(strName, "/", "")
CleanName = Replace(CleanName, "*", "")
CleanName = Replace(CleanName, ".", "")
End Function