[英]VBA - Excel Copy and paste range with criteria
I want to copy a range in Sheet1 range A1:A100 where in the each cells filled with value like "Animal", "Plant", "Rock", and "Sand". 我想在Sheet1范围A1:A100中复制一个范围,其中每个单元格中都填充了“动物”,“植物”,“岩石”和“沙”之类的值。 Then, I want paste in Sheet2 range B1:B100 with conditions if the value at Range A1:A100 is "Animal" paste with "1", if the value is "Plant" paste with "2", ect. 然后,我要在Sheet2范围B1:B100中粘贴条件,条件是范围A1:A100的值为“动物”粘贴为“ 1”,如果值为“植物”粘贴为“ 2”,等等。
How I write the VBA code? 我如何编写VBA代码? With simple and reducing memory usage. 具有简单且减少内存使用的特点。 My code : 我的代码:
Sub copyrange()
Dim i As Long
Dim lRw As Long
Dim lRw_2 As Long
Application.ScreenUpdating = False
lRw = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row
ThisWorkbook.Sheets("Sheet1").Activate
For i = 1 To lRw
Range("A" & i).Copy
lRw_2 = Sheets("Sheet2").Cells(Rows.Count, "B").End(xlUp).Row + 1
Sheets("Sheet1").Activate
'I not sure for this one, the code is too long
Select Case ThisWorkbook.Sheets("sheet1").Range("A" & i).Value
Case "Animal"
With Sheets("Sheet2").Range("B" & lRw_2)
.Value = 1
End With
Case "Plant"
With Sheets("Sheet2").Range("B" & lRw_2)
.Value = 2
End With
Case "Rock"
With Sheets("Sheet2").Range("B" & lRw_2)
.Value = 3
End With
Case "Sand"
With Sheets("Sheet2").Range("B" & lRw_2)
.Value = 4
End With
End Select
Sheets("Sheet1").Activate
Next i
Application.ScreenUpdating = True
End Sub
Thanks in advance. 提前致谢。
Try this: 尝试这个:
Option Explicit
Public Sub replaceItems()
Application.ScreenUpdating = False
With Sheets(2).Range("B1:B100")
.Value2 = Sheets(1).Range("A1:A100").Value2
.Replace What:="Animal", Replacement:=1, LookAt:=xlWhole
.Replace What:="Plant", Replacement:=2, LookAt:=xlWhole
.Replace What:="Rock", Replacement:=3, LookAt:=xlWhole
.Replace What:="Sand", Replacement:=4, LookAt:=xlWhole
End With
Application.ScreenUpdating = True
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.