I have written the below vba function to query a sql database called Nelus, and a table called ShareName. The table has 2 columns, ShortCode and Name. The function takes the company code as parameter e.g. "c01", and should return the company name e.g. "company01".
- When I run the vba code as a
Sub, it works (commented out in below code). - When I try to run it as a
Functionas below, it returns a value of'0', instead of e.g."company01".
Any suggestions how to get it to run as a function? Thanks! Nelus
'Sub TestSQLQuery()
Function ShareInfo(CompCode As String)
Dim SQL As String
Dim RS As ADODB.Recordset
Dim Field As ADODB.Field
'Dim CompCode As String
Dim Server, Database As String
Dim Connect As Boolean
'CompCode = "c01"
SQL = "select p.[Name]" & _
"from dbo.['ShareName'] p " & _
"where p.ShortCode = '" & CompCode & "' "
Server = "npc\SQLEXPRESS"
Database = "Nelus"
Set CN = New ADODB.Connection
On Error Resume Next
With CN
.ConnectionString = "Provider=SQLOLEDB.1;" & _
"Integrated Security=SSPI;" & _
"Server=" & Server & ";" & _
"Database=" & Database & ";"
.Open
End With
If CN.State = 0 Then
Connect = False
Else
Connect = True
End If
If Connect = False Then
MsgBox "Could Not Connect!"
Else
Set RS = New ADODB.Recordset
RS.Open SQL, CN, adOpenStatic, adLockReadOnly, adCmdText
If RS.State Then
Cells(ActiveCell.Row, ActiveCell.Column).CopyFromRecordset RS
Set RS = Nothing
End If
CN.Close
End If
End Function
'End Sub