Collectionsについてご教授願います。
VBAで自動的にSELECT文を作成できるようにしたいのですが、Collectionsにうまく値が追記できません
入力データはexcel表で2列のデータ
部署コード | 品番コード |
---|---|
20 | 20001 |
10 | 2002 |
12 | 3001 |
10 | 4003 |
20 | 2100 |
出力先を一列開けた2行目からとして
SELECT * テーブル名 where bsyo = '20' AND hinban ='2001' AND hinban ='2100' order by DESC
SELECT * テーブル名 where bsyo = '10' AND hinban ='2002' AND hinban ='4003' order by DESC
SELECT * テーブル名 where bsyo = '22' AND hinban ='3001' order by DESC
上のような出力にしたいです。
VBA
1コード 2Sub Creatsql() 3 4 Dim srcsheet As worksheet 5 Set srcsheet = Activesheet 6 Dim targetRange As Range 7 Set targetRange = srcsheet.usedRange.offset(1,0) 8 Dim targetcell As variant 9 targetcell = targetRange 10 Dim maxrow As Integer 11 maxrow = targetRange.row.count 12 13 14 15 Dim hash 16 Set hash = CreateObject("Scripting.Dictionary") 17 18 Dim x 19 For x = 1 To maxrow 20 Dim valueList 21 Dim key 22 key = targetcell(x, 1) 23 Dim value 24 value = targetcell(x, 2) 25 If hash.Exists(key) Then 26 Set valueList = hash.Item(key) 27 valueList.Add value 28 Else 29 Set valueList = CreateObject("System.Collections.ArrayList") 30 hash.Add key, valueList 31 valueList.Add value 32 End If 33 Next 34 35 Dim i 36 Dim keys 37 keys = hash.Keys 38 39 Dim returnCount 40 returnCount = hash.Count - 1 41 42 Dim returnCells() 43 ReDim returnCells(returnCount) 44 45 For i = 1 To hash.Count - 1 46 Dim line 47 line = "Select * テーブル名 where bsyo = '" & keys(i)& " ' " & " " 48 Dim myArrayList 49 Set myArrayList = hash.Item(keys(i)) 50 Dim ii 51 Dim iMax : iMax = myArrayList.Count - 1 52 For ii=1 To iMax 53 line = line & " AND hinban =' " & myArrayList(ii) & " ' "& " " 54 Next 55 returnCells(i) = line 56 Next 57 CellsToArray = returnCells 58 Dim str 59 For Each line In returnCells 60 str = str & line & " order by DESC " &vbCr 61 Next 62 63 64End sub() 65 66
そもそもやり方が間違っていた場合は、そちらを指摘していただきたいです。
稚拙な説明文で申し訳ございませんが、よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/27 10:21