VBA Error Saving, wrap text not working

DanielMZw

New Member
Joined
Aug 31, 2016
Messages
1
Hello,
I am a little bit a newby with VBA. I used a lot of the internet and by self exploring. Made the code a little bit messy.
Whats the problem: I get an Error and can't find the solution. I can send you a example of the worksheet.

In my worksheet Column 20 (T) is a schoolname. Column 18 (R) is their unique schoolcode.
The VBA code I got from internet will create a new folder with a new workbook for every unique value in the Column 18 (R) of the range.The workbooks will be saved with the value in the column 20 (T) + column 18 (r) into the newly created folder. It will also add a worksheet to the workbook named "RDBLogSheet" with hyperlinks to the newly created workbooks so it is easy to open the workbooks.

The problem is that some schoolnames exist out of two schools, like Ambeld LKZ Deltion College. That's why I want to save the worksheet also with the unique schoolcode.
Somehow, even when I use a VBA code for Removing Wrap Text (works well), it gives an error when the sheets is being saved.
The error says: "Rename every worksheet name that starts with "Error_" manually. There are characters in the name that are not allowed in the sheet or the worksheet already exist"
I know definitely that the worksheet does not already exist.

I tried with no success to delete the format of the cells, a different notation (text instead of standard), to create an error in a cell that worked fine (add the same text and format).
PLEASE HELP!!!

The vba code I use:
Option Explicit
'<<<< Create a new workbook for every unique value >>>>>
'This example will create a new folder for you and will create
'a new workbook with the data of every unique value in this folder.
'The workbooks will be saved with the Unique value in the new folder.
'It will also add a worksheet to your workbook named "RDBLogSheet" with
'hyperlinks to the workbooks so it is easy to open the workbooks.
'Every time you run the macro it delete this worksheet first so the information is up to date.
'Note: this example use the function LastRow in the ModReset module
Sub Copy_To_Workbooks()
'Note: This macro use the function LastRow
Columns("R:R").Select
Selection.WrapText = False 'Removing Wrap Text
Selection.Replace What:=Chr(10), Replacement:="-", LookAt:=xlPart, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Columns("T:T").Select
Selection.WrapText = False 'Removing Wrap Text
Selection.Replace What:=Chr(10), Replacement:="-", LookAt:=xlPart, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Dim My_Range As Range
Dim FieldNum As Long
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim ws2 As Worksheet
Dim MyPath As String
Dim foldername As String
Dim Lrow As Long
Dim cell As Range
Dim CCount As Long
Dim WSNew As Worksheet
Dim ErrNum As Long

'Set filter range on ActiveSheet: A11 is the top left cell of your filter range
'and the header of the first column, AO is the last column in the filter range.
'You can also add the sheet name to the code like this :
'Worksheets("Sheet1").Range("A11:AO" & LastRow(Worksheets("Sheet1")))
'No need that the sheet is active then when you run the macro when you use this.
Cells.Select
Selection.ClearFormats
Set My_Range = Range("A11:AZ" & LastRow(ActiveSheet))
My_Range.Parent.Select
If ActiveWorkbook.ProtectStructure = True Or _
My_Range.Parent.ProtectContents = True Then
MsgBox "Sorry, not working when the workbook or worksheet is protected", _
vbOKOnly, "Copy to new workbook"
Exit Sub
End If
'This example filters on the first column in the range(change the field if needed)
'In this case the range starts in A so Field:=1 is column A, 2 = column B, ......
FieldNum = 18
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
'Set the file extension/format
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xlsx": FileFormatNum = -4143
Else
'You use Excel 2007-2013
If ActiveWorkbook.FileFormat = 56 Then
FileExtStr = ".xls": FileFormatNum = 56
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
End If
'Change ScreenUpdating, Calculation, EnableEvents, ....
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
ActiveSheet.DisplayPageBreaks = False
'Delete the sheet RDBLogSheet if it exists
On Error Resume Next
Application.DisplayAlerts = False
Sheets("RDBLogSheet").Delete
Application.DisplayAlerts = True
On Error GoTo 0
' Add worksheet to copy/Paste the unique list
Set ws2 = Worksheets.Add(After:=Sheets(Sheets.Count))
ws2.Name = "RDBLogSheet"
'Fill in the path\folder where you want the new folder with the files
'you can use also this "C:\Users\Ron\test"
MyPath = "Y:\Gemeente\EENHEID_SZ\SZW - Werk Re-integratie Participatie\SharePoint 2014\Schakel-makelpool\Forecast"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "" Then
MyPath = MyPath & ""
End If
'Create folder for the new files
foldername = MyPath & Format(Now, "okt yyyy") & ""
MkDir foldername
With ws2
'first we copy the Unique data from the filter field to ws2
My_Range.Columns(FieldNum).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=.Range("A3"), Unique:=True
'loop through the unique list in ws2 and filter/copy to a new sheet
Lrow = .Cells(Rows.Count, "A").End(xlUp).Row
For Each cell In .Range("A4:A" & Lrow)
'Filter the range
My_Range.AutoFilter Field:=FieldNum, Criteria1:="=" & _
Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")
'Check if there are no more then 8192 areas(limit of areas)
CCount = 0
On Error Resume Next
CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible) _
.Areas(1).Cells.Count
On Error GoTo 0
If CCount = 0 Then
MsgBox "There are more than 8192 areas for the value : " & cell.Value _
& vbNewLine & "It is not possible to copy the visible data." _
& vbNewLine & "Tip: Sort your data before you use this macro.", _
vbOKOnly, "Split in worksheets"
Else
'Add new workbook with one sheet
Set WSNew = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
'Copy/paste the visible data to the new workbook
My_Range.SpecialCells(xlCellTypeVisible).Copy
With WSNew.Range("A1")
' Paste:=8 will copy the columnwidth in Excel 2000 and higher
' Remove this line if you use Excel 97
.PasteSpecial Paste:=8
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
.Select
Columns("A:A").EntireColumn.AutoFit
Cells.Select
Cells.EntireColumn.AutoFit
Cells.EntireRow.AutoFit
Selection.ColumnWidth = 26.43
Cells.EntireColumn.AutoFit
Cells.EntireRow.AutoFit
Range("S2").Select
Columns("R:R").ColumnWidth = 46
Columns("R:R").ColumnWidth = 49.29
Columns("P:P").Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=$AQ$2:$AQ$6"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Sheets.Add After:=Sheets(Sheets.Count)
Sheets("Blad2").Select
Sheets("Blad2").Name = "Toelichting"
Sheets("Blad1").Select
Sheets("Blad1").Name = "Lijst"
Sheets("Toelichting").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "Toelichting"
Range("A1:C1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Selection.Merge
Selection.Font.Bold = True
Selection.Font.Size = 11
Selection.Font.Size = 12
Selection.Font.Size = 14
Selection.Font.Size = 16
Selection.Font.Size = 18
Selection.Font.Size = 20
Range("A3").Select
ActiveCell.FormulaR1C1 = "Vul de lijst als school als volgt in:"
Sheets("Lijst").Select
Range("J1:N1").Select
Selection.Copy
Sheets("Toelichting").Select
Range("A5").Select
ActiveSheet.Paste
Columns("A:A").EntireColumn.AutoFit
Columns("B:B").EntireColumn.AutoFit
Columns("C:C").EntireColumn.AutoFit
Columns("D:D").EntireColumn.AutoFit
Columns("E:E").ColumnWidth = 8.14
Columns("E:E").EntireColumn.AutoFit
Range("D5").Select
Application.CutCopyMode = False
Selection.AutoFill Destination:=Range("D5:D6"), Type:=xlFillDefault
Range("D5:D6").Select
Range("D6").Select
Selection.ClearContents
Range("D6").Select
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Range("D6").Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
Selection.Borders(xlEdgeTop).LineStyle = xlNone
Selection.Borders(xlEdgeBottom).LineStyle = xlNone
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
Range("A6").Select
ActiveCell.FormulaR1C1 = _
"Hier vult u Ja of Nee in als u weet dat de jongere een beschikking heeft ontvangen dat hij/zij is opgenomen in het doelgroepregister"
Range("A1:C1").Select
Columns("A:A").EntireColumn.AutoFit
Range("A6").Select
Rows("6:6").RowHeight = 62.25
Columns("A:A").ColumnWidth = 46.86
Columns("A:A").ColumnWidth = 31.29
Rows("6:6").Select
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlBottom
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("B6").Select
ActiveCell.FormulaR1C1 = "Datum invullen: dd/mm/yyyy"
Range("C6").Select
ActiveCell.FormulaR1C1 = _
"Dit is alleen voor VSO: vul in Vervolgonderwijs / Arbeid / Dagbesteding"
Range("D6").Select
Range("D6").Select
With Selection.Validation
.Delete
.Add Type:=xlValidateInputOnly, AlertStyle:=xlValidAlertStop, Operator _
:=xlBetween
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Range("D6").Select
ActiveCell.FormulaR1C1 = _
"Vul voor PRO of Entree hier alleen in: Vervolgonderwijs/Arbeidsmartk zelfstandig wml/ Arbeidsmarkt ondersteuning wml/Arbeidsmarkt niet wml/Dagbesteding. Er is een keuze lijst. "
Range("E6").Select
Columns("D:D").ColumnWidth = 30.29
Columns("C:C").ColumnWidth = 20.29
Rows("6:6").EntireRow.AutoFit
Columns("D:D").ColumnWidth = 34.14
Columns("A:A").ColumnWidth = 33.57
Rows("6:6").Select
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("E6").Select
ActiveCell.FormulaR1C1 = _
"Hier kunt u de uitstroomrichting ingeven, bijvoorbeeld Techniek of Horeca"
Range("G15:G17").Select
Range("G17").Activate
Columns("E:E").ColumnWidth = 27
Range("A1:E1").Select
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = True
End With
Selection.UnMerge
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Selection.Merge
Range("C10:C11").Select
Sheets("Lijst").Select
Columns("M:M").Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=$AO$2:$AO$3"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Columns("O:O").Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=$AP$2:$AP$4"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Range("K19").Select
Range("A2").Select
Sheets("Toelichting").Select
Sheets("Toelichting").Move Before:=Sheets(1)
Range("A1:E1").Select
Sheets("Lijst").Select
ActiveWindow.LargeScroll ToRight:=-1
Range("A1").Select
Selection.End(xlToRight).Select
Range(Selection, Selection.End(xlToLeft)).Select
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A:$V"), , xlYes).Name = _
"Tabel2"
Columns("A:V").Select
ActiveSheet.ListObjects("Tabel2").TableStyle = "TableStyleMedium2"
Range("B13").Select
ActiveWindow.SmallScroll Down:=-54
Range("AO1").Select
ActiveCell.FormulaR1C1 = "validatie doelgroepregister"
Range("AP1").Select
ActiveCell.FormulaR1C1 = "Validatie VSO"
Range("AQ1").Select
ActiveCell.FormulaR1C1 = "Validatie ProEntree"
Range("AO2").Select
ActiveCell.FormulaR1C1 = "Ja"
Range("AO3").Select
ActiveCell.FormulaR1C1 = "Nee"
Range("AP2").Select
ActiveCell.FormulaR1C1 = "Vervolgonderwijs"
Range("AP3").Select
ActiveCell.FormulaR1C1 = "Arbeid"
Range("AP4").Select
ActiveCell.FormulaR1C1 = "Dagbesteding"
Range("AQ2").Select
ActiveCell.FormulaR1C1 = "Vervolgonderwijs"
Range("AQ3").Select
ActiveCell.FormulaR1C1 = "Arbeidsmarkt zelfstandig wml"
Range("AQ4").Select
ActiveCell.FormulaR1C1 = "Arbeidsmarkt ondersteuning wml"
Range("AQ5").Select
ActiveCell.FormulaR1C1 = "Arbeidsmarkt niet wml"
Range("AQ6").Select
ActiveCell.FormulaR1C1 = "Dagbesteding"
Columns("AO:AR").Select
Selection.EntireColumn.Hidden = True

End With

'Save the file in the new folder and close it
On Error Resume Next
WSNew.Parent.SaveAs foldername & _
Sheets("Lijst").Cells(2, 20) & "_" & Sheets("Lijst").Cells(2, 18) & FileExtStr, FileFormatNum
If Err.Number > 0 Then
Err.Clear
ErrNum = ErrNum + 1
WSNew.Parent.SaveAs foldername & _
"Error_" & Format(ErrNum, "0000") & FileExtStr, FileFormatNum
.Cells(cell.Row, "B").Formula = "=Hyperlink(""" & foldername & _
"Error_" & Format(ErrNum, "0000") & FileExtStr & """)"
.Cells(cell.Row, "A").Interior.Color = vbRed
Else
.Cells(cell.Row, "B").Formula = _
"=Hyperlink(""" & foldername & Sheets("Lijst").Cells(2, 20) & "_" & Sheets("Lijst").Cells(2, 18) & FileExtStr & """)"
End If
WSNew.Parent.Close False
On Error GoTo 0
End If
'Show all the data in the range
My_Range.AutoFilter Field:=FieldNum
Next cell
.Cells(1, "A").Value = "Red cell: can't use the Unique name as file name"
.Cells(1, "B").Value = "Created Files (Click on the link to open a file)"
.Cells(3, "A").Value = "Unique Values"
.Cells(3, "B").Value = "Full Path and File name"
.Cells(3, "A").Font.Bold = True
.Cells(3, "B").Font.Bold = True
.Columns("A:B").AutoFit
End With
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
If ErrNum > 0 Then
MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
& vbNewLine & "There are characters in the name that are not allowed" _
& vbNewLine & "in a sheet name or the worksheet already exist."
End If
'Restore ScreenUpdating, Calculation, EnableEvents, ....
My_Range.Parent.Select
ActiveWindow.View = ViewMode
ws2.Select
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
 

Excel Facts

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.

Forum statistics

Threads
1,214,376
Messages
6,119,178
Members
448,871
Latest member
hengshankouniuniu

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top