具有可变列和lastrow的范围不起作用

时间:2018-08-16 13:53:57

标签: vba excel-vba variables range

我有一个宏,它可以找到标题并将列放在变量中,然后它创建数据集合并删除重复的值,并将结果粘贴到另一个固定位置。我想不通做每个单元的生产线。我发现的原始宏包含“对于.range(“ A1:A”&rlastcell)中的每个单元格,它在A列上正常工作。我需要将该列设置为变量,因此它将使用所有值从该列中删除重复项。

这是我的代码。预先谢谢你。

    Sub copyNoDuplicates()
Dim rLastCell As Range
Dim cell As Range, i As Long
Dim AccTeam As Collection
Dim lCol As Long
Dim rFind As Range

Set rFind = ActiveWorkbook.Sheets("sheet2").Rows("1:3").Find(What:="Accountable Team", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
lCol = rFind.Column

Set AccTeam = New Collection
With ActiveWorkbook.Worksheets("Sheet2")
    'Find last used cell
    Set rLastCell = .Range("A65536").End(xlUp)
    'Parse every animal and put it in a collection
    On Error Resume Next
    For Each cell In .Cells(rLastCell, lCol)
        AccTeam.Add cell.Value, CStr(cell.Value)
    Next cell
    On Error GoTo 0
End With
With ActiveWorkbook.Worksheets("Sheet2")
    For i = 1 To AccTeam.Count
        .Range("D" & i).Value = AccTeam(i)
    Next i
End With
End Sub

3 个答案:

答案 0 :(得分:0)

您很可能需要切换到使用Cells()结构以节省时间/精力。

Dim i As Range, j As Long, lr As Long
Set i = Range(Rows(1), Rows(3)).Find(What:="Accountable Team", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
j = i.Column
lr = Cells(Rows.Count, j).End(xlUp).Row
Range(Cells(2, j), Cells(lr, j)).Value = "" 'assumes header in row 1

在给定找到的列#的情况下,使用A1:A和rlastcell作为范围将需要将找到的具有适当标题的列转换回字母,在我看来这似乎是一种浪费。

答案 1 :(得分:0)

类似于西里尔的想法。使用“查找”时,最好先检查是否找到了搜索词,以避免代码错误。

Sub copyNoDuplicates()

Dim rLastCell As Range
Dim cell As Range, i As Long
Dim AccTeam As Collection
Dim lCol As Long
Dim rFind As Range

With ActiveWorkbook.Worksheets("Sheet2")
    Set rFind = .Rows("1:3").Find(What:="Accountable Team", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
    If Not rFind Is Nothing Then
        lCol = rFind.Column
        Set AccTeam = New Collection
        'Use the relevant column to find last cell
        Set rLastCell = .Cells(Rows.Count, lCol).End(xlUp)
        On Error Resume Next
        'Range from 1st row of column to last
        For Each cell In .Range(.Cells(1, lCol), rLastCell)
            AccTeam.Add cell.Value, CStr(cell.Value)
        Next cell
        On Error GoTo 0
        For i = 1 To AccTeam.Count
            .Range("D" & i).Value = AccTeam(i)
        Next i
    End If
End With

End Sub

答案 2 :(得分:0)

使用:

For Each cell In .Range("A1:A" & rLastCell.Row).Columns(lCol)

因此使用lCol作为A列的偏移列