Trying to write a Clean sheet
Sub
First:
Some serial #'s from the data I get will start with -
which is a problem in excel, I want to replace all cell content that starts
with -
and replace it with @
replace()
does not
work
This is erroring:
.Value = Evaluate("if(row(" & .Address & "),""@"" & Right(" & .Address & ", Len(" & .Address & ") - 2))")
It turns all cells to #NAME?
2nd:
I Changed this
MyArray(x, y) = RemoveChars(MyArray(x, y)
To this
If Not IsError(MyArray(x, y)) Then
MyArray(x, y) = RemoveChars(MyArray(x, y))
End If
Because the code ran (Sans the line of code from Question 1) the first time but if I ran it a second time on the same data sheet it errored
What would cause the code to error on the second run?
Does adding the If Not IsError(MyArray(x, y))
interfere with the removal of unwanted characters?
The UDF
came from Here:
Alter code to Remove instead of Allow characters
Sub UltimateCleanSheet()
Dim HL As Hyperlink
Dim MyArray As Variant
Dim ws As Worksheet
Dim CL As Range
Dim txt As String
Dim LastRow As Long, LastCol As Long, x As Long, y As Long
goFast False
For Each ws In Worksheets(Array("OriginalData", "NewData"))
With ws
'Get error if sheet not selected
ws.Select
'Reset UsedRange
Application.ActiveSheet.UsedRange
'Create Array
MyArray = ws.UsedRange.Offset(1, 0)
'Remove unwanted Characters
'http://www.ascii-code.com/
For x = LBound(MyArray) To UBound(MyArray)
For y = LBound(MyArray, 2) To UBound(MyArray, 2)
If Not IsError(MyArray(x, y)) Then
MyArray(x, y) = RemoveChars(MyArray(x, y))
End If
Next y
Next x
'Postback to sheet
.UsedRange.Offset(1, 0) = MyArray
End With
With ws.UsedRange.Offset(1, 0)
'Clear all formulas
.Value = .Value
'Replace "Non-breaking space" with ""
.Replace what:=Chr(160), replacement:=vbNullString, lookat:=xlPart
'Replace carriage Return with ", "
.Replace what:=Chr(13), replacement:=", ", lookat:=xlPart
'Replace hyphen if 1st char with "@"
.Value = Evaluate("if(row(" & .Address & "),""@"" & Right(" & .Address & ", Len(" & .Address & ") - 2))")
'Clean, Trim
.Value = Evaluate("if(row(" & .Address & "),clean(trim(" & .Address & ")))")
End With
'Turn live hyperlinks to text
For Each HL In ws.Hyperlinks
Set CL = HL.Parent
txt = HL.Address & HL.SubAddress
HL.Delete
CL.Value = txt
Next HL
Next ws
ThisWorkbook.Sheets(1).Select
goFast True
End Sub
UDF:
Function RemoveChars(ByVal strSource As String) As String
Dim i As Integer
Dim strResult As String
For i = 1 To Len(strSource)
Select Case Asc(Mid(strSource, i, 1))
Case 0, 9, 10, 12, 33, 161 To 255:
Case Else:
strResult = strResult & Mid(strSource, i, 1)
End Select
Next i
RemoveChars = strResult
End Function