DB trusted_connection无法正常工作

时间:2016-05-09 04:53:24

标签: excel vba excel-vba

Sub INTL()   
  Dim conn As ADODB.Connection 
  Dim rec1 As ADODB.Recordset 
  Dim thisSql As String  
  Set conn = New ADODB.Connection 
  Dim sConn As String   sConn = "Provider=SQLOLEDB;Trusted_Connection=Yes;Server=mydb;trusted_connection=yes" conn.Open sConn      
  'Set and Excecute SQL Command'     
  thisSql = "select top 5 * from useraccount"               
  'Open Rcordset'     
  Set rec1 = New ADODB.Recordset        
  rec1.Open thisSql, conn       
  'Copy Data to Excel'         
  ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)  
End Sub

代码未在excel中编译,错误:Sub或函数未定义

1 个答案:

答案 0 :(得分:1)

如果这在您的IDE中完全如下:

Dim sConn As String   sConn = "Provider=SQLOLEDB;Trusted_Connection=Yes;Server=mydb;trusted_connection=yes" conn.Open sConn      

然后你错过了指示分隔符,或更好的单独行:

Dim sConn As String
sConn = "Provider=SQLOLEDB;Trusted_Connection=Yes;Server=mydb;trusted_connection=yes"
conn.Open sConn      

另外,在这一行:

ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)  

这些括号是按值(即对象指针的副本)强制传递objMyRecordsetCopyFromRecordset方法。这将是一个更典型的电话:

ActiveSheet.Range("A1").CopyFromRecordset objMyRecordset

如果CopyFromRecordset正在记录集ByVal,那么它会按值传递。如果它正在接受ByRef,那么它将通过引用传递。强制ByVal通常不需要