On the userform there are a few textboxes. When an item in the combobox is chosen, only some of them stay visible. I want to step through visible textboxes at that time and fill them with data from SQL Server database. Items on the combobox list are identical with table names so it becomes a parameter in the SQL statement.
Debugging the code an error pops up while executing the statement (it runs fine in Management Studio). Maybe I'm missing some characters like ' or " or a whitespace (but the code isn't in red) or there is something wrong with the code and using recordset itself:
Private Sub cboTyp_AfterUpdate()
Dim rs As ADODB.Recordset
Dim Nazwa As String
Dim Skr As String
Dim Kolumna As String
Dim c As Control
On Error Resume Next
For Each c In Me.Controls
Select Case c.TabIndex
Case 3 To 10:
If c.Visible = True Then
Nazwa = c.Name
Skr = Right(Nazwa, 5)
On Error GoTo Nazwa_Initialize_Err:
Set rs = New ADODB.Recordset
rs.Open "SELECT DISTINCT c.name AS NazwaKolumny FROM sys.columns c JOIN sys.tables t ON c.object_id = t.object_id" & _
" WHERE c.name LIKE '%" & Skr & "';", _
con, adOpenStatic
Kolumna = rs.Fields("NazwaKolumny")
rs.Close
Set rs = Nothing
'Wyszukanie ostatniej wartości dla wybranej składowej
Set rs = New ADODB.Recordset
rs.Open "Declare @sqlCommand varchar(max)" & _
" Declare @columnName varchar(250)" & _
" Set @columnName = (SELECT DISTINCT c.name FROM sys.columns c JOIN sys.tables t ON c.object_id = t.object_id" & _
" WHERE c.name LIKE '%" & Skr & "')" & _
" Set @sqlCommand = 'SELECT [' + @columnName + ']' + " & _
" 'FROM [" & cboTyp.Value & "] WHERE ID = (SELECT MAX(ID) FROM [" & cboTyp.Value & "])'" & _
" Exec (@sqlCommand);", _
con, adOpenStatic
'Jeżeli brak wartości (zwróci NULL) oznacza to przejdź do normalnego wstawiania
If rs.RecordCount = 0 Then
c.SetFocus
'Jeśli znajdzie wartość to ją wstaw
Else
rs.MoveFirst
Do
Nazwa = rs.Fields(Kolumna)
rs.MoveNext
Loop Until rs.EOF
End If
End If
End Select
Next
On Error GoTo 0
'Opuszczanie pola - zamknięcie i wyczyszczenie Recordset
Nazwa_Initialize_Exit:
On Error Resume Next
rs.Close
Set rs = Nothing
Exit Sub
Dim Skrócona As String