在范围变量中存储动态范围

时间:2019-03-22 10:58:11

标签: excel vba

我试图从动态F列获取唯一值并将其存储在数组中。在将Selection变量设置为动态范围时,我的代码出现“ Object Required Error”。

Sub UniqueFilter()
Dim tmp As String
Dim arr() As String
Dim Selection As Range
Dim lrow As Long
Dim str As String
Dim cell As Range
Dim sht As Worksheet

Set sht = ThisWorkbook.Worksheets("14Feb19")
sht.Activate

'Set Selection = sht.Range(sht.Cells(1, 6), sht.Cells(Rows.Count, 6).End   (xlUp)).Select

lrow = shData.Range("F" & Rows.Count).End(xlUp).Row
Set Selection = sht.Range("F2:F" & lrow).Select



If Not Selection Is Nothing Then
For Each cell In Selection
  If (cell <> "") And (InStr(tmp, cell) = 0) Then
    tmp = tmp & cell & "|"
  End If
Next cell
End If

 If Len(tmp) > 0 Then tmp = Left(tmp, Len(tmp) - 1)

 arr = Split(tmp, "|")

End Sub

1 个答案:

答案 0 :(得分:0)

您完全不需要使用选择即可实现目标。 只需复制范围内容并将其转置为数组即可:

Sub UniqueFilter()
    Dim arr() As String
    Dim tmp As Variant
    Dim lrow As Long
    Dim sht As Worksheet
    Dim index As Integer
    Dim count As Integer

    Set sht = ThisWorkbook.Worksheets("14Feb19")
    sht.Activate

    lrow = sht.Range("F" & Rows.count).End(xlUp).Row

    'Copying and trasposing selected Range
    tmp = Application.Transpose(sht.Range("F2:F" & lrow).Value)

    'Cleaning from temp array all empty values
    count = 1
    For index = 1 To UBound(tmp, 1) - LBound(tmp, 1) + 1
        ReDim Preserve arr(1 To count)
        If tmp(index) <> "" Then
            arr(count) = tmp(index)
            count = count + 1
        End If
    Next

End Sub

(特别感谢@Nathan_Sav,他帮助简化了代码)

相关问题