【问题标题】:Selecting the rows of each cell within a range object (VBA)选择范围对象中每个单元格的行 (VBA)
【发布时间】:2021-06-28 14:30:23
【问题描述】:

我正在尝试将一系列数据从一个工作表复制到另一个工作表。范围由与设定值匹配的 A 列中的值定义。我已经能够将具有指定值的每个单元格添加到范围对象中,但是我现在必须选择范围对象中单元格行中的所有数据,以便将它们复制到另一张表中。有什么建议吗?

另外,我对 VBA 很陌生,所以我确信我的代码格式很糟糕,但我真的只需要解决这个特殊问题。感谢您的帮助!

Dim allAsNum As Range
Dim currAsNum As Range
Dim asnum
Dim j

Sheets("Full Log").Select
asnum = "searchingvalue"
    For j = 2 To CInt(Cells(Rows.Count, "A").End(xlUp).Row)
    If Range(Sheets("Full Log").Cells.Address).Cells(j, 1).Value = asnum Then
        If allAsNum Is Nothing Then
            Set allAsNum = Range(Sheets("Full Log").Cells.Address).Cells(j, 1)
        Else
            Set allAsNum = Union(allAsNum, Range(Sheets("Full Log").Cells.Address).Cells(j, 1))
        End If
    End If
    Next j
    
    Set currAsNum = allAsNum.Rows 'This is the line that I can't figure out
    currAsNum.Select

【问题讨论】:

  • allAsNum.EntireRow.Copy YourTargetRange
  • AdvancedFilter 是一种根据选择标准复制数据的更有效方法。

标签: vba select range


【解决方案1】:

斯科特·克兰纳是对的。但是,对您的代码的一些说明

a) 作为初学者不能不缩进代码。只需按照规则在每个SubIfForWith 语句的缩进级别上加 1(此列表不完整,但您明白了)。在匹配的End-语句中减去 1。每个缩进使用<TAB>

b) 不要使用选择。必须链接到How to avoid using Select in Excel VBA

c) 您使用正确的技术来获取最后一行。但是,这已经返回了一个 Long 值,无需使用 CInt 进行转换。出于调试原因,最好在使用前将其写入变量。顺便说一句,您应该将变量 j 声明为 Long(也许考虑一个更好的名称)。

d) 您读取单元格的技术有效,但不必要地复杂。只需使用Cells(j, 1)

代码可能如下所示:

Const asnum = "searchingvalue"
Dim allAsNum As Range
Dim rowCount as long, curRow as long

With ThisWorkbook.Sheets("Full Log")   
    rowCount = .Cells(.Rows.Count, "A").End(xlUp).Row
    For curRow = 2 To rowCount 
        If .Cells(curRow , 1).Value = asnum Then
            If allAsNum Is Nothing Then
                Set allAsNum = .Cells(curRow, 1)
            Else
                Set allAsNum = Union(allAsNum, .Cells(curRow, 1)) 
            End If
        End If
    Next curRow 
End With
' (The destination of the following copy needs to be adapted to your needs)
allAsNum.EntireRow.Copy ThisWorkbook.Sheets("Sheet1").Range("A1")

【讨论】:

  • 一个注意事项,我没有说明。如果使用EntireRow,您的粘贴必须在A 列中。行可以更改,但列必须是第一列,否则您将收到错误,因为您无法将整行粘贴到部分行中。
猜你喜欢
  • 2017-07-22
  • 2012-02-11
  • 2012-08-17
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多