elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP)
| | | |-+  Programación Visual Basic (Moderadores: LeandroA, seba123neo)
| | | | |-+  [Src][Cls] ManipulacionSimple Excel || Cls_ExcelAplication [Release Memory]
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Src][Cls] ManipulacionSimple Excel || Cls_ExcelAplication [Release Memory]  (Leído 3,728 veces)
BlackZeroX
Wiki

Desconectado Desconectado

Mensajes: 3.158


I'Love...!¡.


Ver Perfil WWW
[Src][Cls] ManipulacionSimple Excel || Cls_ExcelAplication [Release Memory]
« en: 20 Junio 2010, 03:02 am »

Bueno solo traigo este modulo de clase que sirve para que no se quede en memoria la aplicación Excel cuando la creamos con CreateObject(), por ejemplo, hace poco en este Post

http://foro.elhacker.net/programacion_visual_basic/como_exportar_mshflexgrid1_a_excel_expertos_en_vb60-t297037.0.html

Daba la cuestión que siempre para debugear (para ayudarle a Hunter18) se me quedaba la aplicación Abierta y la memoria bien gracias!¡.

Las funciones qué tiene integradas son dos:

Libro()
Hoja()

En el código fuente ya esta con sus descripciones de uso!¡, todo lo demás esta en cuestión vba (abran excel y hay mas o menos vean las propiedades qué podrán usar en vb6 con el objecto qué provenga del createObject("Excel.Application")).

Cls_ExcelAplication.cls
Código
  1. '
  2. '   /////////////////////////////////////////////////////////////
  3. '   // Autor:   BlackZeroX ( Ortega Avila Miguel Angel )       //
  4. '   //                                                         //
  5. '   // Web:     http://InfrAngeluX.Sytes.Net/                  //
  6. '   //                                                         //
  7. '   //    |-> Pueden Distribuir Este Codigo siempre y cuando   //
  8. '   // no se eliminen los creditos originales de este codigo   //
  9. '   // No importando que sea modificado/editado o engrandesido //
  10. '   // o achicado, si es en base a este codigo                 //
  11. '   /////////////////////////////////////////////////////////////
  12. '   //                                                         //
  13. '   //                  Cls_ExcelAplication.cls                //
  14. '   //                                                         //
  15. '   /////////////////////////////////////////////////////////////
  16. '
  17. Rem Opciones.
  18. Option Explicit
  19. Rem End Opciones.
  20.  
  21. Rem Eventos.
  22. Event Errores(ByRef Err As ErrObject)
  23. Rem End Eventos.
  24.  
  25. Rem Declaraciones.
  26. Private Obj_Excel               As Object
  27. Rem End Declaraciones.
  28.  
  29.  
  30.  
  31.  
  32.  
  33. Rem Propiedades.
  34.  
  35. '   //  <Metodo Tipo = Propetiedad Acceso=Publico>
  36. '   //      <Objetivo>
  37. '   //          *   Obtiene la instancia de la aplicacion!¡..
  38. '   //      </Objetivo>
  39. '   //      <Return Tipo=Object Parcial={Excel.Application}>
  40. '   //          Regresa el Objeto {Excel.Application}.
  41. '   //      </Return>
  42. '   //  </Metodo>
  43. Public Property Get Excel() As Object
  44.    Set Excel = Obj_Excel
  45. End Property
  46.  
  47. '   //  <Metodo Tipo = Propetiedad Acceso=Publico>
  48. '   //      <Objetivo>
  49. '   //          *   Obtiene un libro segun los criterios, 1 HOJA!¡..
  50. '   //      </Objetivo>
  51. '   //      <Evaluaciones>
  52. '   //          *   Si no existe el libro se crea uno nuevo!¡, solo por busqueda {Index&}.
  53. '   //          *   Si no se ingresa ningun parametro Opcional se crea un nuevo libro y es devuelto!¡.
  54. '   //      </Evaluaciones>
  55. '   //      <Parametros>
  56. '   //          <Opcional Nombre=Index& Datotipo=Long Predeterminado=-1>
  57. '   //              indice del libro a buscar!¡.
  58. '   //          </Opcional>
  59. '   //          <Opcional Nombre=Hoja Datotipo=Object Predeterminado=Nothing>
  60. '   //              Ignora el parametro {Index&} y procede a buscar en TODOS los libros abiertos la hoja deseada.
  61. '   //          </Opcional>
  62. '   //      </Parametros>
  63. '   //      <Return Tipo=Object Parcial=Workbook>
  64. '   //          Regresa el libro {Workbook} deseado!¡.
  65. '   //      </Return>
  66. '   //  </Metodo>
  67. Public Property Get Libro(Optional ByRef Index& = -1, Optional ByRef Hoja As Object = Nothing) As Object
  68. On Error GoTo EventoError
  69. Dim Lng_IndexLibro&
  70. Dim Lng_IndexHoja&
  71.  
  72.    If Index& <= 0 Then
  73.        Index& = Excel.Workbooks.Count
  74.    End If
  75.  
  76.    If Index& <= 0 And Hoja Is Nothing Then
  77.        Index& = 1
  78.        Set Libro = Excel.Workbooks.Add
  79.        With Libro
  80.            For Lng_IndexHoja& = 1 To .Worksheets.Count - 1
  81.                .Worksheets(Lng_IndexHoja&).Delete
  82.            Next
  83.        End With
  84.    Else
  85.        If Hoja Is Nothing Then
  86.            Set Libro = Excel.Workbooks(Index&)
  87.        Else
  88.            With Excel
  89.                For Lng_IndexLibro& = 1 To .Workbooks.Count
  90.                    With .Workbooks(Lng_IndexLibro&)
  91.                        For Lng_IndexHoja& = 1 To .Worksheets.Count
  92.                            If .Worksheets(Lng_IndexHoja&) Is Hoja Then
  93.                                Set Libro = Excel.Workbooks(Lng_IndexHoja&)
  94.                                Index& = Lng_IndexLibro&
  95.                                Exit Property
  96.                            End If
  97.                        Next
  98.                    End With
  99.                Next
  100.            End With
  101.        End If
  102.    End If
  103. Exit Property
  104. EventoError:
  105.    RaiseEvent Errores(Err)
  106.    Err.Clear
  107. End Property
  108.  
  109.  
  110. '   //  <Metodo Tipo = Propetiedad Acceso=Publico>
  111. '   //      <Objetivo>
  112. '   //          *   Obtiene una Hoja de libro segun los criterios.
  113. '   //      </Objetivo>
  114. '   //      <Evaluaciones>
  115. '   //          *   Si no existen Libros se crea uno nuevo.
  116. '   //          *   Si no existen Hojas se crea una nueva en el libro.
  117. '   //          *   Si no se ingresa ningun parametro Opcional se crea un nuevo Libro, y Hoja son devueltos.
  118. '   //      </Evaluaciones>
  119. '   //      <Parametros>
  120. '   //          <Opcional Nombre=Index& Datotipo=Long Predeterminado=-1>
  121. '   //              indice de la Hoja a buscar!¡.
  122. '   //              Si el parametro es superior a la cantidad de hojas en el libro o si es negativo
  123. '   //              Creara una nueva Hoja.
  124. '   //          </Opcional>
  125. '   //          <Opcional Nombre=Book Datotipo=Object Predeterminado=Nothing>
  126. '   //              Indica el libro donde se buscada, si se deja {Nothing} creara uno nuevo
  127. '   //              y en el parametro {index&} devolvera la posicion de la hoja.
  128. '   //          </Opcional>
  129. '   //      </Parametros>
  130. '   //      <Return Tipo=Object Parcial=Workbook>
  131. '   //          Regresa la Hoja {Worksheets} Indicada.
  132. '   //          Parametro {Book}    Regresa el libro en dado caso que no se aya indicado alguno.
  133. '   //          PArametro {Index&}  Regresa el index de la hoja en el libro indicado en el parametro {Book}, igual si fuese Creado.
  134. '   //          Regresa el
  135. '   //      </Return>
  136. '   //  </Metodo>
  137. Public Property Get Hoja(Optional ByRef Index& = -1, Optional ByRef Book As Object = Nothing) As Object
  138. On Error GoTo EventoError
  139. Dim Lng_IndexLibro&
  140. Dim Lng_IndexHoja&
  141.  
  142.    If Book Is Nothing Then
  143.        Set Book = Libro(Index&)
  144.    End If
  145.    If Index& <= 0 Then
  146.        Set Hoja = Book.Worksheets.Add
  147.        Index& = Book.Worksheets.Count
  148.    Else
  149.        With Book
  150.            If .Worksheets.Count < Index& Then
  151.                Index& = .Worksheets.Count
  152.            End If
  153.            Set Hoja = .Worksheets(Index&)
  154.        End With
  155.    End If
  156.  
  157. Exit Property
  158. EventoError:
  159.    RaiseEvent Errores(Err)
  160.    Err.Clear
  161. End Property
  162. Rem End Propiedades.
  163.  
  164.  
  165.  
  166.  
  167.  
  168. Rem Eventos de Modulo de Clase.
  169.  
  170. '   //  <Metodo Tipo=Proceso Acceso=Local>
  171. '   //      <Objetivo>
  172. '   //          *   Crea la instancia de la aplicacion!¡..
  173. '   //      </Objetivo>
  174. '   //  </Metodo>
  175. Private Sub Class_Initialize()
  176. On Error GoTo EventoError
  177.    Set Obj_Excel = CreateObject("Excel.Application")
  178. Exit Sub
  179. EventoError:
  180.    RaiseEvent Errores(Err)
  181.    Err.Clear
  182. End Sub
  183.  
  184. '   //  <Metodo Tipo=Proceso Acceso=Local>
  185. '   //      <Objetivo>
  186. '   //          *   Liberacion de Memoria.
  187. '   //      </Objetivo>
  188. '   //      <Evaluaciones>
  189. '   //          *   Si hay libros abiertos o cargado los descarga.
  190. '   //          *   Si existe la instancia de la aplicacion la clierra
  191. '   //      </Evaluaciones>
  192. '   //  </Metodo>
  193. Private Sub Class_Terminate()
  194. On Error Resume Next
  195. Dim Lng_IndexLibro&
  196.  
  197.    With Excel
  198.        For Lng_IndexLibro& = 1 To .Worksheets.Count
  199.            .Worksheets(Lng_IndexLibro&).Close
  200.            Set .Libro = Nothing
  201.        Next
  202.    End With
  203.  
  204.    If Not Obj_Excel Is Nothing Then
  205.        Call Obj_Excel.Quit
  206.        Set Obj_Excel = Nothing
  207.    End If
  208.    Err.Clear
  209. End Sub
  210. Rem End Eventos de Modulo de Clase.
  211.  
  212.  

Ejemplo!¡.

Código
  1.  
  2. '
  3. '   /////////////////////////////////////////////////////////////
  4. '   // Autor:   BlackZeroX ( Ortega Avila Miguel Angel )       //
  5. '   //                                                         //
  6. '   // Web:     http://InfrAngeluX.Sytes.Net/                  //
  7. '   //                                                         //
  8. '   //    |-> Pueden Distribuir Este Codigo siempre y cuando   //
  9. '   // no se eliminen los creditos originales de este codigo   //
  10. '   // No importando que sea modificado/editado o engrandesido //
  11. '   // o achicado, si es en base a este codigo                 //
  12. '   /////////////////////////////////////////////////////////////
  13. '   //                                                         //
  14. '   //            Ejemplo: Cls_ExcelAplication.cls             //
  15. '   //                                                         //
  16. '   /////////////////////////////////////////////////////////////
  17. '
  18. Option Explicit
  19.  
  20. Private WithEvents InstanciaExcel   As Cls_ExcelAplication      '   //  Solo para controlar Errores xP!¡.
  21.  
  22. Private Sub Form_Load()
  23. 'Dim InstanciaExcel                  As Cls_ExcelAplication     '   //  Declaracion Recomendada!¡.
  24. Dim Obj_Hoja                        As Object
  25. Const SaveOn$ = "c:\BlackZeroX.xls"
  26.    Set InstanciaExcel = New Cls_ExcelAplication
  27.    With InstanciaExcel
  28.        Set Obj_Hoja = .Hoja                                    '   //  Creamos una libro y hoja
  29.        Obj_Hoja.cells(1, 1) = "BlackZeroX"
  30.        Obj_Hoja.cells(2, 1) = "Http://InfrAngeluX.sytes.net"
  31.        Obj_Hoja.cells(3, 1) = "Dulce Infierno Lunar!¡."
  32.        .Libro(, Obj_Hoja).Close True, SaveOn$                  '   //  Guardamos.
  33.        Set Obj_Hoja = Nothing                                  '   //  Terminamos la instancia!¡.
  34.    End With
  35.    Set InstanciaExcel = Nothing
  36.    Call vbShell(SaveOn$, False)
  37. End Sub
  38. Public Function vbShell(StrPath As String, Optional ByVal hHiden As Boolean = False) As Boolean
  39. Dim ret                     As Object
  40.    Set ret = CreateObject("Shell.Application", "")
  41.    vbShell = Not ret Is Nothing
  42.    If Not ret Is Nothing And CBool(Dir(StrPath) <> "") Then
  43.        Call ret.ShellExecute(StrPath, "", "", "open", Abs(Not hHiden))
  44.        Set ret = Nothing
  45.    End If
  46. End Function
  47.  
  48.  
  49. Private Sub InstanciaExcel_Errores(ByRef Err As ErrObject)
  50.    Call DebugerVB(Err)
  51. End Sub
  52. Private Sub DebugerVB(ByRef Err As ErrObject)
  53.    With Err
  54.        Debug.Print ""
  55.        Debug.Print String$(30, "-")
  56.        Debug.Print "Source:"; .Source
  57.        Debug.Print "Number:"; .Number
  58.        Debug.Print "Description:"; .Description
  59.        Debug.Print String$(30, "-")
  60.        Debug.Print ""
  61.    End With
  62. End Sub
  63.  
  64.  

Dulce Infierno Lunar!¡.


« Última modificación: 13 Julio 2010, 21:20 pm por BlackZeroX » En línea

The Dark Shadow is my passion.
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines