電子書籍の厳選無料作品が豊富!

先日こちらで、Dictionaryを使用して別シートの離れた位置に値を転記する方法を教えていただいたのですが、さらに条件式を組み合わせる場合にはどのようにしたらよいか、お尋ねしたく投稿させていただきます。

現在は、prefShのB列をキーにしてA列、E列、T列をアイテムとして格納し、workShのA列、U列、C列にそれぞれ出力するプログラムになっております。(下記に記載)
これを、prefShのB列に対応する行(520行分)全て引っ張ってくるのではなく、
workShのB列に元々入っている値(512行分)を条件に、prefShのB列の範囲で検索してもし該当があれば、同じ行のA列、E列、T列を引っ張ってくる形に変更したいです。
(もともと、Findメソッドを使ってエラーが出たので、Dictionaryにしたという経緯があります)

大変恐れ入りますが、ご教示頂けますようお願い致します。

ーーー

Dim myDic As Object
Set myDic = CreateObject("Scripting.Dictionary")
Dim i As Long

With prefSh
For i = 2 To .Cells(.Rows.Count, 2).End(xlUp).Row
If Not myDic.Exists(.Cells(i, 2).Value) Then
myDic.Add .Cells(i, 2).Value, Array(.Cells(i, "A").Value, .Cells(i, "E").Value, .Cells(i, "T").Value)
End If
Next i
End With

Dim vKey As Variant
With workSh
i = 3
For Each vKey In myDic
.Cells(i, 2).Value = vKey
.Cells(i, "A").Value = myDic(vKey)(0)
.Cells(i, "U").Value = myDic(vKey)(1)
.Cells(i, "C").Value = myDic(vKey)(2)
i = i + 1
Next
End With
Set myDic = Nothing

'発見できなかった場合はNothingとなる

wb.Save ' 上書き保存

A 回答 (2件)

以下のようにしてください。


------------------------------------
Dim myDic As Object
Set myDic = CreateObject("Scripting.Dictionary")
Dim i As Long

With prefSh
For i = 2 To .Cells(.Rows.Count, 2).End(xlUp).Row
If Not myDic.exists(.Cells(i, 2).Value) Then
myDic.Add .Cells(i, 2).Value, Array(.Cells(i, "A").Value, .Cells(i, "E").Value, .Cells(i, "T").Value)
End If
Next i
End With

Dim vKey As Variant
With workSh
For i = 3 To .Cells(.Rows.Count, 2).End(xlUp).Row
vKey = .Cells(i, 2).Value
If myDic.exists(vKey) Then
.Cells(i, "A").Value = myDic(vKey)(0)
.Cells(i, "U").Value = myDic(vKey)(1)
.Cells(i, "C").Value = myDic(vKey)(2)
End If
Next
End With
Set myDic = Nothing

'発見できなかった場合はNothingとなる

wb.Save ' 上書き保存
    • good
    • 0
この回答へのお礼

教えていただいた内容で、解決できました!

vKey = .Cells(i, 2).Value
If myDic.exists(vKey) Then

このようにすれば良いのですね。
大変助かりました!ありがとうございました。

お礼日時:2021/02/19 18:49

こんにちは


ご自身で条件式は、コードに出来ますでしょうか?
出来ると思いますので参考程度で

myDic.Add .Cells(i, 2).Value, Array(.Cells(i, "A").Value, .Cells(i, "E").Value, .Cells(i, "T").Value)を変更したいと言う事だと思いますが、

myDic.Add 処理の前で 論理式の解を変数に入れて、
配列に入れている各値をその変数に変えれば良いと思います。
If ~.Cells(i, "A")>0 Then
変数1=.Cells(i, "A").Value

Else
変数1=~

myDic.Add .Cells(i, 2).Value, Array(変数1, 変数2,変数3)
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!