← Foro de Visual Basic

Datos de VBasic a Excel

Hilo en el foro de Visual Basic · 16 de Noviembre del 2004 · 2 respuestas
Eugenio16 de Noviembre del 2004
Pregunta
Por favor, necesito un código sencillo para importar-exportar datos de VBasic a Excel.
Muchas Gracias !

Respuestas 2

Luis Atondo16 de Noviembre del 2004
' Importar datos de vb a excel
Sub DatosenExcel()
Plantilla = App.Path + "Listados.xlt"
AbreExcel 'procedimiento para abrir excel
Set XlBook = XlApp.Workbooks.open(Plantilla)
Set XlSheet = XlBook.Worksheets(1)
XlBook.Unprotect "clave" 'desproteges el libro
XlSheet.Unprotect "atd"
XlSheet.Activate
Set celda = XlBook.Sheets(1).cells
'empieza el paso de datos a excel
For x = 1 To ListView1.ListItems.Count
celda.cells(reng, 3) = ListView1.ListItems(x).Text
celda.cells(reng, 4) = ListView1.ListItems(x).ListSubItems(1).Text
celda.cells(reng, 5) = ListView1.ListItems(x).ListSubItems(2).Text
reng = reng + 1
Next
' Fin de paso de datos
XlSheet.Protect "Clave"
XlBook.Activate
XlBook.Protect "clave", True, True ' proteges de nuevo el libro
XlApp.WindowState = 3 'maximizar la pantalla
XlApp.Visible = True
XlBook.PrintOut , , , True
XlBook.Close False
XlApp.Application.Quit
LimpiaVariablesExcel
End Sub

'esto lo declaras en un modulo...

Declare Function FindWindow Lib "user32" Alias _
"FindWindowA" (ByVal lpClassName As String, _
ByVal lpWindowName As Long) As Long

Declare Function SendMessage Lib "user32" Alias _
"SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long

Sub AbreExcel()
On Error Resume Next
DetectExcel
Set XlApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set XlApp = CreateObject("Excel.Application")
Err.Clear ' Clear Err object in case error occurred.
End If
XlApp.AskToUpdateLinks = False ' para automatizar el que no pregunte si actualizar vinculos
XlApp.Calculation = xlAutomatic ' para automatizar el calculo automatico
XlApp.MaxChange = 0.001
XlApp.AutomationSecurity = msoAutomationSecurityLow
XlApp.DisplayAlerts = False
XlApp.Caption = "VisionDat"
End Sub
' para limpiar todas las variables y que no te quede excel en memoria
Sub LimpiaVariablesExcel()
On Error Resume Next
Set XlBook = Nothing
Set XlSheet = Nothing
Set celda = Nothing
Plantilla = ""
DetectExcel
If NoExcel = True Then
XlApp.Application.Quit
Set XlApp = Nothing
End If
End Sub
Luis Atondo16 de Noviembre del 2004
El Ejemplo anterior... te importa datos de vb a excel desde un listview a un listado en excel...

si deseas hacer lo contrario.. utilizas casi el mismo codigo, solo que leeras la informacion de excel... no se si me explique.. pero algo asi es...
¿Buscas más hilos como este? Mira el foro de Visual Basic o usa el buscador.