In my database, One itemNo can have multiple ItemID. I had a list of ItemNo in Excel sheet. I wrote a VB Macro to retrieve the ItemIDs for all the ItemNo. The issue is one ItemNo can have multiple ItemID. So I got CntItemID. I then wrote another macro to Copy multiple rows based on X CntItemID and inserted all the rows.
'Dim gcn As ADODB.connection
Set gcn = New ADODB.Connection
gcn.ConnectionTimeout = 30
gcn.CommandTimeout = 1000
Dim rst As New ADODB.Recordset
Dim strConnection As String
Dim wb As Workbook
Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = wb.Sheets("sheet2")
strConnection = "some SSMS server"
gcn.Open strConnection
CreateSQLConnection = True
Dim sqlStr As String
Dim row As Integer
Dim rowNum As String
Dim colNum As String
Dim strValue As String
Dim LastRow As Long
With ws
LastRow = .Range("A1").SpecialCells(xlCellTypeLastCell).row
End With
For row = 2 To 50
'For Each cell In rng.Cells
rowNum = "A" & CStr(row)
colNum = "B" & CStr(row)
'Set rg = ws.Range("rowNum").Value
'strValue = rg
strValue = ws.Range(rowNum).Value
'strValue = ws.Range("A2").Value
sqlStr = "SELECT DISTINCt ITEMS.ITEMID From dbo.Items Where ITEMS.ITEMNO = '" & strValue & "'"
rst.Open sqlStr, gcn
ws.Range(colNum).CopyFromRecordset rst
rst.Close
Next
gcn.Close
Set gcn = Nothing
Now my table looks like this.
ItemNO ItemID CntItemID
1 1 1
2 2 3
2 2 3
2 2 3
What i want is
ItemNO ItemID
1 1
2 2
2 3
2 4
I want to retrieve unique ItemIDs. I know SSMS automatically does that. But VBA is automatically retrieving first ItemID and repeating it.