Option Compare Database
Option Explicit
'http://www.utteraccess.com/forum/index.php?showtopic=1723895
'Windows API Function Declarations
#If Win64 = 1 Then
Private Declare PtrSafe Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As LongLong
#Else
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
#End If
Public Type POINTAPI
X As Long
Y As Long
End Type
#If Win64 = 1 Then
Public Function GetCursorPosX() As LongLong
Dim n As POINTAPI
GetCursorPos n
GetCursorPosX = n.X
End Function
#Else
Public Function GetCursorPosX() As Long
Dim n As POINTAPI
GetCursorPos n
GetCursorPosX = n.X
End Function
#End If
#If Win64 = 1 Then
Public Function GetCursorPosY() As LongLong
Dim n As POINTAPI
GetCursorPos n
GetCursorPosY = n.Y
End Function
#Else
Public Function GetCursorPosY() As Long
Dim n As POINTAPI
GetCursorPos n
GetCursorPosY = n.Y
End Function
#End If
martes, 21 de noviembre de 2017
lunes, 20 de noviembre de 2017
miércoles, 18 de octubre de 2017
VBA Access. Función para exportar un recordset a Excel.
Public Sub Export2Excel(ByRef rs As Variant, Optional ByVal bShowColumnNames As Boolean = True)
On Error GoTo error
Dim xlApp As Object
Dim xlWb As Object
Dim xlWs As Object
Dim recArray As Variant
Dim strDB As String
Dim fldCount As Integer
Dim recCount As Long
Dim iCol As Integer
Dim iRow As Integer
' Create an instance of Excel and add a workbook
Set xlApp = CreateObject("Excel.Application")
Set xlWb = xlApp.Workbooks.Add
Set xlWs = xlWb.Worksheets("Hoja1")
' Copy field names to the first row of the worksheet
If bShowColumnNames Then
fldCount = rs.Fields.Count
For iCol = 1 To fldCount
xlWs.Cells(1, iCol).value = rs.Fields(iCol - 1).Name
Next
End If
' Check version of Excel
If Val(Mid(xlApp.Version, 1, InStr(1, xlApp.Version, ".") - 1)) > 8 Then
'EXCEL 2000,2002,2003, or 2007: Use CopyFromRecordset
' Copy the recordset to the worksheet, starting in cell A2
xlWs.Cells(IIf(bShowColumnNames, 2, 1), 1).CopyFromRecordset rs
'Note: CopyFromRecordset will fail if the recordset
'contains an OLE object field or array data such
'as hierarchical recordsets
Else
MsgBox "Versión instalada de excel no soportada!", vbCritical
Exit Sub
End If
' Auto-fit the column widths and row heights
xlApp.Selection.CurrentRegion.Columns.AutoFit
xlApp.Selection.CurrentRegion.Rows.AutoFit
' Display Excel and give user control of Excel's lifetime
xlApp.Visible = True
xlApp.UserControl = True
' Release Excel references
Set xlWs = Nothing
Set xlWb = Nothing
Set xlApp = Nothing
Exit Sub
Resume
error:
MsgBox Err.Description
End Sub
On Error GoTo error
Dim xlApp As Object
Dim xlWb As Object
Dim xlWs As Object
Dim recArray As Variant
Dim strDB As String
Dim fldCount As Integer
Dim recCount As Long
Dim iCol As Integer
Dim iRow As Integer
' Create an instance of Excel and add a workbook
Set xlApp = CreateObject("Excel.Application")
Set xlWb = xlApp.Workbooks.Add
Set xlWs = xlWb.Worksheets("Hoja1")
' Copy field names to the first row of the worksheet
If bShowColumnNames Then
fldCount = rs.Fields.Count
For iCol = 1 To fldCount
xlWs.Cells(1, iCol).value = rs.Fields(iCol - 1).Name
Next
End If
' Check version of Excel
If Val(Mid(xlApp.Version, 1, InStr(1, xlApp.Version, ".") - 1)) > 8 Then
'EXCEL 2000,2002,2003, or 2007: Use CopyFromRecordset
' Copy the recordset to the worksheet, starting in cell A2
xlWs.Cells(IIf(bShowColumnNames, 2, 1), 1).CopyFromRecordset rs
'Note: CopyFromRecordset will fail if the recordset
'contains an OLE object field or array data such
'as hierarchical recordsets
Else
MsgBox "Versión instalada de excel no soportada!", vbCritical
Exit Sub
End If
' Auto-fit the column widths and row heights
xlApp.Selection.CurrentRegion.Columns.AutoFit
xlApp.Selection.CurrentRegion.Rows.AutoFit
' Display Excel and give user control of Excel's lifetime
xlApp.Visible = True
xlApp.UserControl = True
' Release Excel references
Set xlWs = Nothing
Set xlWb = Nothing
Set xlApp = Nothing
Exit Sub
Resume
error:
MsgBox Err.Description
End Sub
lunes, 16 de octubre de 2017
VBA Access. Módulo de clase clsTimer. Crear uno o varios Timer independiente(s) sin depender del formulario. (2/2)
Option Compare Database
Option Explicit
'1 Crearemos el timer o timers que necesitemos instanciando esta clase sin depender del formulario.
'Ej: Public WithEvents oTimer1 As clsTimer
'https://access-programmers.co.uk/forums/showthread.php?t=232012
Option Explicit
'1 Crearemos el timer o timers que necesitemos instanciando esta clase sin depender del formulario.
'Ej: Public WithEvents oTimer1 As clsTimer
'2 Para definir las acciones a realizar en el evento OnTimer, en el formulario, debemos crear un 'procedimento que se llamará: Nombre del objeto timer que hallamos creado + "_OnTimer".
'Ejemplo objeto oTimer1 -> Private Sub oTimer1_OnTimer() ..... End Sub
'3 Iniciar timer: oTimer1.Startit
'4 Parar timer: oTimer1.Stopit
'3 Iniciar timer: oTimer1.Startit
'4 Parar timer: oTimer1.Stopit
Option Compare Database
Option Explicit
'Windows API Function Declarations
#If Win64 = 1 Then
Private Declare PtrSafe Function SetTimer Lib "user32" ( _
ByVal hwnd As LongPtr, ByVal nIDEvent As LongPtr, _
ByVal uElapse As LongLong, ByVal lpTimerFunc As LongPtr) As LongLong
Private Declare PtrSafe Function KillTimer Lib "user32" ( _
ByVal hwnd As LongPtr, ByVal nIDEvent As LongPtr) As LongLong
#Else
Private Declare Function SetTimer Lib "user32" ( _
ByVal hWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Private Declare Function KillTimer Lib "user32" ( _
ByVal hWnd As Long, ByVal nIDEvent As Long) As Long
#End If
#If Win64 = 1 Then
Private TimerID As LongLong
#Else
Private TimerID As Long
#End If
Public Event OnTimer()
'Start timer
Public Sub Startit(IntervalMs As Long)
TimerID = SetTimer(Application.hWndAccessApp, ObjPtr(Me), IntervalMs, AddressOf Timers.TimerProc)
End Sub
'Stop timer
Public Sub Stopit()
If TimerID <> -1 Then
KillTimer Application.hWndAccessApp, TimerID
TimerID = 0
End If
End Sub
'Trigger Public event
Public Sub RaiseTimerEvent()
RaiseEvent OnTimer
End Sub
VBA Access. Módulo Timers. Crear uno o varios Timer independiente(s) sin depender del formulario. (1/2)
'Crear un módulo llamado Timers
'https://access-programmers.co.uk/forums/showthread.php?t=232012
'https://access-programmers.co.uk/forums/showthread.php?t=232012
#If Win64 = 1 Then
Public Sub TimerProc(ByVal hwnd As LongPtr, _
ByVal uMsg As LongLong, _
ByVal oTimer As clsTimer, _
ByVal dwTime As LongLong)
' Alert appropriate timer object instance.
If Not oTimer Is Nothing Then
oTimer.RaiseTimerEvent
Debug.Print "evento timer"
End If
End Sub
#Else
Public Sub TimerProc(ByVal hwnd As Long, _
ByVal uMsg As Long, _
ByVal oTimer As clsTimer, _
ByVal dwTime As Long)
' Alert appropriate timer object instance.
If Not oTimer Is Nothing Then
oTimer.RaiseTimerEvent
Debug.Print "evento timer"
End If
End Sub
#End If
VBA Access. Módulo de Clase clsCarousel. Clase para hacer un carrusel de imágenes combinándola con un timer.
Option Compare Database
Option Explicit
'1 En el formulario donde haremos el carrusel, definimos una variable del tipo clsCarousel
'2 Crearemos un control imagen
'3 Instanciamos el objeto y llamamos al método LoadImages pasando la carpeta donde contenga las imágenes y el nombre del control imagen por referencia
'4 Iniciamos un Timer con el refresco que queramos
'5 cada evento del timer (OnTimer), llamaremos al método NextImage
Private ControlImagen As Control
Private NumImagenActual As Integer
Private DiccionarioImagenes As Dictionary
Private Sub Class_Initialize()
NumImagenActual = 0
End Sub
Private Sub Class_Terminate()
If Not DiccionarioImagenes Is Nothing Then
DiccionarioImagenes.RemoveAll
Set DiccionarioImagenes = Nothing
End If
End Sub
Function LoadImages(ByVal CarpetaImagenes As String, ByRef ctlImagen As Control) As Boolean
On Error GoTo error
Set DiccionarioImagenes = New Dictionary
Dim i As Integer
i = 0
Dim file As Object
Dim fso As New FileSystemObject
For Each file In fso.GetFolder(CarpetaImagenes).Files
i = i + 1
DiccionarioImagenes.Add CStr(i), CStr(file)
Next file
Set ControlImagen = ctlImagen
NextImage
LoadImages = True
Exit Function
Resume
error:
LoadImages = False
Debug.Print Err.Number & ": " & Err.Description
End Function
Function NextImage()
On Error Resume Next
NumImagenActual = NumImagenActual Mod DiccionarioImagenes.Count + 1
ControlImagen.Picture = DiccionarioImagenes.Item(CStr(NumImagenActual))
End Function
Option Explicit
'1 En el formulario donde haremos el carrusel, definimos una variable del tipo clsCarousel
'2 Crearemos un control imagen
'3 Instanciamos el objeto y llamamos al método LoadImages pasando la carpeta donde contenga las imágenes y el nombre del control imagen por referencia
'4 Iniciamos un Timer con el refresco que queramos
'5 cada evento del timer (OnTimer), llamaremos al método NextImage
Private ControlImagen As Control
Private NumImagenActual As Integer
Private DiccionarioImagenes As Dictionary
Private Sub Class_Initialize()
NumImagenActual = 0
End Sub
Private Sub Class_Terminate()
If Not DiccionarioImagenes Is Nothing Then
DiccionarioImagenes.RemoveAll
Set DiccionarioImagenes = Nothing
End If
End Sub
Function LoadImages(ByVal CarpetaImagenes As String, ByRef ctlImagen As Control) As Boolean
On Error GoTo error
Set DiccionarioImagenes = New Dictionary
Dim i As Integer
i = 0
Dim file As Object
Dim fso As New FileSystemObject
For Each file In fso.GetFolder(CarpetaImagenes).Files
i = i + 1
DiccionarioImagenes.Add CStr(i), CStr(file)
Next file
Set ControlImagen = ctlImagen
NextImage
LoadImages = True
Exit Function
Resume
error:
LoadImages = False
Debug.Print Err.Number & ": " & Err.Description
End Function
Function NextImage()
On Error Resume Next
NumImagenActual = NumImagenActual Mod DiccionarioImagenes.Count + 1
ControlImagen.Picture = DiccionarioImagenes.Item(CStr(NumImagenActual))
End Function
VBA Access. Modulo ModTransparent. Permite hacer un formulario totalmente visible, translúcido o transparente del todo.
Option Compare Database
Option Explicit
'http://grupos.emagister.com/debate/formulario_transparente/6411-674789
'
'Uso por ejemplo en el load del formulario: Transparent Me, 100
'
'Los valores posibles son entre 0 totalmente transparente y 255 totalmente visible.
'Para que funcione debes poner este código en un módulo nuevo
#If Win64 = 1 Then
Private Declare PtrSafe Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Declare PtrSafe Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Private Declare PtrSafe Function SetLayeredWindowAttributes Lib "user32" (ByVal hWnd As Long, ByVal crKey As Long, ByVal bAlpha As Byte, ByVal dwFlags As Long) As Long
#Else
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetLayeredWindowAttributes Lib "user32" (ByVal hWnd As Long, ByVal crKey As Long, ByVal bAlpha As Byte, ByVal dwFlags As Long) As Long
#End If
Private Const GWL_EXSTYLE = (-20)
Private Const WS_EX_LAYERED = &H80000
Private Const LWA_ALPHA = &H2
Function Transparent(frm As Form, Nivel As Integer)
Dim lngHwnd As Long
If Nivel < 0 Or Nivel > 255 Then Exit Function
lngHwnd = frm.hWnd
SetWindowLong lngHwnd, GWL_EXSTYLE, GetWindowLong(lngHwnd, GWL_EXSTYLE) Or WS_EX_LAYERED
SetLayeredWindowAttributes lngHwnd, 0, Nivel, LWA_ALPHA
End Function
Option Explicit
'http://grupos.emagister.com/debate/formulario_transparente/6411-674789
'
'Uso por ejemplo en el load del formulario: Transparent Me, 100
'
'Los valores posibles son entre 0 totalmente transparente y 255 totalmente visible.
'Para que funcione debes poner este código en un módulo nuevo
#If Win64 = 1 Then
Private Declare PtrSafe Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Declare PtrSafe Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Private Declare PtrSafe Function SetLayeredWindowAttributes Lib "user32" (ByVal hWnd As Long, ByVal crKey As Long, ByVal bAlpha As Byte, ByVal dwFlags As Long) As Long
#Else
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetLayeredWindowAttributes Lib "user32" (ByVal hWnd As Long, ByVal crKey As Long, ByVal bAlpha As Byte, ByVal dwFlags As Long) As Long
#End If
Private Const GWL_EXSTYLE = (-20)
Private Const WS_EX_LAYERED = &H80000
Private Const LWA_ALPHA = &H2
Function Transparent(frm As Form, Nivel As Integer)
Dim lngHwnd As Long
If Nivel < 0 Or Nivel > 255 Then Exit Function
lngHwnd = frm.hWnd
SetWindowLong lngHwnd, GWL_EXSTYLE, GetWindowLong(lngHwnd, GWL_EXSTYLE) Or WS_EX_LAYERED
SetLayeredWindowAttributes lngHwnd, 0, Nivel, LWA_ALPHA
End Function
viernes, 13 de octubre de 2017
VBA Access. Módulo de clase clsFTP para VBA. Métodos FtpDownload y FtpUpload para descargar o subir ficheros.
Option Compare Database
Option Explicit
'http://analystcave.com/vba-downloading-files-from-ftp-using-vba/
'Ejemplo de uso:
'Dim oFtp as new clsFtp
'FtpDownload Fichero_Remoto_Origen, Fichero_Local_Destino, Servidor, Puerto, Usuario, Contraseña
'oFtp.FtpDownload "//Download/text_file.txt", "C:\text_file.txt", "192.168.0.100", 21, "username", "password"
'FtpUpload Fichero_Local_Origen, Fichero_Remoto_Destino, Servidor, Puerto, Usuario, Contraseña
'oFtp.FtpUpload "C:\text_file.txt", "//Download/text_file.txt", "192.168.0.100", 21, "username", "password"
Private Const FTP_TRANSFER_TYPE_UNKNOWN As Long = 0
Private Const INTERNET_FLAG_RELOAD As Long = &H80000000
'Windows API Function Declarations
#If Win64 = 1 Then
Private Declare PtrSafe Function InternetOpenA Lib "wininet.dll" ( _
ByVal sAgent As String, _
ByVal lAccessType As Long, _
ByVal sProxyName As String, _
ByVal sProxyBypass As String, _
ByVal lFlags As Long) As Long
Private Declare PtrSafe Function InternetConnectA Lib "wininet.dll" ( _
ByVal hInternetSession As Long, _
ByVal sServerName As String, _
ByVal nServerPort As Long, _
ByVal sUsername As String, _
ByVal sPassword As String, _
ByVal lService As Long, _
ByVal lFlags As Long, _
ByVal lcontext As Long) As Long
Private Declare PtrSafe Function FtpGetFileA Lib "wininet.dll" ( _
ByVal hConnect As Long, _
ByVal lpszRemoteFile As String, _
ByVal lpszNewFile As String, _
ByVal fFailIfExists As Long, _
ByVal dwFlagsAndAttributes As Long, _
ByVal dwFlags As Long, _
ByVal dwContext As Long) As Long
Private Declare PtrSafe Function FtpPutFileA _
Lib "wininet.dll" _
_
(ByVal hFtpSession As Long, _
ByVal lpszLocalFile As String, _
ByVal lpszRemoteFile As String, _
ByVal dwFlags As Long, _
ByVal dwContext As Long) As Boolean
Private Declare PtrSafe Function InternetCloseHandle Lib "wininet" ( _
ByVal hInet As Long) As Long
#Else
Private Declare Function InternetOpenA Lib "wininet.dll" ( _
ByVal sAgent As String, _
ByVal lAccessType As Long, _
ByVal sProxyName As String, _
ByVal sProxyBypass As String, _
ByVal lFlags As Long) As Long
Private Declare Function InternetConnectA Lib "wininet.dll" ( _
ByVal hInternetSession As Long, _
ByVal sServerName As String, _
ByVal nServerPort As Long, _
ByVal sUsername As String, _
ByVal sPassword As String, _
ByVal lService As Long, _
ByVal lFlags As Long, _
ByVal lcontext As Long) As Long
Private Declare Function FtpGetFileA Lib "wininet.dll" ( _
ByVal hConnect As Long, _
ByVal lpszRemoteFile As String, _
ByVal lpszNewFile As String, _
ByVal fFailIfExists As Long, _
ByVal dwFlagsAndAttributes As Long, _
ByVal dwFlags As Long, _
ByVal dwContext As Long) As Long
Private Declare Function FtpPutFileA _
Lib "wininet.dll" _
_
(ByVal hFtpSession As Long, _
ByVal lpszLocalFile As String, _
ByVal lpszRemoteFile As String, _
ByVal dwFlags As Long, _
ByVal dwContext As Long) As Boolean
Private Declare Function InternetCloseHandle Lib "wininet" ( _
ByVal hInet As Long) As Long
#End If
Public Function FtpDownload(ByVal strRemoteFile As String, ByVal strLocalFile As String, ByVal strHost As String, ByVal lngPort As Long, ByVal strUser As String, ByVal strPass As String) As Boolean
On Error GoTo error
Dim hOpen As Long
Dim hConn As Long
hOpen = InternetOpenA("FTPGET", 1, vbNullString, vbNullString, 1)
hConn = InternetConnectA(hOpen, strHost, lngPort, strUser, strPass, 1, 0, 2)
If FtpGetFileA(hConn, strRemoteFile, strLocalFile, 1, 0, FTP_TRANSFER_TYPE_UNKNOWN Or INTERNET_FLAG_RELOAD, 0) Then
FtpDownload = True
Debug.Print "Success"
Else
FtpDownload = False
Debug.Print "Fail"
End If
'Close connections
InternetCloseHandle hConn
InternetCloseHandle hOpen
Exit Function
error:
FtpDownload = False
Debug.Print Err.Number & ": " & Err.Description
End Function
Public Function FtpUpload(ByVal strLocalFile As String, ByVal strRemoteFile As String, ByVal strHost As String, ByVal lngPort As Long, ByVal strUser As String, ByVal strPass As String) As Boolean
On Error GoTo error
Dim hOpen As Long
Dim hConn As Long
hOpen = InternetOpenA("FTPGET", 1, vbNullString, vbNullString, 1)
hConn = InternetConnectA(hOpen, strHost, lngPort, strUser, strPass, 1, 0, 2)
If FtpPutFileA(hConn, strLocalFile, strRemoteFile, FTP_TRANSFER_TYPE_UNKNOWN Or INTERNET_FLAG_RELOAD, 0) Then
FtpUpload = True
Debug.Print "Success"
Else
FtpUpload = False
Debug.Print "Fail"
End If
'Close connections
InternetCloseHandle hConn
InternetCloseHandle hOpen
Exit Function
error:
FtpUpload = False
Debug.Print Err.Number & ": " & Err.Description
End Function
Option Explicit
'http://analystcave.com/vba-downloading-files-from-ftp-using-vba/
'Ejemplo de uso:
'Dim oFtp as new clsFtp
'FtpDownload Fichero_Remoto_Origen, Fichero_Local_Destino, Servidor, Puerto, Usuario, Contraseña
'oFtp.FtpDownload "//Download/text_file.txt", "C:\text_file.txt", "192.168.0.100", 21, "username", "password"
'FtpUpload Fichero_Local_Origen, Fichero_Remoto_Destino, Servidor, Puerto, Usuario, Contraseña
'oFtp.FtpUpload "C:\text_file.txt", "//Download/text_file.txt", "192.168.0.100", 21, "username", "password"
Private Const FTP_TRANSFER_TYPE_UNKNOWN As Long = 0
Private Const INTERNET_FLAG_RELOAD As Long = &H80000000
'Windows API Function Declarations
#If Win64 = 1 Then
Private Declare PtrSafe Function InternetOpenA Lib "wininet.dll" ( _
ByVal sAgent As String, _
ByVal lAccessType As Long, _
ByVal sProxyName As String, _
ByVal sProxyBypass As String, _
ByVal lFlags As Long) As Long
Private Declare PtrSafe Function InternetConnectA Lib "wininet.dll" ( _
ByVal hInternetSession As Long, _
ByVal sServerName As String, _
ByVal nServerPort As Long, _
ByVal sUsername As String, _
ByVal sPassword As String, _
ByVal lService As Long, _
ByVal lFlags As Long, _
ByVal lcontext As Long) As Long
Private Declare PtrSafe Function FtpGetFileA Lib "wininet.dll" ( _
ByVal hConnect As Long, _
ByVal lpszRemoteFile As String, _
ByVal lpszNewFile As String, _
ByVal fFailIfExists As Long, _
ByVal dwFlagsAndAttributes As Long, _
ByVal dwFlags As Long, _
ByVal dwContext As Long) As Long
Private Declare PtrSafe Function FtpPutFileA _
Lib "wininet.dll" _
_
(ByVal hFtpSession As Long, _
ByVal lpszLocalFile As String, _
ByVal lpszRemoteFile As String, _
ByVal dwFlags As Long, _
ByVal dwContext As Long) As Boolean
Private Declare PtrSafe Function InternetCloseHandle Lib "wininet" ( _
ByVal hInet As Long) As Long
#Else
Private Declare Function InternetOpenA Lib "wininet.dll" ( _
ByVal sAgent As String, _
ByVal lAccessType As Long, _
ByVal sProxyName As String, _
ByVal sProxyBypass As String, _
ByVal lFlags As Long) As Long
Private Declare Function InternetConnectA Lib "wininet.dll" ( _
ByVal hInternetSession As Long, _
ByVal sServerName As String, _
ByVal nServerPort As Long, _
ByVal sUsername As String, _
ByVal sPassword As String, _
ByVal lService As Long, _
ByVal lFlags As Long, _
ByVal lcontext As Long) As Long
Private Declare Function FtpGetFileA Lib "wininet.dll" ( _
ByVal hConnect As Long, _
ByVal lpszRemoteFile As String, _
ByVal lpszNewFile As String, _
ByVal fFailIfExists As Long, _
ByVal dwFlagsAndAttributes As Long, _
ByVal dwFlags As Long, _
ByVal dwContext As Long) As Long
Private Declare Function FtpPutFileA _
Lib "wininet.dll" _
_
(ByVal hFtpSession As Long, _
ByVal lpszLocalFile As String, _
ByVal lpszRemoteFile As String, _
ByVal dwFlags As Long, _
ByVal dwContext As Long) As Boolean
Private Declare Function InternetCloseHandle Lib "wininet" ( _
ByVal hInet As Long) As Long
#End If
Public Function FtpDownload(ByVal strRemoteFile As String, ByVal strLocalFile As String, ByVal strHost As String, ByVal lngPort As Long, ByVal strUser As String, ByVal strPass As String) As Boolean
On Error GoTo error
Dim hOpen As Long
Dim hConn As Long
hOpen = InternetOpenA("FTPGET", 1, vbNullString, vbNullString, 1)
hConn = InternetConnectA(hOpen, strHost, lngPort, strUser, strPass, 1, 0, 2)
If FtpGetFileA(hConn, strRemoteFile, strLocalFile, 1, 0, FTP_TRANSFER_TYPE_UNKNOWN Or INTERNET_FLAG_RELOAD, 0) Then
FtpDownload = True
Debug.Print "Success"
Else
FtpDownload = False
Debug.Print "Fail"
End If
'Close connections
InternetCloseHandle hConn
InternetCloseHandle hOpen
Exit Function
error:
FtpDownload = False
Debug.Print Err.Number & ": " & Err.Description
End Function
Public Function FtpUpload(ByVal strLocalFile As String, ByVal strRemoteFile As String, ByVal strHost As String, ByVal lngPort As Long, ByVal strUser As String, ByVal strPass As String) As Boolean
On Error GoTo error
Dim hOpen As Long
Dim hConn As Long
hOpen = InternetOpenA("FTPGET", 1, vbNullString, vbNullString, 1)
hConn = InternetConnectA(hOpen, strHost, lngPort, strUser, strPass, 1, 0, 2)
If FtpPutFileA(hConn, strLocalFile, strRemoteFile, FTP_TRANSFER_TYPE_UNKNOWN Or INTERNET_FLAG_RELOAD, 0) Then
FtpUpload = True
Debug.Print "Success"
Else
FtpUpload = False
Debug.Print "Fail"
End If
'Close connections
InternetCloseHandle hConn
InternetCloseHandle hOpen
Exit Function
error:
FtpUpload = False
Debug.Print Err.Number & ": " & Err.Description
End Function
viernes, 6 de octubre de 2017
VBA Access. Listado de artículos con sus imágenes asociadas de una BdD Sql Server en un formulario con Botones e Imágenes (ejemplo de 4x4 botones/imágenes)
'Formulario de tipo único compuesto por:
'16 botones cmdBut1,cmdBut2, ... (Botón con estilo transparente para poder ver la imagen de detrás)
'16 imagenes (detrás de cada botón) Imagen1,Imagen2, ...
'16 textbox Desc1, Desc2,... (DEBAJO DE CADA BOTÓN/IMAGEN) cada uno de ellos con Origen de control = Desc1, Desc2, ... respectivamente
'16 textbox RefArt1,RefArt2,... (OCULTOS) cada uno de ellos con Origen de control = RefArt1, RefArt2, ... respectivamente
'16 textbox CodImg1,CodImg2,... (OCULTOS) cada uno de ellos con Origen de control = CodImg1, CodImg2, ... respectivamente
'4 botones para navegar por los registros (Anterior, Siguiente, Primero y Último)
Option Compare Database
Option Explicit
Const NUMBUTTONS = 16
Private Sub ProcessButtonClicked()
On Error GoTo error
Dim NumButton As Integer
NumButton = CInt(Replace(Me.ActiveControl.Name, "cmdBut", "0"))
If Nz(Me.Controls("RefArt" & NumButton).Value, "") = "" Then Err.Raise 99, "ProcessButtonClicked", "Botón / RefArt N. " & NumButton & " sin definir!"
MsgBox Me.Controls("RefArt" & NumButton).Value & " " & Me.Controls("Desc" & NumButton).Value, , ""
Exit Sub
error:
MsgBox Err.Description, vbCritical, ""
End Sub
Private Sub cmdBut1_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut2_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut3_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut4_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut5_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut6_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut7_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut8_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut9_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut10_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut11_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut12_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut13_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut14_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut15_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut16_Click()
ProcessButtonClicked
End Sub
Private Sub LoadArticulos()
On Error GoTo error
'Creamos recordset dinámico
Dim rsD As New ADODB.Recordset
With rsD
Dim i As Integer
For i = 1 To NUMBUTTONS
.Fields.Append "RefArt" & i, adVarChar, 255, adFldKeyColumn
.Fields.Append "Desc" & i, adVarChar, 255, adFldMayBeNull
.Fields.Append "CodImg" & i, adInteger, , adFldMayBeNull
Next i
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.LockType = adLockPessimistic
.Open
End With
'A partir del recordset original, creamos otro recordset dinámicamente para simular un total de NUMBUTTONS por cada fila/pantalla
Dim rsArt As New ADODB.Recordset
Dim cnArt As New ADODB.Connection
cnArt.ConnectionString = DimeCadenaConexion
cnArt.Open
rsArt.Open "SELECT TOP 1000 UPPER(ReferenciaArtículo) AS ReferenciaArtículo,UPPER(Descripción) AS Descripción,CodigoImagen FROM Artículos", _
cnArt, adOpenStatic, adLockReadOnly
'Rellenamos el recordset dinámico que al final asignaremos al formulario
Do Until rsArt.EOF
rsD.AddNew
Dim j As Integer
For j = 1 To NUMBUTTONS
If Not rsArt.EOF Then
rsD("RefArt" & j) = rsArt!ReferenciaArtículo
rsD("Desc" & j) = rsArt!DESCRIPCIÓN
rsD("CodImg" & j) = Nz(rsArt!CodigoImagen, 0)
rsArt.MoveNext
End If
Next j
rsD.Update
Loop
Set Me.Recordset = rsD
rsArt.Close
cnArt.Close
Set rsArt = Nothing
rsD.Close
Set rsD = Nothing
DoCmd.GoToRecord , , acFirst
Exit Sub
Resume
error:
MsgBox Err.Number & ": " & Err.Description
End Sub
Private Sub cmdRegAnterior_Click()
On Error Resume Next
DoCmd.GoToRecord , , acPrevious
End Sub
Private Sub cmdRegPrimero_Click()
On Error Resume Next
DoCmd.GoToRecord , , acFirst
End Sub
Private Sub cmdRegSiguiente_Click()
On Error Resume Next
DoCmd.GoToRecord , , acNext
End Sub
Private Sub cmdRegUltimo_Click()
On Error Resume Next
DoCmd.GoToRecord , , acLast
End Sub
Private Sub Form_Current()
On Error Resume Next
CargarImagenes
End Sub
Private Sub CargarImagenes()
On Error GoTo error
'Asignaremos al registro actual / pantalla, las 16 imágenes que tienen asignadas por código de imagen
'1 Consultaremos en la BdD la imagen y si esta no existe en la carpeta "Images" , con el mismo nombre de la referencia
'2 Asignamos a cada control Imagen, el path de la imagen que deben cargar. Ej. Imagen1.Picture = "C:\...\Images\ficheroimagen"
Debug.Print "Cargando Imágenes " & Now
'Application.Echo False
Dim fso As New FileSystemObject
If Not fso.FolderExists(CurrentProject.Path & "\Images") Then fso.CreateFolder (CurrentProject.Path & "\Images")
Dim i As Integer
For i = 1 To NUMBUTTONS
Dim CodigoImagen As Long
CodigoImagen = Nz(Me.Controls("CodImg" & i), 0)
If CodigoImagen <> 0 Then
Dim rs As New ADODB.Recordset
Dim cn As New ADODB.Connection
cn.Open DimeCadenaConexion
rs.Open "SELECT * FROM Imagenes WHERE CodigoImagen = " & CodigoImagen, cn, adOpenStatic, adLockReadOnly
If Not rs.EOF Then
Dim sFName As String
If Nz(rs!Fichero, "") <> "" Then
sFName = CurrentProject.Path & "\Images\" & Me.Controls("RefArt" & i) & "." & fso.GetExtensionName(rs!Fichero)
If Not fso.FileExists(sFName) Then
Dim objStream As New ADODB.Stream
objStream.Type = adTypeBinary
objStream.Open
objStream.Write rs!Imagen
objStream.SaveToFile sFName, adSaveCreateOverWrite
objStream.Close
Set objStream = Nothing
End If
If fso.FileExists(sFName) Then
Me.Controls("Imagen" & i).Picture = sFName
Else
Me.Controls("Imagen" & i).Picture = ""
End If
End If
Else
Me.Controls("Imagen" & i).Picture = ""
End If
rs.Close
cn.Close
Set rs = Nothing
Else
Me.Controls("Imagen" & i).Picture = ""
End If
Next i
Set fso = Nothing
'Application.Echo True
Exit Sub
error:
MsgBox Err.Number & ": " & Err.Description
End Sub
Private Sub Form_Load()
LoadArticulos
End Sub
'16 botones cmdBut1,cmdBut2, ... (Botón con estilo transparente para poder ver la imagen de detrás)
'16 imagenes (detrás de cada botón) Imagen1,Imagen2, ...
'16 textbox Desc1, Desc2,... (DEBAJO DE CADA BOTÓN/IMAGEN) cada uno de ellos con Origen de control = Desc1, Desc2, ... respectivamente
'16 textbox RefArt1,RefArt2,... (OCULTOS) cada uno de ellos con Origen de control = RefArt1, RefArt2, ... respectivamente
'16 textbox CodImg1,CodImg2,... (OCULTOS) cada uno de ellos con Origen de control = CodImg1, CodImg2, ... respectivamente
'4 botones para navegar por los registros (Anterior, Siguiente, Primero y Último)
Option Compare Database
Option Explicit
Const NUMBUTTONS = 16
Private Sub ProcessButtonClicked()
On Error GoTo error
Dim NumButton As Integer
NumButton = CInt(Replace(Me.ActiveControl.Name, "cmdBut", "0"))
If Nz(Me.Controls("RefArt" & NumButton).Value, "") = "" Then Err.Raise 99, "ProcessButtonClicked", "Botón / RefArt N. " & NumButton & " sin definir!"
MsgBox Me.Controls("RefArt" & NumButton).Value & " " & Me.Controls("Desc" & NumButton).Value, , ""
Exit Sub
error:
MsgBox Err.Description, vbCritical, ""
End Sub
Private Sub cmdBut1_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut2_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut3_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut4_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut5_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut6_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut7_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut8_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut9_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut10_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut11_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut12_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut13_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut14_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut15_Click()
ProcessButtonClicked
End Sub
Private Sub cmdBut16_Click()
ProcessButtonClicked
End Sub
Private Sub LoadArticulos()
On Error GoTo error
'Creamos recordset dinámico
Dim rsD As New ADODB.Recordset
With rsD
Dim i As Integer
For i = 1 To NUMBUTTONS
.Fields.Append "RefArt" & i, adVarChar, 255, adFldKeyColumn
.Fields.Append "Desc" & i, adVarChar, 255, adFldMayBeNull
.Fields.Append "CodImg" & i, adInteger, , adFldMayBeNull
Next i
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.LockType = adLockPessimistic
.Open
End With
'A partir del recordset original, creamos otro recordset dinámicamente para simular un total de NUMBUTTONS por cada fila/pantalla
Dim rsArt As New ADODB.Recordset
Dim cnArt As New ADODB.Connection
cnArt.ConnectionString = DimeCadenaConexion
cnArt.Open
rsArt.Open "SELECT TOP 1000 UPPER(ReferenciaArtículo) AS ReferenciaArtículo,UPPER(Descripción) AS Descripción,CodigoImagen FROM Artículos", _
cnArt, adOpenStatic, adLockReadOnly
'Rellenamos el recordset dinámico que al final asignaremos al formulario
Do Until rsArt.EOF
rsD.AddNew
Dim j As Integer
For j = 1 To NUMBUTTONS
If Not rsArt.EOF Then
rsD("RefArt" & j) = rsArt!ReferenciaArtículo
rsD("Desc" & j) = rsArt!DESCRIPCIÓN
rsD("CodImg" & j) = Nz(rsArt!CodigoImagen, 0)
rsArt.MoveNext
End If
Next j
rsD.Update
Loop
Set Me.Recordset = rsD
rsArt.Close
cnArt.Close
Set rsArt = Nothing
rsD.Close
Set rsD = Nothing
DoCmd.GoToRecord , , acFirst
Exit Sub
Resume
error:
MsgBox Err.Number & ": " & Err.Description
End Sub
Private Sub cmdRegAnterior_Click()
On Error Resume Next
DoCmd.GoToRecord , , acPrevious
End Sub
Private Sub cmdRegPrimero_Click()
On Error Resume Next
DoCmd.GoToRecord , , acFirst
End Sub
Private Sub cmdRegSiguiente_Click()
On Error Resume Next
DoCmd.GoToRecord , , acNext
End Sub
Private Sub cmdRegUltimo_Click()
On Error Resume Next
DoCmd.GoToRecord , , acLast
End Sub
Private Sub Form_Current()
On Error Resume Next
CargarImagenes
End Sub
Private Sub CargarImagenes()
On Error GoTo error
'Asignaremos al registro actual / pantalla, las 16 imágenes que tienen asignadas por código de imagen
'1 Consultaremos en la BdD la imagen y si esta no existe en la carpeta "Images" , con el mismo nombre de la referencia
'2 Asignamos a cada control Imagen, el path de la imagen que deben cargar. Ej. Imagen1.Picture = "C:\...\Images\ficheroimagen"
Debug.Print "Cargando Imágenes " & Now
'Application.Echo False
Dim fso As New FileSystemObject
If Not fso.FolderExists(CurrentProject.Path & "\Images") Then fso.CreateFolder (CurrentProject.Path & "\Images")
Dim i As Integer
For i = 1 To NUMBUTTONS
Dim CodigoImagen As Long
CodigoImagen = Nz(Me.Controls("CodImg" & i), 0)
If CodigoImagen <> 0 Then
Dim rs As New ADODB.Recordset
Dim cn As New ADODB.Connection
cn.Open DimeCadenaConexion
rs.Open "SELECT * FROM Imagenes WHERE CodigoImagen = " & CodigoImagen, cn, adOpenStatic, adLockReadOnly
If Not rs.EOF Then
Dim sFName As String
If Nz(rs!Fichero, "") <> "" Then
sFName = CurrentProject.Path & "\Images\" & Me.Controls("RefArt" & i) & "." & fso.GetExtensionName(rs!Fichero)
If Not fso.FileExists(sFName) Then
Dim objStream As New ADODB.Stream
objStream.Type = adTypeBinary
objStream.Open
objStream.Write rs!Imagen
objStream.SaveToFile sFName, adSaveCreateOverWrite
objStream.Close
Set objStream = Nothing
End If
If fso.FileExists(sFName) Then
Me.Controls("Imagen" & i).Picture = sFName
Else
Me.Controls("Imagen" & i).Picture = ""
End If
End If
Else
Me.Controls("Imagen" & i).Picture = ""
End If
rs.Close
cn.Close
Set rs = Nothing
Else
Me.Controls("Imagen" & i).Picture = ""
End If
Next i
Set fso = Nothing
'Application.Echo True
Exit Sub
error:
MsgBox Err.Number & ": " & Err.Description
End Sub
Private Sub Form_Load()
LoadArticulos
End Sub
martes, 3 de octubre de 2017
VBA Access. Listar en un formulario las imágenes de una tabla Sql Server.
'En un formulario tendremos un control imagen con origen de control: PathFName
'3 Textbox con orígenes de control: CodigoImagen, FName y KBSize
Private Sub LoadFormRecordset()
On Error GoTo error
'Crear y abrir recordset dinamico al cual asignaremos valores y finalmente lo asignaremos al recordset del formulario
'https://www.w3schools.com/asp/ado_datatypes.asp
Dim rsD As New ADODB.Recordset
rsD.Fields.Append "CodigoImagen", adInteger, , adFldKeyColumn
rsD.Fields.Append "PathFName", adVarChar, 255, adFldIsNullable
rsD.Fields.Append "FName", adVarChar, 255, adFldIsNullable
rsD.Fields.Append "KBSize", adInteger, , adFldIsNullable
rsD.CursorType = adOpenKeyset
rsD.CursorLocation = adUseClient
rsD.LockType = adLockPessimistic
rsD.Open
'Consultar BdD en otro recordset y extraer imagenes a ficheros
Dim rsT As New ADODB.Recordset
Dim cn As New ADODB.Connection
cn.ConnectionString = DimeCadenaConexion
cn.Open
rsT.Open "SELECT CodigoImagen,NombreFichero,KBSize,Imagen FROM Imagenes", cn, adOpenStatic, adLockReadOnly
If Not rsT.EOF Then
'Crear carpeta temporal
Dim sTempFolder As String
sTempFolder = CurrentProject.Path & "\TempImgs"
Dim fso As New FileSystemObject
If Not fso.FolderExists(sTempFolder) Then fso.CreateFolder (sTempFolder)
'Guardar imagen de bdd a fichero
Dim str As New ADODB.Stream
Dim objStream As New ADODB.Stream
objStream.Type = adTypeBinary
objStream.Open
rsT.MoveFirst
Dim i As Long
For i = 1 To rsT.RecordCount
objStream.Write rsT("Imagen")
objStream.SaveToFile sTempFolder & "\" & fso.GetFileName(rsT("NombreFichero")), adSaveCreateOverWrite
'Asignamos valores a recordset dinamico
rsD.AddNew
rsD!CodigoImagen = rsT("CodigoImagen")
rsD!PathFName = sTempFolder & "\" & fso.GetFileName(rsT("NombreFichero"))
rsD!FName = fso.GetFileName(rsT("NombreFichero"))
rsD!KBSize = rsT("KBFichero")
rsD.Update
rsT.MoveNext
Next i
objStream.Close
Set objStream = Nothing
'asignar recordset dinamico al formulario
Set Me.Recordset = rsD
End If
rsD.Close
Set rsD = Nothing
rsT.Close
cn.Close
Set rsT = Nothing
Exit Sub
Resume
error:
MsgBox Err.Number & ": " & Err.Description
End Sub
'3 Textbox con orígenes de control: CodigoImagen, FName y KBSize
Private Sub LoadFormRecordset()
On Error GoTo error
'Crear y abrir recordset dinamico al cual asignaremos valores y finalmente lo asignaremos al recordset del formulario
'https://www.w3schools.com/asp/ado_datatypes.asp
Dim rsD As New ADODB.Recordset
rsD.Fields.Append "CodigoImagen", adInteger, , adFldKeyColumn
rsD.Fields.Append "PathFName", adVarChar, 255, adFldIsNullable
rsD.Fields.Append "FName", adVarChar, 255, adFldIsNullable
rsD.Fields.Append "KBSize", adInteger, , adFldIsNullable
rsD.CursorType = adOpenKeyset
rsD.CursorLocation = adUseClient
rsD.LockType = adLockPessimistic
rsD.Open
'Consultar BdD en otro recordset y extraer imagenes a ficheros
Dim rsT As New ADODB.Recordset
Dim cn As New ADODB.Connection
cn.ConnectionString = DimeCadenaConexion
cn.Open
rsT.Open "SELECT CodigoImagen,NombreFichero,KBSize,Imagen FROM Imagenes", cn, adOpenStatic, adLockReadOnly
If Not rsT.EOF Then
'Crear carpeta temporal
Dim sTempFolder As String
sTempFolder = CurrentProject.Path & "\TempImgs"
Dim fso As New FileSystemObject
If Not fso.FolderExists(sTempFolder) Then fso.CreateFolder (sTempFolder)
'Guardar imagen de bdd a fichero
Dim str As New ADODB.Stream
Dim objStream As New ADODB.Stream
objStream.Type = adTypeBinary
objStream.Open
rsT.MoveFirst
Dim i As Long
For i = 1 To rsT.RecordCount
objStream.Write rsT("Imagen")
objStream.SaveToFile sTempFolder & "\" & fso.GetFileName(rsT("NombreFichero")), adSaveCreateOverWrite
'Asignamos valores a recordset dinamico
rsD.AddNew
rsD!CodigoImagen = rsT("CodigoImagen")
rsD!PathFName = sTempFolder & "\" & fso.GetFileName(rsT("NombreFichero"))
rsD!FName = fso.GetFileName(rsT("NombreFichero"))
rsD!KBSize = rsT("KBFichero")
rsD.Update
rsT.MoveNext
Next i
objStream.Close
Set objStream = Nothing
'asignar recordset dinamico al formulario
Set Me.Recordset = rsD
End If
rsD.Close
Set rsD = Nothing
rsT.Close
cn.Close
Set rsT = Nothing
Exit Sub
Resume
error:
MsgBox Err.Number & ": " & Err.Description
End Sub
VBA Access. Grabar fichero imagen en una tabla Sql Server.
'Ejemplo tabla Sql Server
'TABLE [dbo].[Imagenes](
' [CodigoImagen] [int] NOT NULL,
' [Fichero] [nvarchar](255) NOT NULL,
' [KBSize] [float] NOT NULL CONSTRAINT [DF_Imagenes_New_KBSize] DEFAULT ((0))
' [Imagen] [image] NULL
Option Compare Database
Option Explicit
Private Enum MsoFileDialogType
msoFileDialogOpen = 1 'Permite al usuario abrir un archivo.
msoFileDialogSaveAs = 2 'Permite al usuario guardar un archivo.
msoFileDialogFilePicker = 3 'Permite al usuario seleccionar un archivo.
msoFileDialogFolderPicker = 4 'Permite al usuario seleccionar una carpeta.
End Enum
Private Function SelectItem(ByVal tipo As MsoFileDialogType) As String
On Error GoTo error
Dim fDialog As Object
Dim intResult As Integer
Dim strPath As String
strPath = ""
Set fDialog = Application.FileDialog(tipo)
intResult = Application.FileDialog(tipo).Show
If intResult <> 0 Then
strPath = Application.FileDialog(tipo).SelectedItems(1)
End If
SelectItem = strPath
Exit Function
error:
SelectItem = ""
MsgBox Err.Description
End Function
Private Sub cmdSaveToDB_Click()
On Error GoTo error
Dim sFile As String
sFile = SelectItem(msoFileDialogFilePicker)
If sFile = "" Then Exit Sub
Dim fso As New FileSystemObject
Dim rs As New ADODB.Recordset
Dim cn As New ADODB.Connection
cn.ConnectionString = DimeCadenaConexion
cn.Open
rs.Open "SELECT TOP 0 * FROM Imagenes", cn, adOpenStatic, adLockPessimistic
rs.AddNew
rs!CodigoImagen = cn.Execute("SELECT ISNULL(MAX(CodigoImagen),0) + 1 AS NewCodigoImagen FROM Imagenes")!NewCodigoImagen
rs!Fichero = fso.GetFileName(sFile)
rs!KBSize = Round(fso.GetFile(sFile).Size / 1024, 2)
'insertar imagen a bdd
Dim objStream As New ADODB.Stream
objStream.Type = adTypeBinary
objStream.Open
objStream.LoadFromFile sFile
rs!Imagen = objStream.Read
objStream.Close
Set objStream = Nothing
rs.Update
rs.Close
cn.Close
Set rs = Nothing
Set fso = Nothing
Exit Sub
Resume
error:
MsgBox Err.Number & ": " & Err.Description
End Sub
'TABLE [dbo].[Imagenes](
' [CodigoImagen] [int] NOT NULL,
' [Fichero] [nvarchar](255) NOT NULL,
' [KBSize] [float] NOT NULL CONSTRAINT [DF_Imagenes_New_KBSize] DEFAULT ((0))
' [Imagen] [image] NULL
')
Option Explicit
Private Enum MsoFileDialogType
msoFileDialogOpen = 1 'Permite al usuario abrir un archivo.
msoFileDialogSaveAs = 2 'Permite al usuario guardar un archivo.
msoFileDialogFilePicker = 3 'Permite al usuario seleccionar un archivo.
msoFileDialogFolderPicker = 4 'Permite al usuario seleccionar una carpeta.
End Enum
Private Function SelectItem(ByVal tipo As MsoFileDialogType) As String
On Error GoTo error
Dim fDialog As Object
Dim intResult As Integer
Dim strPath As String
strPath = ""
Set fDialog = Application.FileDialog(tipo)
intResult = Application.FileDialog(tipo).Show
If intResult <> 0 Then
strPath = Application.FileDialog(tipo).SelectedItems(1)
End If
SelectItem = strPath
Exit Function
error:
SelectItem = ""
MsgBox Err.Description
End Function
Private Sub cmdSaveToDB_Click()
On Error GoTo error
Dim sFile As String
sFile = SelectItem(msoFileDialogFilePicker)
If sFile = "" Then Exit Sub
Dim fso As New FileSystemObject
Dim rs As New ADODB.Recordset
Dim cn As New ADODB.Connection
cn.ConnectionString = DimeCadenaConexion
cn.Open
rs.Open "SELECT TOP 0 * FROM Imagenes", cn, adOpenStatic, adLockPessimistic
rs.AddNew
rs!CodigoImagen = cn.Execute("SELECT ISNULL(MAX(CodigoImagen),0) + 1 AS NewCodigoImagen FROM Imagenes")!NewCodigoImagen
rs!Fichero = fso.GetFileName(sFile)
rs!KBSize = Round(fso.GetFile(sFile).Size / 1024, 2)
'insertar imagen a bdd
Dim objStream As New ADODB.Stream
objStream.Type = adTypeBinary
objStream.Open
objStream.LoadFromFile sFile
rs!Imagen = objStream.Read
objStream.Close
Set objStream = Nothing
rs.Update
rs.Close
cn.Close
Set rs = Nothing
Set fso = Nothing
Exit Sub
Resume
error:
MsgBox Err.Number & ": " & Err.Description
End Sub
VBA Access. Listar datos de una tabla Sql Server en un formulario.
Option Compare Database
Option Explicit
Private Sub Form_Open(Cancel As Integer)
Dim rs As New ADODB.Recordset
Dim cn As New ADODB.Connection
cn.ConnectionString = "Provider=SQLNCLI11;DATA SOURCE=localhost;Integrated Security=SSPI;INITIAL CATALOG=CatalogoBD"
cn.Open
rs.CursorLocation = adUseClient
'adLockPessimistic >>> registros son modificables en la bdd des de el formulario
'rs.Open "SELECT * FROM Tabla", cn, adOpenStatic, adLockPessimistic
'solo lectura >>> registros no son modificables
rs.Open "SELECT * FROM Tabla", cn, adOpenStatic, adLockReadOnly
If Not rs.EOF Then
Set Me.Recordset = rs
DoCmd.GoToRecord , , acFirst
End If
rs.Close
cn.Close
End Sub
Option Explicit
Private Sub Form_Open(Cancel As Integer)
Dim rs As New ADODB.Recordset
Dim cn As New ADODB.Connection
cn.ConnectionString = "Provider=SQLNCLI11;DATA SOURCE=localhost;Integrated Security=SSPI;INITIAL CATALOG=CatalogoBD"
cn.Open
rs.CursorLocation = adUseClient
'adLockPessimistic >>> registros son modificables en la bdd des de el formulario
'rs.Open "SELECT * FROM Tabla", cn, adOpenStatic, adLockPessimistic
'solo lectura >>> registros no son modificables
rs.Open "SELECT * FROM Tabla", cn, adOpenStatic, adLockReadOnly
If Not rs.EOF Then
Set Me.Recordset = rs
DoCmd.GoToRecord , , acFirst
End If
rs.Close
cn.Close
End Sub
lunes, 2 de octubre de 2017
VBA Access. Mostrar todas las imágenes en 5 columnas de una carpeta y sus subdirectorios en un formulario continuo utilizando un recordset dinámico.
Option Compare Database
Option Explicit
'Visualizar todas las imágenes de una carpeta y subcarpetas en un formulario simulando 5 registros por fila
'
'Construimos un formulario con
'encabezado formulario:
'1 botón de comando para seleccionar la carpeta con las imagenes
'
'detalles formulario:
'5 controles imagen1,imagen2,imagen3,imagen4,imagen5 y origen del control llamados Img_1,Img_2,Img_3,Img_4,Img_5 en cada uno de ellos
'5 botones transparentes encima de cada imagen
'Por cada imagen, debajo añadimos, 3 textbox con origen del control FName,PathFName,Order, para la segunda imagen FName_2,PathFName_2,Order_2, ...
'
'configurar el formulario en formularios continuos
Private Enum MsoFileDialogType
msoFileDialogOpen = 1 'Permite al usuario abrir un archivo.
msoFileDialogSaveAs = 2 'Permite al usuario guardar un archivo.
msoFileDialogFilePicker = 3 'Permite al usuario seleccionar un archivo.
msoFileDialogFolderPicker = 4 'Permite al usuario seleccionar una carpeta.
End Enum
Private Function SelectItem(ByVal tipo As MsoFileDialogType) As String
On Error GoTo error
Dim fDialog As Object
Dim intResult As Integer
Dim strPath As String
strPath = ""
Set fDialog = Application.FileDialog(tipo)
intResult = Application.FileDialog(tipo).Show
If intResult <> 0 Then
strPath = Application.FileDialog(tipo).SelectedItems(1)
End If
SelectItem = strPath
Exit Function
error:
SelectItem = ""
MsgBox Err.Description
End Function
Private Sub cmbButton1_Click()
MsgBox Me.PathFName
End Sub
Private Sub cmbButton2_Click()
MsgBox Me.PathFName_2
End Sub
Private Sub cmbButton3_Click()
MsgBox Me.PathFName_3
End Sub
Private Sub cmbButton4_Click()
MsgBox Me.PathFName_4
End Sub
Private Sub cmbButton5_Click()
MsgBox Me.PathFName_5
End Sub
Private Sub cmdLoadFolderImageToPictures_Click()
Dim res As Boolean
Dim sFPathFolder As String
sFPathFolder = SelectItem(msoFileDialogFolderPicker)
If sFPathFolder = "" Then Exit Sub
Dim oFileList As New clsFileList
res = oFileList.GetFileList(sFPathFolder)
If Not res Then Exit Sub
Dim rs As New ADODB.Recordset
With rs
.Fields.Append "FName", adVarChar, 255, adFldIsNullable
.Fields.Append "PathFName", adVarChar, 255, adFldKeyColumn
.Fields.Append "Img", adVarChar, 255, adFldIsNullable
.Fields.Append "Order", adInteger, , adFldIsNullable
.Fields.Append "FName_2", adVarChar, 255, adFldIsNullable
.Fields.Append "PathFName_2", adVarChar, 255, adFldKeyColumn
.Fields.Append "Img_2", adVarChar, 255, adFldIsNullable
.Fields.Append "Order_2", adInteger, , adFldIsNullable
.Fields.Append "FName_3", adVarChar, 255, adFldIsNullable
.Fields.Append "PathFName_3", adVarChar, 255, adFldKeyColumn
.Fields.Append "Img_3", adVarChar, 255, adFldIsNullable
.Fields.Append "Order_3", adInteger, , adFldIsNullable
.Fields.Append "FName_4", adVarChar, 255, adFldIsNullable
.Fields.Append "PathFName_4", adVarChar, 255, adFldKeyColumn
.Fields.Append "Img_4", adVarChar, 255, adFldIsNullable
.Fields.Append "Order_4", adInteger, , adFldIsNullable
.Fields.Append "FName_5", adVarChar, 255, adFldIsNullable
.Fields.Append "PathFName_5", adVarChar, 255, adFldKeyColumn
.Fields.Append "Img_5", adVarChar, 255, adFldIsNullable
.Fields.Append "Order_5", adInteger, , adFldIsNullable
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.LockType = adLockPessimistic
.Open
End With
Dim nRecords As Long
nRecords = oFileList.FilesCount
Dim fso As New FileSystemObject
Dim i As Long
Dim j As Integer
For i = 1 To nRecords
rs.AddNew
rs!FName = fso.GetFileName(oFileList.Files(i))
rs!PathFName = oFileList.Files(i)
rs!Img = oFileList.Files(i)
rs!Order = i
j = 0
j = i + 1
If j <= nRecords Then
rs!FName_2 = fso.GetFileName(oFileList.Files(j))
rs!PathFName_2 = oFileList.Files(j)
rs!Img_2 = oFileList.Files(j)
rs!Order_2 = j
End If
j = j + 1
If j <= nRecords Then
rs!FName_3 = fso.GetFileName(oFileList.Files(j))
rs!PathFName_3 = oFileList.Files(j)
rs!Img_3 = oFileList.Files(j)
rs!Order_3 = j
End If
j = j + 1
If j <= nRecords Then
rs!FName_4 = fso.GetFileName(oFileList.Files(j))
rs!PathFName_4 = oFileList.Files(j)
rs!Img_4 = oFileList.Files(j)
rs!Order_4 = j
End If
j = j + 1
If j <= nRecords Then
rs!FName_5 = fso.GetFileName(oFileList.Files(j))
rs!PathFName_5 = oFileList.Files(j)
rs!Img_5 = oFileList.Files(j)
rs!Order_5 = j
End If
rs.Update
i = j
Next i
Set fso = Nothing
'rs.Sort = "PathFname,FName"
'rs.Sort = "FName"
Set Me.Recordset = rs
rs.Close
Set rs = Nothing
End Sub
Option Explicit
'Visualizar todas las imágenes de una carpeta y subcarpetas en un formulario simulando 5 registros por fila
'
'Construimos un formulario con
'encabezado formulario:
'1 botón de comando para seleccionar la carpeta con las imagenes
'
'detalles formulario:
'5 controles imagen1,imagen2,imagen3,imagen4,imagen5 y origen del control llamados Img_1,Img_2,Img_3,Img_4,Img_5 en cada uno de ellos
'5 botones transparentes encima de cada imagen
'Por cada imagen, debajo añadimos, 3 textbox con origen del control FName,PathFName,Order, para la segunda imagen FName_2,PathFName_2,Order_2, ...
'
'configurar el formulario en formularios continuos
Private Enum MsoFileDialogType
msoFileDialogOpen = 1 'Permite al usuario abrir un archivo.
msoFileDialogSaveAs = 2 'Permite al usuario guardar un archivo.
msoFileDialogFilePicker = 3 'Permite al usuario seleccionar un archivo.
msoFileDialogFolderPicker = 4 'Permite al usuario seleccionar una carpeta.
End Enum
Private Function SelectItem(ByVal tipo As MsoFileDialogType) As String
On Error GoTo error
Dim fDialog As Object
Dim intResult As Integer
Dim strPath As String
strPath = ""
Set fDialog = Application.FileDialog(tipo)
intResult = Application.FileDialog(tipo).Show
If intResult <> 0 Then
strPath = Application.FileDialog(tipo).SelectedItems(1)
End If
SelectItem = strPath
Exit Function
error:
SelectItem = ""
MsgBox Err.Description
End Function
Private Sub cmbButton1_Click()
MsgBox Me.PathFName
End Sub
Private Sub cmbButton2_Click()
MsgBox Me.PathFName_2
End Sub
Private Sub cmbButton3_Click()
MsgBox Me.PathFName_3
End Sub
Private Sub cmbButton4_Click()
MsgBox Me.PathFName_4
End Sub
Private Sub cmbButton5_Click()
MsgBox Me.PathFName_5
End Sub
Private Sub cmdLoadFolderImageToPictures_Click()
Dim res As Boolean
Dim sFPathFolder As String
sFPathFolder = SelectItem(msoFileDialogFolderPicker)
If sFPathFolder = "" Then Exit Sub
Dim oFileList As New clsFileList
res = oFileList.GetFileList(sFPathFolder)
If Not res Then Exit Sub
Dim rs As New ADODB.Recordset
With rs
.Fields.Append "FName", adVarChar, 255, adFldIsNullable
.Fields.Append "PathFName", adVarChar, 255, adFldKeyColumn
.Fields.Append "Img", adVarChar, 255, adFldIsNullable
.Fields.Append "Order", adInteger, , adFldIsNullable
.Fields.Append "FName_2", adVarChar, 255, adFldIsNullable
.Fields.Append "PathFName_2", adVarChar, 255, adFldKeyColumn
.Fields.Append "Img_2", adVarChar, 255, adFldIsNullable
.Fields.Append "Order_2", adInteger, , adFldIsNullable
.Fields.Append "FName_3", adVarChar, 255, adFldIsNullable
.Fields.Append "PathFName_3", adVarChar, 255, adFldKeyColumn
.Fields.Append "Img_3", adVarChar, 255, adFldIsNullable
.Fields.Append "Order_3", adInteger, , adFldIsNullable
.Fields.Append "FName_4", adVarChar, 255, adFldIsNullable
.Fields.Append "PathFName_4", adVarChar, 255, adFldKeyColumn
.Fields.Append "Img_4", adVarChar, 255, adFldIsNullable
.Fields.Append "Order_4", adInteger, , adFldIsNullable
.Fields.Append "FName_5", adVarChar, 255, adFldIsNullable
.Fields.Append "PathFName_5", adVarChar, 255, adFldKeyColumn
.Fields.Append "Img_5", adVarChar, 255, adFldIsNullable
.Fields.Append "Order_5", adInteger, , adFldIsNullable
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.LockType = adLockPessimistic
.Open
End With
Dim nRecords As Long
nRecords = oFileList.FilesCount
Dim fso As New FileSystemObject
Dim i As Long
Dim j As Integer
For i = 1 To nRecords
rs.AddNew
rs!FName = fso.GetFileName(oFileList.Files(i))
rs!PathFName = oFileList.Files(i)
rs!Img = oFileList.Files(i)
rs!Order = i
j = 0
j = i + 1
If j <= nRecords Then
rs!FName_2 = fso.GetFileName(oFileList.Files(j))
rs!PathFName_2 = oFileList.Files(j)
rs!Img_2 = oFileList.Files(j)
rs!Order_2 = j
End If
j = j + 1
If j <= nRecords Then
rs!FName_3 = fso.GetFileName(oFileList.Files(j))
rs!PathFName_3 = oFileList.Files(j)
rs!Img_3 = oFileList.Files(j)
rs!Order_3 = j
End If
j = j + 1
If j <= nRecords Then
rs!FName_4 = fso.GetFileName(oFileList.Files(j))
rs!PathFName_4 = oFileList.Files(j)
rs!Img_4 = oFileList.Files(j)
rs!Order_4 = j
End If
j = j + 1
If j <= nRecords Then
rs!FName_5 = fso.GetFileName(oFileList.Files(j))
rs!PathFName_5 = oFileList.Files(j)
rs!Img_5 = oFileList.Files(j)
rs!Order_5 = j
End If
rs.Update
i = j
Next i
Set fso = Nothing
'rs.Sort = "PathFname,FName"
'rs.Sort = "FName"
Set Me.Recordset = rs
rs.Close
Set rs = Nothing
End Sub
domingo, 1 de octubre de 2017
VBA Access. Mostrar todas las imágenes de una carpeta y sus subdirectorios en un formulario continuo utilizando un recordset dinámico.
Option Compare Database
Option Explicit
'Visualizar todas las imágenes de una carpeta y subcarpetas en un formulario
'
'Construimos un formulario con
'encabezado formulario:
'1 botón de comando
'
'detalles formulario:
'1 control imagen y origen del control llamado Img
'3 textbox con origen del control FName, PathFName y Order
'
'configurar el formulario en formularios continuos
Private Enum MsoFileDialogType
msoFileDialogOpen = 1 'Permite al usuario abrir un archivo.
msoFileDialogSaveAs = 2 'Permite al usuario guardar un archivo.
msoFileDialogFilePicker = 3 'Permite al usuario seleccionar un archivo.
msoFileDialogFolderPicker = 4 'Permite al usuario seleccionar una carpeta.
End Enum
Private Function SelectItem(ByVal tipo As MsoFileDialogType) As String
On Error GoTo error
Dim fDialog As Object
Dim intResult As Integer
Dim strPath As String
strPath = ""
Set fDialog = Application.FileDialog(tipo)
intResult = Application.FileDialog(tipo).Show
If intResult <> 0 Then
strPath = Application.FileDialog(tipo).SelectedItems(1)
End If
SelectItem = strPath
Exit Function
error:
SelectItem = ""
MsgBox Err.Description
End Function
Private Sub cmdLoadFolderImageToPictures_Click()
Dim res As Boolean
Dim sFPathFolder As String
sFPathFolder = SelectItem(msoFileDialogFolderPicker)
If sFPathFolder = "" Then Exit Sub
Dim oFileList As New clsFileList
res = oFileList.GetFileList(sFPathFolder)
If Not res Then Exit Sub
Dim rs As New ADODB.Recordset
With rs
.Fields.Append "PathFName", adVarChar, 255, adFldKeyColumn
.Fields.Append "FName", adVarChar, 255, adFldIsNullable
.Fields.Append "Img", adVarChar, 255, adFldIsNullable
.Fields.Append "Order", adInteger, , adFldIsNullable
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.LockType = adLockPessimistic
.Open
End With
Dim fso As New FileSystemObject
Dim i As Long
For i = 1 To oFileList.FilesCount
rs.AddNew
rs!FName = fso.GetFileName(oFileList.Files(i))
rs!PathFName = oFileList.Files(i)
rs!Img = oFileList.Files(i)
rs!Order = i
rs.Update
Next i
Set fso = Nothing
'rs.Sort = "PathFname,FName"
rs.Sort = "FName"
Set Me.Recordset = rs
rs.Close
Set rs = Nothing
End Sub
Option Explicit
'Visualizar todas las imágenes de una carpeta y subcarpetas en un formulario
'
'Construimos un formulario con
'encabezado formulario:
'1 botón de comando
'
'detalles formulario:
'1 control imagen y origen del control llamado Img
'3 textbox con origen del control FName, PathFName y Order
'
'configurar el formulario en formularios continuos
Private Enum MsoFileDialogType
msoFileDialogOpen = 1 'Permite al usuario abrir un archivo.
msoFileDialogSaveAs = 2 'Permite al usuario guardar un archivo.
msoFileDialogFilePicker = 3 'Permite al usuario seleccionar un archivo.
msoFileDialogFolderPicker = 4 'Permite al usuario seleccionar una carpeta.
End Enum
Private Function SelectItem(ByVal tipo As MsoFileDialogType) As String
On Error GoTo error
Dim fDialog As Object
Dim intResult As Integer
Dim strPath As String
strPath = ""
Set fDialog = Application.FileDialog(tipo)
intResult = Application.FileDialog(tipo).Show
If intResult <> 0 Then
strPath = Application.FileDialog(tipo).SelectedItems(1)
End If
SelectItem = strPath
Exit Function
error:
SelectItem = ""
MsgBox Err.Description
End Function
Private Sub cmdLoadFolderImageToPictures_Click()
Dim res As Boolean
Dim sFPathFolder As String
sFPathFolder = SelectItem(msoFileDialogFolderPicker)
If sFPathFolder = "" Then Exit Sub
Dim oFileList As New clsFileList
res = oFileList.GetFileList(sFPathFolder)
If Not res Then Exit Sub
Dim rs As New ADODB.Recordset
With rs
.Fields.Append "PathFName", adVarChar, 255, adFldKeyColumn
.Fields.Append "FName", adVarChar, 255, adFldIsNullable
.Fields.Append "Img", adVarChar, 255, adFldIsNullable
.Fields.Append "Order", adInteger, , adFldIsNullable
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.LockType = adLockPessimistic
.Open
End With
Dim fso As New FileSystemObject
Dim i As Long
For i = 1 To oFileList.FilesCount
rs.AddNew
rs!FName = fso.GetFileName(oFileList.Files(i))
rs!PathFName = oFileList.Files(i)
rs!Img = oFileList.Files(i)
rs!Order = i
rs.Update
Next i
Set fso = Nothing
'rs.Sort = "PathFname,FName"
rs.Sort = "FName"
Set Me.Recordset = rs
rs.Close
Set rs = Nothing
End Sub
VBA Access. Mostrar una imagen en un control imagen.
Option Compare Database
Option Explicit
'Construimos un formulario con:
'1 control imagen llamado Imagen1
'2 textbox llamados txtImagenName y txtImagenPath
Private Enum MsoFileDialogType
msoFileDialogOpen = 1 'Permite al usuario abrir un archivo.
msoFileDialogSaveAs = 2 'Permite al usuario guardar un archivo.
msoFileDialogFilePicker = 3 'Permite al usuario seleccionar un archivo.
msoFileDialogFolderPicker = 4 'Permite al usuario seleccionar una carpeta.
End Enum
Private Function SelectItem(ByVal tipo As MsoFileDialogType) As String
On Error GoTo error
Dim fDialog As Object
Dim intResult As Integer
Dim strPath As String
strPath = ""
Set fDialog = Application.FileDialog(tipo)
intResult = Application.FileDialog(tipo).Show
If intResult <> 0 Then
strPath = Application.FileDialog(tipo).SelectedItems(1)
End If
SelectItem = strPath
Exit Function
error:
SelectItem = ""
MsgBox Err.Description
End Function
Private Sub cmdLoadFileImageToPicture_Click()
On Error GoTo error
Dim sFPathName As String
sFPathName = SelectItem(msoFileDialogFilePicker)
If sFPathName = "" Then Exit Sub
Dim fso As New FileSystemObject
Dim sFName As String
sFName = fso.GetFileName(sFPathName)
Me.txtImagenName = sFName
Me.txtImagenPath = sFPathName
Me.Imagen1.Picture = sFPathName
Set fso = Nothing
Exit Sub
error:
MsgBox Err.Description
End Sub
Option Explicit
'Construimos un formulario con:
'1 control imagen llamado Imagen1
'2 textbox llamados txtImagenName y txtImagenPath
Private Enum MsoFileDialogType
msoFileDialogOpen = 1 'Permite al usuario abrir un archivo.
msoFileDialogSaveAs = 2 'Permite al usuario guardar un archivo.
msoFileDialogFilePicker = 3 'Permite al usuario seleccionar un archivo.
msoFileDialogFolderPicker = 4 'Permite al usuario seleccionar una carpeta.
End Enum
Private Function SelectItem(ByVal tipo As MsoFileDialogType) As String
On Error GoTo error
Dim fDialog As Object
Dim intResult As Integer
Dim strPath As String
strPath = ""
Set fDialog = Application.FileDialog(tipo)
intResult = Application.FileDialog(tipo).Show
If intResult <> 0 Then
strPath = Application.FileDialog(tipo).SelectedItems(1)
End If
SelectItem = strPath
Exit Function
error:
SelectItem = ""
MsgBox Err.Description
End Function
Private Sub cmdLoadFileImageToPicture_Click()
On Error GoTo error
Dim sFPathName As String
sFPathName = SelectItem(msoFileDialogFilePicker)
If sFPathName = "" Then Exit Sub
Dim fso As New FileSystemObject
Dim sFName As String
sFName = fso.GetFileName(sFPathName)
Me.txtImagenName = sFName
Me.txtImagenPath = sFPathName
Me.Imagen1.Picture = sFPathName
Set fso = Nothing
Exit Sub
error:
MsgBox Err.Description
End Sub
viernes, 29 de septiembre de 2017
VBA Access. Funciones para guardar imagen a Bdd, leer de Bdd y volcar a fichero, leer de Bdd y mostrar en un control Imagen del formulario.
' SQL Server, Tabla Imagenes
' [Id] [int] NOT NULL,
' [Descripcion] [nvarchar](250) NULL,
' [Imagen] [varbinary](max) NULL,
Function AddFileImageToBdd(ByVal Id As Long, ByVal sDescripcion As String, ByVal sFName As String) As Boolean
On Error GoTo error
Dim rs As ADODB.Recordset
Dim objStream As New ADODB.Stream
'create the stream
objStream.Type = adTypeBinary
objStream.Open
objStream.LoadFromFile sFName
Set rs = GetRecordset("SELECT TOP 0 * FROM Imagenes")
With rs
.AddNew
!Id = Id
!Descripcion = sDescripcion
!Imagen = objStream.Read
.Update
.Close
End With
Set rs = Nothing
objStream.Close
Set objStream = Nothing
AddFileImageToBdd = True
Exit Function
error:
AddFileImageToBdd = False
Debug.Print Err.Description
End Function
Function ReadFileImageBdd(ByVal Id As Long, ByVal sDescripcion As String, ByVal sFName As String) As Boolean
On Error GoTo error
Dim rs As ADODB.Recordset
Dim objStream As New ADODB.Stream
'create the stream
objStream.Type = adTypeBinary
objStream.Open
Set rs = GetRecordset("SELECT Imagen FROM Imagenes WHERE Id = " & Id)
If Not rs.EOF Then
objStream.Write rs!Imagen
objStream.SaveToFile sFName, adSaveCreateOverWrite
End If
rs.Close
Set rs = Nothing
objStream.Close
Set objStream = Nothing
ReadFileImageBdd = True
Exit Function
error:
ReadFileImageBdd = False
Debug.Print Err.Description
End Function
Function ReadFileImageBddToPicture(ByVal Id As Long, ByRef ImgCtl As image) As Boolean
On Error GoTo error
Dim rs As ADODB.Recordset
Dim objStream As New ADODB.Stream
'create the stream
objStream.Type = adTypeBinary
objStream.Open
Set rs = GetRecordset("SELECT Imagen FROM Imagenes WHERE Id = " & Id)
If Not rs.EOF Then
objStream.Write rs!Imagen
objStream.Position = 0
ImgCtl.PictureData = objStream.Read ' load bytes into Image control on form
End If
rs.Close
Set rs = Nothing
objStream.Close
Set objStream = Nothing
ReadFileImageBddToPicture = True
Exit Function
Resume
error:
ReadFileImageBddToPicture = False
Debug.Print Err.Description
End Function
' [Id] [int] NOT NULL,
' [Descripcion] [nvarchar](250) NULL,
' [Imagen] [varbinary](max) NULL,
Function AddFileImageToBdd(ByVal Id As Long, ByVal sDescripcion As String, ByVal sFName As String) As Boolean
On Error GoTo error
Dim rs As ADODB.Recordset
Dim objStream As New ADODB.Stream
'create the stream
objStream.Type = adTypeBinary
objStream.Open
objStream.LoadFromFile sFName
Set rs = GetRecordset("SELECT TOP 0 * FROM Imagenes")
With rs
.AddNew
!Id = Id
!Descripcion = sDescripcion
!Imagen = objStream.Read
.Update
.Close
End With
Set rs = Nothing
objStream.Close
Set objStream = Nothing
AddFileImageToBdd = True
Exit Function
error:
AddFileImageToBdd = False
Debug.Print Err.Description
End Function
Function ReadFileImageBdd(ByVal Id As Long, ByVal sDescripcion As String, ByVal sFName As String) As Boolean
On Error GoTo error
Dim rs As ADODB.Recordset
Dim objStream As New ADODB.Stream
'create the stream
objStream.Type = adTypeBinary
objStream.Open
Set rs = GetRecordset("SELECT Imagen FROM Imagenes WHERE Id = " & Id)
If Not rs.EOF Then
objStream.Write rs!Imagen
objStream.SaveToFile sFName, adSaveCreateOverWrite
End If
rs.Close
Set rs = Nothing
objStream.Close
Set objStream = Nothing
ReadFileImageBdd = True
Exit Function
error:
ReadFileImageBdd = False
Debug.Print Err.Description
End Function
Function ReadFileImageBddToPicture(ByVal Id As Long, ByRef ImgCtl As image) As Boolean
On Error GoTo error
Dim rs As ADODB.Recordset
Dim objStream As New ADODB.Stream
'create the stream
objStream.Type = adTypeBinary
objStream.Open
Set rs = GetRecordset("SELECT Imagen FROM Imagenes WHERE Id = " & Id)
If Not rs.EOF Then
objStream.Write rs!Imagen
objStream.Position = 0
ImgCtl.PictureData = objStream.Read ' load bytes into Image control on form
End If
rs.Close
Set rs = Nothing
objStream.Close
Set objStream = Nothing
ReadFileImageBddToPicture = True
Exit Function
Resume
error:
ReadFileImageBddToPicture = False
Debug.Print Err.Description
End Function
VBA Access. Módulo de clase clsWindowExists para comprobar si una ventana de aplicación Windows existe por su nombre parcial. Window Exists.
Option Compare Database
Option Explicit
'http://www.vbforums.com/showthread.php?316924-Find-Window-handle-by-Partial-Caption
'Windows API Function Declarations
#If Win64 = 1 Then
Private Declare PtrSafe Function FindWindow Lib "User32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare PtrSafe Function GetWindowText Lib "User32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare PtrSafe Function GetWindowTextLength Lib "User32" Alias "GetWindowTextLengthA" (ByVal hWnd As Long) As Long
Private Declare PtrSafe Function GetWindow Lib "User32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare PtrSafe Function IsWindowVisible Lib "User32" (ByVal hWnd As Long) As Boolean
#Else
Private Declare Function FindWindow Lib "User32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetWindowText Lib "User32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function GetWindowTextLength Lib "User32" Alias "GetWindowTextLengthA" (ByVal hWnd As Long) As Long
Private Declare Function GetWindow Lib "User32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare Function IsWindowVisible Lib "User32" (ByVal hWnd As Long) As Boolean
#End If
#If Win64 = 1 Then
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems
#Else
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'For 32 Bit Systems
#End If
Private Const GW_HWNDNEXT = 2
Public Function WindowExists(ByVal PartialCaption As String) As Boolean
On Error GoTo error
Dim lhWndP As Long
If GetHandleFromPartialCaption(lhWndP, PartialCaption) = True Then
If IsWindowVisible(lhWndP) = True Then
Debug.Print "Found VISIBLE Window Handle: " & lhWndP, vbOKOnly + vbInformation
Else
Debug.Print "Found INVISIBLE Window Handle: " & lhWndP, vbOKOnly + vbInformation
End If
WindowExists = True
Else
Debug.Print "Window '" & PartialCaption & "' not found!", vbOKOnly + vbExclamation
WindowExists = False
End If
Exit Function
error:
WindowExists = False
Debug.Print Err.Number & ": " & Err.Description
End Function
Public Sub LoopWhileWindowsExists(ByVal PartialCaption As String, Optional ByVal CheckTimeMilliSeconds As Long = 3000)
On Error GoTo error
Do
Sleep (CheckTimeMilliSeconds)
Loop Until Not WindowExists(PartialCaption)
Exit Sub
error:
Debug.Print Err.Number & ": " & Err.Description
End Sub
Private Function GetHandleFromPartialCaption(ByRef lWnd As Long, ByVal sCaption As String) As Boolean
Dim lhWndP As Long
Dim sStr As String
GetHandleFromPartialCaption = False
lhWndP = FindWindow(vbNullString, vbNullString) 'PARENT WINDOW
Do While lhWndP <> 0
sStr = String(GetWindowTextLength(lhWndP) + 1, Chr$(0))
GetWindowText lhWndP, sStr, Len(sStr)
sStr = Left$(sStr, Len(sStr) - 1)
If InStr(1, sStr, sCaption) > 0 Then
GetHandleFromPartialCaption = True
lWnd = lhWndP
Exit Do
End If
lhWndP = GetWindow(lhWndP, GW_HWNDNEXT)
Loop
End Function
Option Explicit
'http://www.vbforums.com/showthread.php?316924-Find-Window-handle-by-Partial-Caption
'Windows API Function Declarations
#If Win64 = 1 Then
Private Declare PtrSafe Function FindWindow Lib "User32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare PtrSafe Function GetWindowText Lib "User32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare PtrSafe Function GetWindowTextLength Lib "User32" Alias "GetWindowTextLengthA" (ByVal hWnd As Long) As Long
Private Declare PtrSafe Function GetWindow Lib "User32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare PtrSafe Function IsWindowVisible Lib "User32" (ByVal hWnd As Long) As Boolean
#Else
Private Declare Function FindWindow Lib "User32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetWindowText Lib "User32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function GetWindowTextLength Lib "User32" Alias "GetWindowTextLengthA" (ByVal hWnd As Long) As Long
Private Declare Function GetWindow Lib "User32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare Function IsWindowVisible Lib "User32" (ByVal hWnd As Long) As Boolean
#End If
#If Win64 = 1 Then
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems
#Else
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'For 32 Bit Systems
#End If
Private Const GW_HWNDNEXT = 2
Public Function WindowExists(ByVal PartialCaption As String) As Boolean
On Error GoTo error
Dim lhWndP As Long
If GetHandleFromPartialCaption(lhWndP, PartialCaption) = True Then
If IsWindowVisible(lhWndP) = True Then
Debug.Print "Found VISIBLE Window Handle: " & lhWndP, vbOKOnly + vbInformation
Else
Debug.Print "Found INVISIBLE Window Handle: " & lhWndP, vbOKOnly + vbInformation
End If
WindowExists = True
Else
Debug.Print "Window '" & PartialCaption & "' not found!", vbOKOnly + vbExclamation
WindowExists = False
End If
Exit Function
error:
WindowExists = False
Debug.Print Err.Number & ": " & Err.Description
End Function
Public Sub LoopWhileWindowsExists(ByVal PartialCaption As String, Optional ByVal CheckTimeMilliSeconds As Long = 3000)
On Error GoTo error
Do
Sleep (CheckTimeMilliSeconds)
Loop Until Not WindowExists(PartialCaption)
Exit Sub
error:
Debug.Print Err.Number & ": " & Err.Description
End Sub
Private Function GetHandleFromPartialCaption(ByRef lWnd As Long, ByVal sCaption As String) As Boolean
Dim lhWndP As Long
Dim sStr As String
GetHandleFromPartialCaption = False
lhWndP = FindWindow(vbNullString, vbNullString) 'PARENT WINDOW
Do While lhWndP <> 0
sStr = String(GetWindowTextLength(lhWndP) + 1, Chr$(0))
GetWindowText lhWndP, sStr, Len(sStr)
sStr = Left$(sStr, Len(sStr) - 1)
If InStr(1, sStr, sCaption) > 0 Then
GetHandleFromPartialCaption = True
lWnd = lhWndP
Exit Do
End If
lhWndP = GetWindow(lhWndP, GW_HWNDNEXT)
Loop
End Function
VBA Access. Seleccionar fichero, carpeta, nombre de fichero guardar como, nombre de fichero a abrir
Option Compare Database
Option Explicit
'*****************************
' 'Ejemplo de uso
msoFileDialogSaveAs = 2 'Permite al usuario guardar un archivo.
msoFileDialogFilePicker = 3 'Permite al usuario seleccionar un archivo.
msoFileDialogFolderPicker = 4 'Permite al usuario seleccionar una carpeta.
End Enum
Public Function SelectItem(ByVal tipo As MsoFileDialogType, Optional ByVal filtro As String, Optional ByVal bMultiSelect As Boolean = False, Optional TituloVentana As String = "") As String()
On Error GoTo error
Dim fDialog As Object
Dim intResult As Integer
Dim i As Long
Dim items() As String
Set fDialog = Application.FileDialog(tipo)
'Optional: FileDialog properties
'fDialog.AllowMultiSelect = False
'fDialog.title = "título de ventana"
'fDialog.InitialFileName = "C:\"
'Optional: Add filters
'fDialog.Filters.Clear
'fDialog.Filters.Add "File images", "*.jpeg"
'fDialog.Filters.Add "All files", "*.*"
'Optional
'Application.FileDialog(tipo).ButtonName = "nombre del botón personalizado El nombre del botón : 'Abrir' por defecto"
If TituloVentana <> "" Then fDialog.Title = TituloVentana
fDialog.AllowMultiSelect = bMultiSelect
If tipo = msoFileDialogFilePicker Then
'limpiamos historial de filtros
fDialog.Filters.Clear
'aplicamos filtro
If Nz(filtro, "") <> "" Then
fDialog.Filters.Add filtro, filtro
End If
End If
intResult = Application.FileDialog(tipo).Show
If intResult <> 0 Then
For i = 0 To Application.FileDialog(tipo).SelectedItems.Count - 1
ReDim Preserve items(i)
items(i) = Application.FileDialog(tipo).SelectedItems(i + 1)
Next
End If
Set fDialog = Nothing
SelectItem = items
Exit Function
Resume
error:
Set fDialog = Nothing
MsgBox Err.Description
End Function
Option Explicit
'*****************************
' 'Ejemplo de uso
' 'selecciona 1 fichero de Excel
' Dim RutaDoc() As String
' RutaDoc = SelectItem(msoFileDialogFilePicker, "*.xls,*.xlsx", False, "Selección de fichero Excel")
'
' 'comprueba si se ha seleccionado un fichero
' If Len(Join(RutaDoc)) > 0 Then
' Debug.Print "Fichero seleccionado: " & RutaDoc(0)
' End If
'*****************************/
Public Enum MsoFileDialogType
msoFileDialogOpen = 1 'Permite al usuario abrir un archivo.msoFileDialogSaveAs = 2 'Permite al usuario guardar un archivo.
msoFileDialogFilePicker = 3 'Permite al usuario seleccionar un archivo.
msoFileDialogFolderPicker = 4 'Permite al usuario seleccionar una carpeta.
End Enum
Public Function SelectItem(ByVal tipo As MsoFileDialogType, Optional ByVal filtro As String, Optional ByVal bMultiSelect As Boolean = False, Optional TituloVentana As String = "") As String()
On Error GoTo error
Dim fDialog As Object
Dim intResult As Integer
Dim i As Long
Dim items() As String
Set fDialog = Application.FileDialog(tipo)
'Optional: FileDialog properties
'fDialog.AllowMultiSelect = False
'fDialog.title = "título de ventana"
'fDialog.InitialFileName = "C:\"
'Optional: Add filters
'fDialog.Filters.Clear
'fDialog.Filters.Add "File images", "*.jpeg"
'fDialog.Filters.Add "All files", "*.*"
'Optional
'Application.FileDialog(tipo).ButtonName = "nombre del botón personalizado El nombre del botón : 'Abrir' por defecto"
If TituloVentana <> "" Then fDialog.Title = TituloVentana
fDialog.AllowMultiSelect = bMultiSelect
If tipo = msoFileDialogFilePicker Then
'limpiamos historial de filtros
fDialog.Filters.Clear
'aplicamos filtro
If Nz(filtro, "") <> "" Then
fDialog.Filters.Add filtro, filtro
End If
End If
intResult = Application.FileDialog(tipo).Show
If intResult <> 0 Then
For i = 0 To Application.FileDialog(tipo).SelectedItems.Count - 1
ReDim Preserve items(i)
items(i) = Application.FileDialog(tipo).SelectedItems(i + 1)
Next
End If
Set fDialog = Nothing
SelectItem = items
Exit Function
Resume
error:
Set fDialog = Nothing
MsgBox Err.Description
End Function
lunes, 25 de septiembre de 2017
VBA Access. Módulo de clase clsFileList. Obtiene listado de ficheros, carpetas y el número total de ficheros y carpetas encontrados. La búsqueda puede ser recursiva o no.
Option Compare Database
Option Explicit
'#########################################################################################################################################
'GetFileList(Folder,Optional bRecursive=true)
'Obtiene la lista de ficheros y carpetas recursivamente de una carpeta / La búsqueda recursiva es opcional
'Si GetFileList = False, han habido errores y los resultados obtenidos no son fiables (por ejemplo un error de permiso de acceso denegado)
'
'Ejemplo de uso:
'Dim res As Boolean
'Dim oFileList As New clsFileList
'res = oFileList.GetFileList("C:\Temp")
'Debug.Print "#Folders : " & UBound(oFileList.Folders)
'Debug.Print "FoldersCount: " & oFileList.FoldersCount
'Debug.Print "#Files : " & UBound(oFileList.Files)
'Debug.Print "FilesCount: " & oFileList.FilesCount
'Set oFileList = Nothing
'
'Tip: Comprobar si un array está vacío
'(not arrayName) = -1
'#########################################################################################################################################
Private m_Folder As String
Private m_Files() As String
Private m_FilesCount As Long
Private m_FoldersCount As Long
Private m_Folders() As String
Private Sub Class_Initialize()
'initialize values
FilesCount = 0
FoldersCount = 0
End Sub
Private Sub Class_Terminate()
'deallocate if needed
End Sub
Public Sub InitiateProperties(ByRef ArrayFolders() As String, ByVal FoldersCount As Long, ByRef ArrayFiles() As String, ByVal FilesCount As Long)
On Error GoTo error
ReDim Preserve m_Files(UBound(ArrayFiles))
m_Files = ArrayFiles
m_FilesCount = FilesCount
ReDim Preserve m_Folders(UBound(ArrayFolders))
m_Folders = ArrayFolders
m_FoldersCount = FoldersCount
Exit Sub
error:
Debug.Print Err.Description
End Sub
Public Property Get Files()
Files = m_Files
End Property
Public Property Get FilesCount() As Long
FilesCount = m_FilesCount
End Property
Public Property Let FilesCount(ByVal Value As Long)
m_FilesCount = Value
End Property
Public Property Get Folders()
Folders = m_Folders
End Property
Public Property Get FoldersCount() As Long
FoldersCount = m_FoldersCount
End Property
Public Property Let FoldersCount(ByVal Value As Long)
m_FoldersCount = Value
End Property
Public Property Get Folder() As String
Folder = m_Folder
End Property
Public Property Let Folder(ByVal Value As String)
m_Folder = Value
End Property
Public Function GetFileList(ByVal Folder As String, Optional ByVal bRecursivo As Boolean = True) As Boolean
On Error GoTo error
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim res As Boolean
Dim resR As Boolean
res = True
resR = True
Debug.Print Folder & vbNewLine
If Dir(Folder, vbDirectory) <> "" Then
'root folder not included
If (Not m_Folders) <> -1 Then
'Add folder to array
m_Folders(UBound(m_Folders)) = Folder
End If
End If
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Folder)
'Add files to array and count them
For Each objFile In objFolder.Files
If (Not m_Files) = -1 Then
ReDim Preserve m_Files(1)
Else
ReDim Preserve m_Files(UBound(m_Files) + 1)
End If
'Count files
FilesCount = UBound(m_Files)
'Add file to array
m_Files(FilesCount) = objFile.path
Debug.Print vbTab & objFile.path & vbNewLine
Next objFile
'loops through each folder in the directory
For Each objSubFolder In objFolder.SubFolders
'Count folders
FoldersCount = FoldersCount + 1
'recursive search
If bRecursivo Then
Dim SubFolders() As String
Dim oFileList As New clsFileList
If (Not m_Folders) = -1 Then
'1st item
ReDim Preserve m_Folders(1)
Else
ReDim Preserve m_Folders(UBound(m_Folders) + 1)
End If
oFileList.InitiateProperties m_Folders, UBound(m_Folders), m_Files, m_FilesCount
resR = oFileList.GetFileList(objSubFolder.path, bRecursivo)
m_Files = oFileList.Files
FilesCount = oFileList.FilesCount
m_Folders = oFileList.Folders
FoldersCount = oFileList.FoldersCount
Set oFileList = Nothing
End If
res = res And resR
DoEvents
Next objSubFolder
Set objFolder = Nothing
Set objSubFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
GetFileList = res
Exit Function
Resume
error:
GetFileList = False
Debug.Print vbTab & ">>>> " & "Error " & Err.Number & ", " & Err.Description & " <<<<"
End Function
Option Explicit
'#########################################################################################################################################
'GetFileList(Folder,Optional bRecursive=true)
'Obtiene la lista de ficheros y carpetas recursivamente de una carpeta / La búsqueda recursiva es opcional
'Si GetFileList = False, han habido errores y los resultados obtenidos no son fiables (por ejemplo un error de permiso de acceso denegado)
'
'Ejemplo de uso:
'Dim res As Boolean
'Dim oFileList As New clsFileList
'res = oFileList.GetFileList("C:\Temp")
'Debug.Print "#Folders : " & UBound(oFileList.Folders)
'Debug.Print "FoldersCount: " & oFileList.FoldersCount
'Debug.Print "#Files : " & UBound(oFileList.Files)
'Debug.Print "FilesCount: " & oFileList.FilesCount
'Set oFileList = Nothing
'
'Tip: Comprobar si un array está vacío
'(not arrayName) = -1
'#########################################################################################################################################
Private m_Folder As String
Private m_Files() As String
Private m_FilesCount As Long
Private m_FoldersCount As Long
Private m_Folders() As String
Private Sub Class_Initialize()
'initialize values
FilesCount = 0
FoldersCount = 0
End Sub
Private Sub Class_Terminate()
'deallocate if needed
End Sub
Public Sub InitiateProperties(ByRef ArrayFolders() As String, ByVal FoldersCount As Long, ByRef ArrayFiles() As String, ByVal FilesCount As Long)
On Error GoTo error
ReDim Preserve m_Files(UBound(ArrayFiles))
m_Files = ArrayFiles
m_FilesCount = FilesCount
ReDim Preserve m_Folders(UBound(ArrayFolders))
m_Folders = ArrayFolders
m_FoldersCount = FoldersCount
Exit Sub
error:
Debug.Print Err.Description
End Sub
Public Property Get Files()
Files = m_Files
End Property
Public Property Get FilesCount() As Long
FilesCount = m_FilesCount
End Property
Public Property Let FilesCount(ByVal Value As Long)
m_FilesCount = Value
End Property
Public Property Get Folders()
Folders = m_Folders
End Property
Public Property Get FoldersCount() As Long
FoldersCount = m_FoldersCount
End Property
Public Property Let FoldersCount(ByVal Value As Long)
m_FoldersCount = Value
End Property
Public Property Get Folder() As String
Folder = m_Folder
End Property
Public Property Let Folder(ByVal Value As String)
m_Folder = Value
End Property
Public Function GetFileList(ByVal Folder As String, Optional ByVal bRecursivo As Boolean = True) As Boolean
On Error GoTo error
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim res As Boolean
Dim resR As Boolean
res = True
resR = True
Debug.Print Folder & vbNewLine
If Dir(Folder, vbDirectory) <> "" Then
'root folder not included
If (Not m_Folders) <> -1 Then
'Add folder to array
m_Folders(UBound(m_Folders)) = Folder
End If
End If
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Folder)
'Add files to array and count them
For Each objFile In objFolder.Files
If (Not m_Files) = -1 Then
ReDim Preserve m_Files(1)
Else
ReDim Preserve m_Files(UBound(m_Files) + 1)
End If
'Count files
FilesCount = UBound(m_Files)
'Add file to array
m_Files(FilesCount) = objFile.path
Debug.Print vbTab & objFile.path & vbNewLine
Next objFile
'loops through each folder in the directory
For Each objSubFolder In objFolder.SubFolders
'Count folders
FoldersCount = FoldersCount + 1
'recursive search
If bRecursivo Then
Dim SubFolders() As String
Dim oFileList As New clsFileList
If (Not m_Folders) = -1 Then
'1st item
ReDim Preserve m_Folders(1)
Else
ReDim Preserve m_Folders(UBound(m_Folders) + 1)
End If
oFileList.InitiateProperties m_Folders, UBound(m_Folders), m_Files, m_FilesCount
resR = oFileList.GetFileList(objSubFolder.path, bRecursivo)
m_Files = oFileList.Files
FilesCount = oFileList.FilesCount
m_Folders = oFileList.Folders
FoldersCount = oFileList.FoldersCount
Set oFileList = Nothing
End If
res = res And resR
DoEvents
Next objSubFolder
Set objFolder = Nothing
Set objSubFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
GetFileList = res
Exit Function
Resume
error:
GetFileList = False
Debug.Print vbTab & ">>>> " & "Error " & Err.Number & ", " & Err.Description & " <<<<"
End Function
viernes, 15 de septiembre de 2017
VBA Access. Módulo de clase clsImageResize usando WIA. Redimensionar / cambiar de resolución una imagen.
'---------------------------------------------------------------------------------------
' Procedure : WIA_ResizeImage
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Resize an image based on Max width and Max height using WIA
' Copyright : The following may be altered and reused as you wish so long as the
' copyright notice is left unchanged (including Author, Website and
' Copyright). It may not be sold/resold or reposted on other sites (links
' back to this site are allowed).
' Req'd Refs: Uses Late Binding, so none required
'
' Windows Image Acquisition (WIA)
' https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sInitialImage : Fully qualified path and filename of the original image to resize
' sResizedImage : Fully qualified path and filename of where to save the resized image
' lMaximumWidth : Maximum allowable image width
' lMaximumHeight: Maximum allowable image height
'
' Usage:
' ~~~~~~
' Call WIA_ResizeImage("C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg", _
' "C:\Users\MyUser\Desktop\Chrysanthemum_small.jpg", _
' 800, 600)
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2017-01-18 Initial Release
'---------------------------------------------------------------------------------------
Public Function WIA_ResizeImage(sInitialImage As String, sResizedImage As String, _
lMaximumWidth As Long, lMaximumHeight As Long) As Boolean
On Error GoTo Error_Handler
Dim oWIA As Object 'WIA.ImageFile
Dim oIP As Object 'ImageProcess
Set oWIA = CreateObject("WIA.ImageFile")
Set oIP = CreateObject("WIA.ImageProcess")
oIP.Filters.Add oIP.FilterInfos("Scale").FilterID
oIP.Filters(1).Properties("MaximumWidth") = lMaximumWidth
oIP.Filters(1).Properties("MaximumHeight") = lMaximumHeight
oWIA.LoadFile sInitialImage
Set oWIA = oIP.Apply(oWIA)
oWIA.SaveFile sResizedImage
WIA_ResizeImage = True
Error_Handler_Exit:
On Error Resume Next
If Not oIP Is Nothing Then Set oIP = Nothing
If Not oWIA Is Nothing Then Set oWIA = Nothing
Exit Function
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: WIA_ResizeImage" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Function
' Procedure : WIA_ResizeImage
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Resize an image based on Max width and Max height using WIA
' Copyright : The following may be altered and reused as you wish so long as the
' copyright notice is left unchanged (including Author, Website and
' Copyright). It may not be sold/resold or reposted on other sites (links
' back to this site are allowed).
' Req'd Refs: Uses Late Binding, so none required
'
' Windows Image Acquisition (WIA)
' https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sInitialImage : Fully qualified path and filename of the original image to resize
' sResizedImage : Fully qualified path and filename of where to save the resized image
' lMaximumWidth : Maximum allowable image width
' lMaximumHeight: Maximum allowable image height
'
' Usage:
' ~~~~~~
' Call WIA_ResizeImage("C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg", _
' "C:\Users\MyUser\Desktop\Chrysanthemum_small.jpg", _
' 800, 600)
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2017-01-18 Initial Release
'---------------------------------------------------------------------------------------
Public Function WIA_ResizeImage(sInitialImage As String, sResizedImage As String, _
lMaximumWidth As Long, lMaximumHeight As Long) As Boolean
On Error GoTo Error_Handler
Dim oWIA As Object 'WIA.ImageFile
Dim oIP As Object 'ImageProcess
Set oWIA = CreateObject("WIA.ImageFile")
Set oIP = CreateObject("WIA.ImageProcess")
oIP.Filters.Add oIP.FilterInfos("Scale").FilterID
oIP.Filters(1).Properties("MaximumWidth") = lMaximumWidth
oIP.Filters(1).Properties("MaximumHeight") = lMaximumHeight
oWIA.LoadFile sInitialImage
Set oWIA = oIP.Apply(oWIA)
oWIA.SaveFile sResizedImage
WIA_ResizeImage = True
Error_Handler_Exit:
On Error Resume Next
If Not oIP Is Nothing Then Set oIP = Nothing
If Not oWIA Is Nothing Then Set oWIA = Nothing
Exit Function
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: WIA_ResizeImage" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Function
VBA Access. Módulo de clase clsImageConvert usando WIA. Convertir formatos de imagen (BMP.JPEG,PNG,TIFF).
Public Enum wiaFormat
BMP = 0
GIF = 1
JPEG = 2
PNG = 3
TIFF = 4
End Enum
'---------------------------------------------------------------------------------------
' Procedure : WIA_ConvertImage
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Convert an image's format using WIA
' Copyright : The following may be altered and reused as you wish so long as the
' copyright notice is left unchanged (including Author, Website and
' Copyright). It may not be sold/resold or reposted on other sites (links
' back to this site are allowed).
' Req'd Refs: Uses Late Binding, so none required
'
' Windows Image Acquisition (WIA)
' https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sInitialImage : Fully qualified path and filename of the original image to resize
' sOutputImage : Fully qualified path and filename of where to save the new image
' lFormat : Format to convert the image into
' lQuality : Quality level to be used for the conversion process (1-100)
'
' Usage:
' ~~~~~~
' Call WIA_ConvertImage("C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg", _
' "C:\Users\MyUser\Desktop\Chrysanthemum_2.jpg", _
' JPEG)
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2017-01-18 Initial Release
'---------------------------------------------------------------------------------------
Public Function WIA_ConvertImage(sInitialImage As String, _
sOutputImage As String, _
lFormat As wiaFormat, _
Optional lQuality As Long = 85) As Boolean
On Error GoTo Error_Handler
Dim oWIA As Object 'WIA.ImageFile
Dim oIP As Object 'ImageProcess
Dim sFormatID As String
Dim sExt As String
'Convert our Enum over to the proper value used by WIA
Select Case lFormat
Case 0
sFormatID = "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}"
sExt = "BMP"
Case 1
sFormatID = "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}"
sExt = "GIF"
Case 2
sFormatID = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"
sExt = "JPEG"
Case 3
sFormatID = "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}"
sExt = "PNG"
Case 4
sFormatID = "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}"
sExt = "TIFF"
End Select
If lQuality > 100 Then lQuality = 100
'Should check if the output file already exists and if so,
'prompt the user to overwrite it or not
Set oWIA = CreateObject("WIA.ImageFile")
Set oIP = CreateObject("WIA.ImageProcess")
oIP.Filters.Add oIP.FilterInfos("Convert").FilterID
oIP.Filters(1).Properties("FormatID") = sFormatID
oIP.Filters(1).Properties("Quality") = lQuality
oWIA.LoadFile sInitialImage
Set oWIA = oIP.Apply(oWIA)
'Overide the specified ext with the appropriate one for the choosen format
oWIA.SaveFile Left(sOutputImage, InStrRev(sOutputImage, ".")) & LCase(sExt)
WIA_ConvertImage = True
Error_Handler_Exit:
On Error Resume Next
If Not oIP Is Nothing Then Set oIP = Nothing
If Not oWIA Is Nothing Then Set oWIA = Nothing
Exit Function
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: WIA_ConvertImage" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Function
BMP = 0
GIF = 1
JPEG = 2
PNG = 3
TIFF = 4
End Enum
'---------------------------------------------------------------------------------------
' Procedure : WIA_ConvertImage
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Convert an image's format using WIA
' Copyright : The following may be altered and reused as you wish so long as the
' copyright notice is left unchanged (including Author, Website and
' Copyright). It may not be sold/resold or reposted on other sites (links
' back to this site are allowed).
' Req'd Refs: Uses Late Binding, so none required
'
' Windows Image Acquisition (WIA)
' https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sInitialImage : Fully qualified path and filename of the original image to resize
' sOutputImage : Fully qualified path and filename of where to save the new image
' lFormat : Format to convert the image into
' lQuality : Quality level to be used for the conversion process (1-100)
'
' Usage:
' ~~~~~~
' Call WIA_ConvertImage("C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg", _
' "C:\Users\MyUser\Desktop\Chrysanthemum_2.jpg", _
' JPEG)
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2017-01-18 Initial Release
'---------------------------------------------------------------------------------------
Public Function WIA_ConvertImage(sInitialImage As String, _
sOutputImage As String, _
lFormat As wiaFormat, _
Optional lQuality As Long = 85) As Boolean
On Error GoTo Error_Handler
Dim oWIA As Object 'WIA.ImageFile
Dim oIP As Object 'ImageProcess
Dim sFormatID As String
Dim sExt As String
'Convert our Enum over to the proper value used by WIA
Select Case lFormat
Case 0
sFormatID = "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}"
sExt = "BMP"
Case 1
sFormatID = "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}"
sExt = "GIF"
Case 2
sFormatID = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"
sExt = "JPEG"
Case 3
sFormatID = "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}"
sExt = "PNG"
Case 4
sFormatID = "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}"
sExt = "TIFF"
End Select
If lQuality > 100 Then lQuality = 100
'Should check if the output file already exists and if so,
'prompt the user to overwrite it or not
Set oWIA = CreateObject("WIA.ImageFile")
Set oIP = CreateObject("WIA.ImageProcess")
oIP.Filters.Add oIP.FilterInfos("Convert").FilterID
oIP.Filters(1).Properties("FormatID") = sFormatID
oIP.Filters(1).Properties("Quality") = lQuality
oWIA.LoadFile sInitialImage
Set oWIA = oIP.Apply(oWIA)
'Overide the specified ext with the appropriate one for the choosen format
oWIA.SaveFile Left(sOutputImage, InStrRev(sOutputImage, ".")) & LCase(sExt)
WIA_ConvertImage = True
Error_Handler_Exit:
On Error Resume Next
If Not oIP Is Nothing Then Set oIP = Nothing
If Not oWIA Is Nothing Then Set oWIA = Nothing
Exit Function
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: WIA_ConvertImage" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Function
jueves, 14 de septiembre de 2017
VBA Access. Módulo de clase clsPrintScreen. Captura de pantalla en BMP. Screenshot, PrintScreen.
'***********************************************************************************************
' * Please leave any Trademarks or Credits in place.
' *
' * ACKNOWLEDGEMENT TO CONTRIBUTORS :
' * STEPHEN BULLEN, 15 November 1998 - Original PastPicture code
' * G HUDSON, 5 April 2010 - Pause Function
' * LUTZ GENTKOW, 23 July 2011 - Alt + PrtScrn
' * PAUL FRANCIS, 11 April 2013 - Putting all pieces together, bridging the 32 bit and 64 bit version.
' * CHRIS O, 12 April 2013 - Code suggestion to work on older versions of Access.
' *
' * DESCRIPTION: Creates a standard Picture object from whatever is on the clipboard.
' * This object is then saved to a location on the disc. Please note, this
' * can also be assigned to (for example) and Image control on a userform.
' *
' * The code requires a reference to the "OLE Automation" type library.
' *
' * The code in this module has been derived from a number of sources
' * discovered on MSDN, Access World Forum, VBForums.
' *
' * To use it, just copy this module into your project, then you can use:
' * SaveClip2Bit("C:\Pics\Sample.bmp")
' * to save this to a location on the Disc.
' * (Or)
' * Set ImageControl.Image = PastePicture
' * to paste a picture of whatever is on the clipboard into a standard image control.
' *
' * PROCEDURES:
' * PastePicture : The entry point for 'Setting' the Image
' * CreatePicture : Private function to convert a bitmap or metafile handle to an OLE reference
' * fnOLEError : Get the error text for an OLE error code
' * SaveClip2Bit : The entry point for 'Saving' the Image, calls for PastePicture
' * AltPrintScreen: Performs the automation of Alt + PrtScrn, for getting the Active Window.
' * Pause : Makes the program wait, to make sure proper screen capture takes place.
'**************************************************************************************************
Option Explicit
Option Compare Text
'Declare a UDT to store a GUID for the IPicture OLE Interface
Private Type Guid
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(0 To 7) As Byte
End Type
'Declare a UDT to store the bitmap information
Private Type uPicDesc
Size As Long
Type As Long
hPic As Long
hPal As Long
End Type
'Windows API Function Declarations
#If Win64 = 1 Then
'Does the clipboard contain a bitmap/metafile?
Private Declare PtrSafe Function IsClipboardFormatAvailable Lib "user32" (ByVal wFormat As Integer) As Long
'Open the clipboard to read
Private Declare PtrSafe Function OpenClipboard Lib "user32" (ByVal hWnd As Long) As Long
'Get a pointer to the bitmap/metafile
Private Declare PtrSafe Function GetClipboardData Lib "user32" (ByVal wFormat As Integer) As Long
'Close the clipboard
Private Declare PtrSafe Function CloseClipboard Lib "user32" () As Long
'Convert the handle into an OLE IPicture interface.
Private Declare PtrSafe Function OleCreatePictureIndirect Lib "oleaut32.dll" (PicDesc As uPicDesc, RefIID As Guid, ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long
'Create our own copy of the metafile, so it doesn't get wiped out by subsequent clipboard updates.
Private Declare PtrSafe Function CopyEnhMetaFile Lib "gdi32" Alias "CopyEnhMetaFileA" (ByVal hemfSrc As Long, ByVal lpszFile As String) As Long
'Create our own copy of the bitmap, so it doesn't get wiped out by subsequent clipboard updates.
Private Declare PtrSafe Function CopyImage Lib "user32" (ByVal Handle As Long, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long
'Uses the Keyboard simulation
Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
#Else
'Does the clipboard contain a bitmap/metafile?
Private Declare Function IsClipboardFormatAvailable Lib "user32" (ByVal wFormat As Integer) As Long
'Open the clipboard to read
Private Declare Function OpenClipboard Lib "user32" (ByVal hWnd As Long) As Long
'Get a pointer to the bitmap/metafile
Private Declare Function GetClipboardData Lib "user32" (ByVal wFormat As Integer) As Long
'Close the clipboard
Private Declare Function CloseClipboard Lib "user32" () As Long
'Convert the handle into an OLE IPicture interface.
Private Declare Function OleCreatePictureIndirect Lib "oleaut32.dll" (PicDesc As uPicDesc, RefIID As Guid, ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long
'Create our own copy of the metafile, so it doesn't get wiped out by subsequent clipboard updates.
Private Declare Function CopyEnhMetaFile Lib "gdi32" Alias "CopyEnhMetaFileA" (ByVal hemfSrc As Long, ByVal lpszFile As String) As Long
'Create our own copy of the bitmap, so it doesn't get wiped out by subsequent clipboard updates.
Private Declare Function CopyImage Lib "user32" (ByVal Handle As Long, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long
'Uses the Keyboard simulation
Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
#End If
'The API format types we're interested in
Const CF_BITMAP = 2
Const CF_PALETTE = 9
Const CF_ENHMETAFILE = 14
Const IMAGE_BITMAP = 0
Const LR_COPYRETURNORG = &H4
Private Const KEYEVENTF_KEYUP = &H2
Private Const VK_SNAPSHOT = &H2C
Private Const VK_MENU = &H12
' Subroutine : AltPrintScreen
' Purpose : Capture the Active window, and places on the Clipboard.
Sub AltPrintScreen()
keybd_event VK_MENU, 0, 0, 0
keybd_event VK_SNAPSHOT, 0, 0, 0
keybd_event VK_SNAPSHOT, 0, KEYEVENTF_KEYUP, 0
keybd_event VK_MENU, 0, KEYEVENTF_KEYUP, 0
End Sub
' Subroutine : PastePicture
' Purpose : Get a Picture object showing whatever's on the clipboard.
Function PastePicture() As IPicture
'Some pointers
Dim h As Long, hPtr As Long, hPal As Long, lPicType As Long, hCopy As Long
'Check if the clipboard contains the required format
If IsClipboardFormatAvailable(CF_BITMAP) Then
'Get access to the clipboard
h = OpenClipboard(0&)
If h > 0 Then
'Get a handle to the image data
hPtr = GetClipboardData(CF_BITMAP)
hCopy = CopyImage(hPtr, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG)
'Release the clipboard to other programs
h = CloseClipboard
'If we got a handle to the image, convert it into a Picture object and return it
If hPtr <> 0 Then Set PastePicture = CreatePicture(hCopy, 0, CF_BITMAP)
End If
End If
End Function
' Subroutine : CreatePicture
' Purpose : Converts a image (and palette) handle into a Picture object.
' NOTE : Requires a reference to the "OLE Automation" type library
Private Function CreatePicture(ByVal hPic As Long, ByVal hPal As Long, ByVal lPicType) As IPicture
' IPicture requires a reference to "OLE Automation"
Dim r As Long, uPicInfo As uPicDesc, IID_IDispatch As Guid, IPic As IPicture
'OLE Picture types
Const PICTYPE_BITMAP = 1
Const PICTYPE_ENHMETAFILE = 4
' Create the Interface GUID (for the IPicture interface)
With IID_IDispatch
.Data1 = &H7BF80980
.Data2 = &HBF32
.Data3 = &H101A
.Data4(0) = &H8B
.Data4(1) = &HBB
.Data4(2) = &H0
.Data4(3) = &HAA
.Data4(4) = &H0
.Data4(5) = &H30
.Data4(6) = &HC
.Data4(7) = &HAB
End With
' Fill uPicInfo with necessary parts.
With uPicInfo
.Size = Len(uPicInfo) ' Length of structure.
.Type = PICTYPE_BITMAP ' Type of Picture
.hPic = hPic ' Handle to image.
.hPal = hPal ' Handle to palette (if bitmap).
End With
' Create the Picture object.
r = OleCreatePictureIndirect(uPicInfo, IID_IDispatch, True, IPic)
' If an error occurred, show the description
If r <> 0 Then Debug.Print "Create Picture: " & fnOLEError(r)
' Return the new Picture object.
Set CreatePicture = IPic
End Function
' Subroutine : fnOLEError
' Purpose : Gets the message text for standard OLE errors
Private Function fnOLEError(lErrNum As Long) As String
'OLECreatePictureIndirect return values
Const E_ABORT = &H80004004
Const E_ACCESSDENIED = &H80070005
Const E_FAIL = &H80004005
Const E_HANDLE = &H80070006
Const E_INVALIDARG = &H80070057
Const E_NOINTERFACE = &H80004002
Const E_NOTIMPL = &H80004001
Const E_OUTOFMEMORY = &H8007000E
Const E_POINTER = &H80004003
Const E_UNEXPECTED = &H8000FFFF
Const S_OK = &H0
Select Case lErrNum
Case E_ABORT
fnOLEError = " Aborted"
Case E_ACCESSDENIED
fnOLEError = " Access Denied"
Case E_FAIL
fnOLEError = " General Failure"
Case E_HANDLE
fnOLEError = " Bad/Missing Handle"
Case E_INVALIDARG
fnOLEError = " Invalid Argument"
Case E_NOINTERFACE
fnOLEError = " No Interface"
Case E_NOTIMPL
fnOLEError = " Not Implemented"
Case E_OUTOFMEMORY
fnOLEError = " Out of Memory"
Case E_POINTER
fnOLEError = " Invalid Pointer"
Case E_UNEXPECTED
fnOLEError = " Unknown Error"
Case S_OK
fnOLEError = " Success!"
End Select
End Function
' Routine : SaveClip2Bit
' Purpose : Saves Picture object to desired location.
' Arguments : Path to save the file
Public Sub SaveClip2Bit(savePath As String)
On Error GoTo ErrHandler:
AltPrintScreen
Pause (3)
SavePicture PastePicture, savePath
errExit:
Exit Sub
ErrHandler:
Debug.Print "Save Picture: (" & Err.Number & ") - " & Err.Description
Resume errExit
End Sub
' Routine : Pause
' Purpose : Gives a short interval for proper image capture.
' Arguments : Seconds to wait.
Public Function Pause(NumberOfSeconds As Variant)
On Error GoTo Err_Pause
Dim PauseTime As Variant, start As Variant
PauseTime = NumberOfSeconds
start = Timer
Do While Timer < start + PauseTime
DoEvents
Loop
Exit_Pause:
Exit Function
Err_Pause:
MsgBox Err.Number & " - " & Err.Description, vbCritical, "Pause()"
Resume Exit_Pause
End Function
' * Please leave any Trademarks or Credits in place.
' *
' * ACKNOWLEDGEMENT TO CONTRIBUTORS :
' * STEPHEN BULLEN, 15 November 1998 - Original PastPicture code
' * G HUDSON, 5 April 2010 - Pause Function
' * LUTZ GENTKOW, 23 July 2011 - Alt + PrtScrn
' * PAUL FRANCIS, 11 April 2013 - Putting all pieces together, bridging the 32 bit and 64 bit version.
' * CHRIS O, 12 April 2013 - Code suggestion to work on older versions of Access.
' *
' * DESCRIPTION: Creates a standard Picture object from whatever is on the clipboard.
' * This object is then saved to a location on the disc. Please note, this
' * can also be assigned to (for example) and Image control on a userform.
' *
' * The code requires a reference to the "OLE Automation" type library.
' *
' * The code in this module has been derived from a number of sources
' * discovered on MSDN, Access World Forum, VBForums.
' *
' * To use it, just copy this module into your project, then you can use:
' * SaveClip2Bit("C:\Pics\Sample.bmp")
' * to save this to a location on the Disc.
' * (Or)
' * Set ImageControl.Image = PastePicture
' * to paste a picture of whatever is on the clipboard into a standard image control.
' *
' * PROCEDURES:
' * PastePicture : The entry point for 'Setting' the Image
' * CreatePicture : Private function to convert a bitmap or metafile handle to an OLE reference
' * fnOLEError : Get the error text for an OLE error code
' * SaveClip2Bit : The entry point for 'Saving' the Image, calls for PastePicture
' * AltPrintScreen: Performs the automation of Alt + PrtScrn, for getting the Active Window.
' * Pause : Makes the program wait, to make sure proper screen capture takes place.
'**************************************************************************************************
Option Explicit
Option Compare Text
'Declare a UDT to store a GUID for the IPicture OLE Interface
Private Type Guid
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(0 To 7) As Byte
End Type
'Declare a UDT to store the bitmap information
Private Type uPicDesc
Size As Long
Type As Long
hPic As Long
hPal As Long
End Type
'Windows API Function Declarations
#If Win64 = 1 Then
'Does the clipboard contain a bitmap/metafile?
Private Declare PtrSafe Function IsClipboardFormatAvailable Lib "user32" (ByVal wFormat As Integer) As Long
'Open the clipboard to read
Private Declare PtrSafe Function OpenClipboard Lib "user32" (ByVal hWnd As Long) As Long
'Get a pointer to the bitmap/metafile
Private Declare PtrSafe Function GetClipboardData Lib "user32" (ByVal wFormat As Integer) As Long
'Close the clipboard
Private Declare PtrSafe Function CloseClipboard Lib "user32" () As Long
'Convert the handle into an OLE IPicture interface.
Private Declare PtrSafe Function OleCreatePictureIndirect Lib "oleaut32.dll" (PicDesc As uPicDesc, RefIID As Guid, ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long
'Create our own copy of the metafile, so it doesn't get wiped out by subsequent clipboard updates.
Private Declare PtrSafe Function CopyEnhMetaFile Lib "gdi32" Alias "CopyEnhMetaFileA" (ByVal hemfSrc As Long, ByVal lpszFile As String) As Long
'Create our own copy of the bitmap, so it doesn't get wiped out by subsequent clipboard updates.
Private Declare PtrSafe Function CopyImage Lib "user32" (ByVal Handle As Long, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long
'Uses the Keyboard simulation
Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
#Else
'Does the clipboard contain a bitmap/metafile?
Private Declare Function IsClipboardFormatAvailable Lib "user32" (ByVal wFormat As Integer) As Long
'Open the clipboard to read
Private Declare Function OpenClipboard Lib "user32" (ByVal hWnd As Long) As Long
'Get a pointer to the bitmap/metafile
Private Declare Function GetClipboardData Lib "user32" (ByVal wFormat As Integer) As Long
'Close the clipboard
Private Declare Function CloseClipboard Lib "user32" () As Long
'Convert the handle into an OLE IPicture interface.
Private Declare Function OleCreatePictureIndirect Lib "oleaut32.dll" (PicDesc As uPicDesc, RefIID As Guid, ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long
'Create our own copy of the metafile, so it doesn't get wiped out by subsequent clipboard updates.
Private Declare Function CopyEnhMetaFile Lib "gdi32" Alias "CopyEnhMetaFileA" (ByVal hemfSrc As Long, ByVal lpszFile As String) As Long
'Create our own copy of the bitmap, so it doesn't get wiped out by subsequent clipboard updates.
Private Declare Function CopyImage Lib "user32" (ByVal Handle As Long, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long
'Uses the Keyboard simulation
Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
#End If
'The API format types we're interested in
Const CF_BITMAP = 2
Const CF_PALETTE = 9
Const CF_ENHMETAFILE = 14
Const IMAGE_BITMAP = 0
Const LR_COPYRETURNORG = &H4
Private Const KEYEVENTF_KEYUP = &H2
Private Const VK_SNAPSHOT = &H2C
Private Const VK_MENU = &H12
' Subroutine : AltPrintScreen
' Purpose : Capture the Active window, and places on the Clipboard.
Sub AltPrintScreen()
keybd_event VK_MENU, 0, 0, 0
keybd_event VK_SNAPSHOT, 0, 0, 0
keybd_event VK_SNAPSHOT, 0, KEYEVENTF_KEYUP, 0
keybd_event VK_MENU, 0, KEYEVENTF_KEYUP, 0
End Sub
' Subroutine : PastePicture
' Purpose : Get a Picture object showing whatever's on the clipboard.
Function PastePicture() As IPicture
'Some pointers
Dim h As Long, hPtr As Long, hPal As Long, lPicType As Long, hCopy As Long
'Check if the clipboard contains the required format
If IsClipboardFormatAvailable(CF_BITMAP) Then
'Get access to the clipboard
h = OpenClipboard(0&)
If h > 0 Then
'Get a handle to the image data
hPtr = GetClipboardData(CF_BITMAP)
hCopy = CopyImage(hPtr, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG)
'Release the clipboard to other programs
h = CloseClipboard
'If we got a handle to the image, convert it into a Picture object and return it
If hPtr <> 0 Then Set PastePicture = CreatePicture(hCopy, 0, CF_BITMAP)
End If
End If
End Function
' Subroutine : CreatePicture
' Purpose : Converts a image (and palette) handle into a Picture object.
' NOTE : Requires a reference to the "OLE Automation" type library
Private Function CreatePicture(ByVal hPic As Long, ByVal hPal As Long, ByVal lPicType) As IPicture
' IPicture requires a reference to "OLE Automation"
Dim r As Long, uPicInfo As uPicDesc, IID_IDispatch As Guid, IPic As IPicture
'OLE Picture types
Const PICTYPE_BITMAP = 1
Const PICTYPE_ENHMETAFILE = 4
' Create the Interface GUID (for the IPicture interface)
With IID_IDispatch
.Data1 = &H7BF80980
.Data2 = &HBF32
.Data3 = &H101A
.Data4(0) = &H8B
.Data4(1) = &HBB
.Data4(2) = &H0
.Data4(3) = &HAA
.Data4(4) = &H0
.Data4(5) = &H30
.Data4(6) = &HC
.Data4(7) = &HAB
End With
' Fill uPicInfo with necessary parts.
With uPicInfo
.Size = Len(uPicInfo) ' Length of structure.
.Type = PICTYPE_BITMAP ' Type of Picture
.hPic = hPic ' Handle to image.
.hPal = hPal ' Handle to palette (if bitmap).
End With
' Create the Picture object.
r = OleCreatePictureIndirect(uPicInfo, IID_IDispatch, True, IPic)
' If an error occurred, show the description
If r <> 0 Then Debug.Print "Create Picture: " & fnOLEError(r)
' Return the new Picture object.
Set CreatePicture = IPic
End Function
' Subroutine : fnOLEError
' Purpose : Gets the message text for standard OLE errors
Private Function fnOLEError(lErrNum As Long) As String
'OLECreatePictureIndirect return values
Const E_ABORT = &H80004004
Const E_ACCESSDENIED = &H80070005
Const E_FAIL = &H80004005
Const E_HANDLE = &H80070006
Const E_INVALIDARG = &H80070057
Const E_NOINTERFACE = &H80004002
Const E_NOTIMPL = &H80004001
Const E_OUTOFMEMORY = &H8007000E
Const E_POINTER = &H80004003
Const E_UNEXPECTED = &H8000FFFF
Const S_OK = &H0
Select Case lErrNum
Case E_ABORT
fnOLEError = " Aborted"
Case E_ACCESSDENIED
fnOLEError = " Access Denied"
Case E_FAIL
fnOLEError = " General Failure"
Case E_HANDLE
fnOLEError = " Bad/Missing Handle"
Case E_INVALIDARG
fnOLEError = " Invalid Argument"
Case E_NOINTERFACE
fnOLEError = " No Interface"
Case E_NOTIMPL
fnOLEError = " Not Implemented"
Case E_OUTOFMEMORY
fnOLEError = " Out of Memory"
Case E_POINTER
fnOLEError = " Invalid Pointer"
Case E_UNEXPECTED
fnOLEError = " Unknown Error"
Case S_OK
fnOLEError = " Success!"
End Select
End Function
' Routine : SaveClip2Bit
' Purpose : Saves Picture object to desired location.
' Arguments : Path to save the file
Public Sub SaveClip2Bit(savePath As String)
On Error GoTo ErrHandler:
AltPrintScreen
Pause (3)
SavePicture PastePicture, savePath
errExit:
Exit Sub
ErrHandler:
Debug.Print "Save Picture: (" & Err.Number & ") - " & Err.Description
Resume errExit
End Sub
' Routine : Pause
' Purpose : Gives a short interval for proper image capture.
' Arguments : Seconds to wait.
Public Function Pause(NumberOfSeconds As Variant)
On Error GoTo Err_Pause
Dim PauseTime As Variant, start As Variant
PauseTime = NumberOfSeconds
start = Timer
Do While Timer < start + PauseTime
DoEvents
Loop
Exit_Pause:
Exit Function
Err_Pause:
MsgBox Err.Number & " - " & Err.Description, vbCritical, "Pause()"
Resume Exit_Pause
End Function
Suscribirse a:
Entradas (Atom)
VBA Access. Redondeo de números decimales con el método medio redondeo. Alternativa a la función Round (bankers round)
Private Function Redondeo(ByVal Numero As Variant, ByVal Decimales As Integer) As Double 'Aplica método medio redondeo (half round ...
-
Option Compare Database Option Explicit '***************************** ' 'Ejemplo de uso ' 'selecciona 1 ficher...
-
Option Compare Database Option Explicit 'Zip / UnZip file or folder 'http://www.codekabinett.com/rdumps.php?Lang=2&targetDoc...