[英]Copy/paste value a range in VBA excel
In order to apply the clean function to the range A1:B50 in my excel sheet, I wrote the code below.为了将干净的 function 应用到我的 excel 表中的范围 A1:B50,我编写了下面的代码。 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) CLEAN function
(附加非打印字符)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 重新创建一个测试用例,您的代码工作的最小更改包含在此代码段中:
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:尽管如此,考虑到 VBA 是非常宽松的(特别是没有 Option Explicit 并且遵循良好的代码实践),这里我提出了更多修复:
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
直到此时,我还没有触及可以使用 vba 函数优化的逻辑,但依赖 excel 函数似乎还不错
Sorry for the format of the post, I'm new here.抱歉帖子的格式,我是新来的。
Edit: I deleted a bold markdown to a word.编辑:我删除了一个粗体字 markdown。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.