Exportar una tabla de SQL a Excel

Para obtener el string de conexión, ver este post


Sub ExportarSQL_A_Excel(sProducto, sPeriodo)
 Set conn = CreateObject("ADODB.Connection") 

 sNombreArch = "C:\temp\archivo.xlsx"
 
 conn.open "Provider=SQLNCLI.1;Persist Security Info=False;User ID=usuario;Password=password;Initial Catalog=nombreBase;Data Source=servidor\instancia"
  
 Set objCommand = CreateObject("ADODB.Command")
 Set objCommand.ActiveConnection = conn
 objCommand.CommandTimeout = 6000
 
  
 objCommand.CommandText = "SELECT * FROM tabla where condicion"
 
 Set rs = CreateObject("ADODB.recordset")
 Set rs = objCommand.Execute()
 
 
 Dim e
 Dim wb
 Dim sheet
 Dim sNombreArch
  
 Set e = CreateObject("Excel.Application")
  
 e.Workbooks.Add
 Set wb = e.ActiveWorkbook 
 Set sheet = wb.ActiveSheet
 
 nCantColumnas = rs.fields.count
 
 'Agrego los nombres de columnas
 For i = 0 to nCantColumnas - 1
  sheet.Range(Chr(64 + i + 1) & 1) = rs.fields(i).name
 Next
 
 sheet.Range("A2").CopyFromRecordset rs
  
 Set sheet = Nothing
 wb.SaveAs sNombreArch
 wb.Close
 Set wb = Nothing
 
 e.Quit
 Set e = Nothing
End Sub

No hay comentarios:

Publicar un comentario