Excel (VBA)

Excel VBAに関するフォーラムです。
  • 解決済みのトピックにはコメントできません。
このトピックは解決済みです。
質問

 
(Windows 10 Pro : Microsoft 365)
重複していないリストを作りたい
投稿日時: 25/03/24 15:10:24
投稿者: takatada72

お疲れさまです。
 
下記は、アクティブなExcel シートのD2-D100にあるデータを重複がないデータにして
F列に記載するようにAIにお願いしたのです。実際に、動かしてみると、次のコードの所
で、オブジェクトが必要(For Each cell In dict.Keys)とエラーになります。
何度も確認しているのですが、一項に修正ができずに、こちらにお願いした次第です。
※項目は、色々な会社名があるため、こちらでの公開は、できません。すみません。
 
何が問題なのでしょうか
お忙しいとは思いますが宜しくお願い致します。
 
 
'Dim ws As Worksheet
   Dim ws As Worksheet
    Dim dict As Object
    Dim cell As Range
    Dim outputCell As Range
     
    ' アクティブシートを設定
    Set ws = ActiveSheet
     
    ' Dictionaryオブジェクトを作成
    Set dict = CreateObject("Scripting.Dictionary")
     
    ' D2からD100までの範囲をループ
    For Each cell In ws.Range("D2:D100")
        If Not IsEmpty(cell.Value) Then
            ' 値がDictionaryに存在しない場合、追加
            If Not dict.exists(cell.Value) Then
                dict.Add cell.Value, Nothing
            End If
        End If
    Next cell
     
    ' F2セルから重複しない値を出力
    Set outputCell = ws.Range("F2")
    For Each cell In dict.Keys
        outputCell.Value = cell
        Set outputCell = outputCell.Offset(1, 0)
    Next cell
     
End Sub

回答
投稿日時: 25/03/24 15:50:54
投稿者: gombohori

 For Each cell In dict.Keys
 のループ変数になっているcellがRange型の変数だからです。
  
 ループ変数にはVariant型の変数を使いましょう

投稿日時: 25/03/24 16:08:55
投稿者: takatada72

ありがとうございました。
gombohoriさんの指摘された内容をAIにつげたら、無事、解決しました。
私は、何を言われているのかが全くわからなく、AIに任せていました。
 
下記のような回答になりましたので、無事、解決とさせて頂きます。
Dim ws As Worksheet
    Dim dict As Object
    Dim cell As Range
    Dim key As Variant
    Dim outputCell As Range
     
    ' アクティブシートを設定
    Set ws = ActiveSheet
     
    ' Dictionaryオブジェクトを作成
    Set dict = CreateObject("Scripting.Dictionary")
     
    ' D2からD8000までの範囲をループ
    For Each cell In ws.Range("D2:D8000")
        If Not IsEmpty(cell.Value) Then
            ' 値がDictionaryに存在しない場合、追加
            If Not dict.exists(cell.Value) Then
                dict.Add cell.Value, Nothing
            End If
        End If
    Next cell
     
    ' F2セルを出力の開始セルとして設定
    Set outputCell = ws.Range("F2")
     
    ' DictionaryのキーをF列に出力
    For Each key In dict.Keys
        outputCell.Value = key
        Set outputCell = outputCell.Offset(1, 0) ' 次のセルに移動
    Next key