excel VBA 中的循环列引用更改为另一个工作表

问题描述

我在 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

让我知道它是否有效

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...