79703806

Date: 2025-07-16 17:39:12
Score: 0.5
Natty:
Report link

Due to @Tim William's insight that a function can make no changes to the calling worksheet, modified the code to return the desired values obtained by a SQL query.

Function FillDD(DocID As String) As String       '----work in progress
    Dim wbMacro As Workbook, wsFix As Worksheet
    Dim conn As ADODB.Connection, recs As ADODB.Recordset
    Dim vTestField As String
    Set conn = New ADODB.Connection
    Set recs = New ADODB.Recordset
    vx = ActiveWorkbook.Name
    Set wbMacro = Workbooks(vx)
    Set wsFix = wbMacro.Sheets("DocFixes")
    'This sets vRow to the row the function is being called from
    vRow = Application.ThisCell.Row
    vServer = "<Server>"
    vDatabase = "<DB>"
    vQuery = "SELECT AND FROM Clauses WHERE DocumentID = '" & DocID & "'"
    On Error GoTo EH
    vQuery = "SET NOCOUNT ON " & Replace(Replace(vQuery, Chr(13), ""), Chr(10), " ")
    conn.ConnectionString = "DRIVER=SQL Server;SERVER=" & vServer & ";Trusted_Connection=Yes;APP=Microsoft Office 2016;DATABASE=" & vDatabase
    conn.Open
    recs.CursorType = adOpenKeyset
    recs.Open vQuery, conn
EH:
    If 0 < Len(Err.Description) Then MsgBox "Error#: " & Err.Number & " Description: " & Err.Description
    'Get first of four fields
    vTestField = recs.Fields.Item(0).Value
    'First field will be empty if error, if expected length concatinate next three fields separated by comma and return
    If Len(vTestField) = 9 Then
        vx = "'" & vTestField
        vTestField = recs.Fields.Item(1).Value
        vx = vx & ",'" & vTestField
        vTestField = recs.Fields.Item(2).Value
        vx = vx & ",'" & vTestField
        vTestField = recs.Fields.Item(3).Value
        vx = vx & ",'" & vTestField
        FillDD = vx
    Else
        FillDD = "Fail"
    End If
    recs.Close
    conn.Close
    Set conn = Nothing
    Set recs = Nothing
End Function
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Tim
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Jan