Excel의 VBA 연결 데이터베이스 방법 - 네트워크에서 발췌

4572 단어 Excel
Sub GetData()     

     Dim strConn As String, strSQL As String 

     Dim conn As ADODB.Connection 

     Dim ds As ADODB.Recordset 

     Dim col As Integer 

     

    '       

    Cells.Clear 

     

    '       

    strConn = "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=name;Password=pwd;Initial Catalog=dataname;Data Source=servername" 

    '  

     strSQL = "select * from table1" 

     Set conn = New ADODB.Connection 

     Set ds = New ADODB.Recordset 

    '  

     conn.Open strConn 

     

     With ds 

   '  

         .Open strSQL, conn 

         

         '  

         For col = 0 To ds.Fields.Count - 1 

    ' Offset(0, col)  

             Range("A1").Offset(0, col).Value = ds.Fields(col).Name 

         Next 

         

        '  

         Range("a1").Offset(1, 0).CopyFromRecordset ds 

     End With 

     

    '  

     Set ds = Nothing 

     conn.Close 

     Set conn = Nothing 

End Sub 

 
참고:
1. 저장할 때 다음과 같은 메시지를 볼 수 있습니다. "Privacy warning: This document contains macros, ActiveX Controls, XML expansion pack..."
해결 방법:
경고를 취소하려면 현재 Excel->Options->Trust Center->Trust Center Settings...->Privacy Options, "Remove Personal information from file properties on save"확인란을 선택 취소합니다.
 
2. 저장할 때 다음 메시지가 표시될 수 있습니다. "
the following features cannot be saved in macro-free workbooks  vb project  to save a file with these features click no  and then choose a macro-enabled file type in the file type list. to continue saving as a macro-free workbook, click yes"
해결 방법:
1. 열린 파일은 읽기 전용입니다. 2.열려 있는 파일은 매크로를 사용하지 않는 작업 얇은 xlsx입니다. 매크로를 사용했기 때문에 xlsm로 저장해야 한다는 것을 알립니다

좋은 웹페이지 즐겨찾기