问题描述
我在 Excel 中有 VBA 代码。我让它循环一列(E2:E100)。我只想将一个单元格(相同的引用)从一个工作表复制到另一个工作表。
Sub et()
Dim c As Range
Dim a As Range
Worksheets("CSV2").Select
'//loop it
For Each c In Range(Range("E2"),Range("E2").End(xlDown))
Set a = Worksheets("CSV").c '// The problem is here. I want the same range selection [c] as worksheet (CSV2) to the worksheet ("CSV") for the range selection [a]. I want to copy directly from [a] to [c]. I want to keep it in this format. Just help with the line here. Thanks.
If c.Value > 0 & c.Value < 3 Then
Sheets("CSV").Select
a.copy'// here I have it to copy the "CSV" sheet
Sheets("CSV2").Select
c.PasteSpecial Paste:=xlPasteValues'// here I want to paste it to the "CSV2" sheet
End If
Next
Worksheets("RETURN").Select
End Sub
解决方法
您应该避免选择工作表和单元格 (read this)
在我的代码中,我遵循了您通过使用 End(xlDown)
查找源范围的逻辑,但您应该考虑通过不同的方法 (read this) 查找一行中的最后一个单元格
阅读代码的注释并根据您的需要进行调整
Public Sub CopyValues()
' Set source sheet
Dim sourceSheet As Worksheet
Set sourceSheet = ThisWorkbook.Worksheets("CSV")
' Set target sheet
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.Worksheets("CSV2")
' Set source range
Dim sourceRange As Range
Set sourceRange = sourceSheet.Range("E2:E" & sourceSheet.Range("E2").End(xlDown).Row)
' Loop through cells in range
Dim sourceCell As Range
For Each sourceCell In sourceRange.Cells
If sourceCell.Value > 0 And sourceCell.Value < 3 Then
' This is one alternative to paste only values
targetSheet.Range(sourceCell.Address).Value = sourceCell.Value
' This is another alternative to paste the cell with value and formats (just comment previous line,and uncomment next to use it)
'sourceCell.Copy targetSheet.Range(sourceCell.Address)
End If
Next sourcell
End Sub
让我知道它是否有效