In order to apply the clean function to the range A1:B50 in my excel sheet, I wrote the code below. However this code won't paste the values I copied. Any idea what's wrong with it? Thanks!
Sub clean ()
Dim ws
Set ws = wb.Worksheets(1)
ws.Range("D1:D50") = "=CLEAN(RC[-3])"
ws.Range("E1:E50") = "=CLEAN(RC[-3])"
ws.Range("D1:E50").Copy
ws.Range("A1:B50").PasteSpecial Paste:=xlPasteValues
ws.Range("D:E").Delete Shift:=xlToLeft
End sub
Microsoft Links
CLEAN function
(additional nonprinting characters) Top ten ways to clean your data
Option Explicit
Sub cleanRange()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containinig this code
Dim ws As Worksheet: Set ws = wb.Worksheets(1)
Dim rg As Range: Set rg = ws.Range("A1:B50")
rg.Value = Application.Clean(rg.Value)
' These will not work:
'rg.Value = WorksheetFunction.Clean(rg.Value)
'rg.Value = WorksheetFunction.Clean(rg)
End Sub
Sub cleanRangeYourIdea()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containinig this code
Dim ws As Worksheet: Set ws = wb.Worksheets(1)
ws.Range("D1:E50").Value = "=CLEAN(RC[-3])"
ws.Range("A1:B50").Value = ws.Range("D1:E50").Value
ws.Range("D:E").Delete Shift:=xlToLeft
End Sub
Recreating a test case for your SUB, the minimun changes for your code to work are include in this snippet:
Sub clean()
Dim ws
Set ws = ThisWorkbook.Worksheets(1)
ws.Range("D1:D2") = "=CLEAN(RC[-3])"
ws.Range("E1:E2") = "=CLEAN(RC[-3])"
ws.Range("D1:E2").Copy
ws.Range("A1:B2").PasteSpecial Paste:=xlPasteValues
ws.Range("D:E").Delete Shift:=xlToLeft
End Sub
Nonetheless, considering that VBA is very permissive (specially without Option Explicit) and for following good code practice), here I put some more fixes:
Option Explicit
Sub Clean1()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
ws.Range("D1:D2").Formula = "=CLEAN(RC[-3])"
ws.Range("E1:E2").Formula = "=CLEAN(RC[-3])"
ws.Range("D1:E2").Copy
ws.Range("A1:B2").PasteSpecial Paste:=xlPasteValues
ws.Range("D:E").Delete Shift:=xlToLeft
Set ws = Nothing
End Sub
Both codes were tested and they work. Until this time, I did not touched the logic which could be optmized with vba functions but does not seem to bad to rely on excel functions
Sorry for the format of the post, I'm new here.
Edit: I deleted a bold markdown to a word.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.