Public Function MakeDirFullPath(ByVal sPath As String) As Boolean
On Error GoTo error
'crear todo el path de un directorio
If Right(sPath, 1) = "\" Then
sPath = Left(sPath, Len(sPath) - 1)
End If
Dim SplitPath() As String
SplitPath = Split(sPath, "\")
Dim Value As Integer
Dim Merge As String
For Value = 0 To UBound(SplitPath)
If Value <> 0 Then
Merge = Merge & "\"
End If
Merge = Merge & SplitPath(Value)
If Dir(Merge, vbDirectory) = "" Then
MkDir Merge
End If
Next
SetAttr sPath, vbNormal
MakeDirFullPath = True
Exit Function
error:
MakeDirFullPath = False
Debug.Print Err.Description
End Function
jueves, 14 de septiembre de 2017
VBA Access. Obtener nombre de usuario y máquina. GetWindowsUser, GetComputerName.
Public Function GetWindowsUser() As String
On Error GoTo error
Dim sUsername As String
Dim objNetwork As Object
sUsername = Environ$("username")
If sUsername = "" Then
Set objNetwork = CreateObject("WScript.Network")
sUsername = objNetwork.username
Set objNetwork = Nothing
End If
GetWindowsUser = sUsername
Exit Function
error:
Debug.Print Err.Description
GetWindowsUser = ""
End Function
Public Function GetComputerName() As String
On Error GoTo error
Dim sComputerName As String
Dim objNetwork As Object
sComputerName = Environ$("ComputerName")
If sComputerName = "" Then
Set objNetwork = CreateObject("WScript.Network")
sComputerName = objNetwork.ComputerName
Set objNetwork = Nothing
End If
GetComputerName = sComputerName
Exit Function
error:
Debug.Print Err.Description
GetComputerName = ""
End Function
On Error GoTo error
Dim sUsername As String
Dim objNetwork As Object
sUsername = Environ$("username")
If sUsername = "" Then
Set objNetwork = CreateObject("WScript.Network")
sUsername = objNetwork.username
Set objNetwork = Nothing
End If
GetWindowsUser = sUsername
Exit Function
error:
Debug.Print Err.Description
GetWindowsUser = ""
End Function
Public Function GetComputerName() As String
On Error GoTo error
Dim sComputerName As String
Dim objNetwork As Object
sComputerName = Environ$("ComputerName")
If sComputerName = "" Then
Set objNetwork = CreateObject("WScript.Network")
sComputerName = objNetwork.ComputerName
Set objNetwork = Nothing
End If
GetComputerName = sComputerName
Exit Function
error:
Debug.Print Err.Description
GetComputerName = ""
End Function
VBA Access. Módulo de clase clsResizeForm. Redimensionar formulario. Resize form.
Option Compare Database
Option Explicit
'CREDITS:
'This modResizeForm module was created by Jamie Czernik 31st March 2000 (jsczernik@hotmail.com)
'The module was updated by Dr. Martin Dumskyj 30th January 2001 (mdumskyj@sghms.ac.UK)
'Module Declarations (here, set the original resolution width was made the form)
'* changes to use as a class and now can pass the resolutionX as an argument
'* To use, put on event onload form passing form and DesignResolutionX as argument : create object and then ... objResizeForm.ResizeForm Me, 1024
'* Added control for 64 bits Windows API declaration
'* Tip: DesignResolutionX nomally must be the resolutionX that was designed the form to adjust to the current resolution
Const WM_HORZRES = 8
Const WM_VERTRES = 10
Dim m_DesignResolutionX As Integer
Dim Width As Integer
Dim Factor As Single 'Used as multiplier for current size properties'
'Windows API Function Declarations
#If Win64 = 1 Then
Private Declare PtrSafe Function WM_apiGetDeviceCaps Lib "gdi32" Alias "GetDeviceCaps" (ByVal hDC As Long, ByVal nIndex As Long) As Long
Private Declare PtrSafe Function WM_apiGetDesktopWindow Lib "user32" Alias "GetDesktopWindow" () As Long
Private Declare PtrSafe Function WM_apiGetDC Lib "user32" Alias "GetDC" (ByVal hWnd As Long) As Long
Private Declare PtrSafe Function WM_apiReleaseDC Lib "user32" Alias "ReleaseDC" (ByVal hWnd As Long, ByVal hDC As Long) As Long
Private Declare PtrSafe Function WM_apiGetSystemMetrics Lib "user32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
#Else
Private Declare Function WM_apiGetDeviceCaps Lib "gdi32" Alias "GetDeviceCaps" (ByVal hDC As Long, ByVal nIndex As Long) As Long
Private Declare Function WM_apiGetDesktopWindow Lib "user32" Alias "GetDesktopWindow" () As Long
Private Declare Function WM_apiGetDC Lib "user32" Alias "GetDC" (ByVal hWnd As Long) As Long
Private Declare Function WM_apiReleaseDC Lib "user32" Alias "ReleaseDC" (ByVal hWnd As Long, ByVal hDC As Long) As Long
Private Declare Function WM_apiGetSystemMetrics Lib "user32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
#End If
Function GetScreenResolution() As String
'returns the height and width
Dim DisplayHeight As Integer
Dim DisplayWidth As Integer
Dim hDesktopWnd As Long
Dim hDCcaps As Long
Dim iRtn As Integer
'API call get current resolution
hDesktopWnd = WM_apiGetDesktopWindow() 'get handle to desktop
hDCcaps = WM_apiGetDC(hDesktopWnd) 'get display context for desktop
DisplayHeight = WM_apiGetDeviceCaps(hDCcaps, WM_VERTRES)
DisplayWidth = WM_apiGetDeviceCaps(hDCcaps, WM_HORZRES)
iRtn = WM_apiReleaseDC(hDesktopWnd, hDCcaps) 'release display context
GetScreenResolution = DisplayWidth & "x" & DisplayHeight
Width = DisplayWidth
End Function
Public Sub ReSizeForm(frm As Form, Optional ByVal DesignResolutionX As Integer = 1024)
On Error Resume Next
Dim ctl As Control
m_DesignResolutionX = DesignResolutionX
SetFactor 'Call to procedure SetFactor
With frm
.Width = frm.Width * Factor
End With
For Each ctl In frm.Controls
With ctl
.Height = ctl.Height * Factor
.Left = ctl.Left * Factor
.Top = ctl.Top * Factor
.Width = ctl.Width * Factor
.FontSize = .FontSize * Factor
End With
Next ctl
End Sub
Sub SetFactor()
GetScreenResolution 'Call to function GetScreenResolution
Factor = Width / m_DesignResolutionX
End Sub
Option Explicit
'CREDITS:
'This modResizeForm module was created by Jamie Czernik 31st March 2000 (jsczernik@hotmail.com)
'The module was updated by Dr. Martin Dumskyj 30th January 2001 (mdumskyj@sghms.ac.UK)
'Module Declarations (here, set the original resolution width was made the form)
'* changes to use as a class and now can pass the resolutionX as an argument
'* To use, put on event onload form passing form and DesignResolutionX as argument : create object and then ... objResizeForm.ResizeForm Me, 1024
'* Added control for 64 bits Windows API declaration
'* Tip: DesignResolutionX nomally must be the resolutionX that was designed the form to adjust to the current resolution
Const WM_HORZRES = 8
Const WM_VERTRES = 10
Dim m_DesignResolutionX As Integer
Dim Width As Integer
Dim Factor As Single 'Used as multiplier for current size properties'
'Windows API Function Declarations
#If Win64 = 1 Then
Private Declare PtrSafe Function WM_apiGetDeviceCaps Lib "gdi32" Alias "GetDeviceCaps" (ByVal hDC As Long, ByVal nIndex As Long) As Long
Private Declare PtrSafe Function WM_apiGetDesktopWindow Lib "user32" Alias "GetDesktopWindow" () As Long
Private Declare PtrSafe Function WM_apiGetDC Lib "user32" Alias "GetDC" (ByVal hWnd As Long) As Long
Private Declare PtrSafe Function WM_apiReleaseDC Lib "user32" Alias "ReleaseDC" (ByVal hWnd As Long, ByVal hDC As Long) As Long
Private Declare PtrSafe Function WM_apiGetSystemMetrics Lib "user32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
#Else
Private Declare Function WM_apiGetDeviceCaps Lib "gdi32" Alias "GetDeviceCaps" (ByVal hDC As Long, ByVal nIndex As Long) As Long
Private Declare Function WM_apiGetDesktopWindow Lib "user32" Alias "GetDesktopWindow" () As Long
Private Declare Function WM_apiGetDC Lib "user32" Alias "GetDC" (ByVal hWnd As Long) As Long
Private Declare Function WM_apiReleaseDC Lib "user32" Alias "ReleaseDC" (ByVal hWnd As Long, ByVal hDC As Long) As Long
Private Declare Function WM_apiGetSystemMetrics Lib "user32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
#End If
Function GetScreenResolution() As String
'returns the height and width
Dim DisplayHeight As Integer
Dim DisplayWidth As Integer
Dim hDesktopWnd As Long
Dim hDCcaps As Long
Dim iRtn As Integer
'API call get current resolution
hDesktopWnd = WM_apiGetDesktopWindow() 'get handle to desktop
hDCcaps = WM_apiGetDC(hDesktopWnd) 'get display context for desktop
DisplayHeight = WM_apiGetDeviceCaps(hDCcaps, WM_VERTRES)
DisplayWidth = WM_apiGetDeviceCaps(hDCcaps, WM_HORZRES)
iRtn = WM_apiReleaseDC(hDesktopWnd, hDCcaps) 'release display context
GetScreenResolution = DisplayWidth & "x" & DisplayHeight
Width = DisplayWidth
End Function
Public Sub ReSizeForm(frm As Form, Optional ByVal DesignResolutionX As Integer = 1024)
On Error Resume Next
Dim ctl As Control
m_DesignResolutionX = DesignResolutionX
SetFactor 'Call to procedure SetFactor
With frm
.Width = frm.Width * Factor
End With
For Each ctl In frm.Controls
With ctl
.Height = ctl.Height * Factor
.Left = ctl.Left * Factor
.Top = ctl.Top * Factor
.Width = ctl.Width * Factor
.FontSize = .FontSize * Factor
End With
Next ctl
End Sub
Sub SetFactor()
GetScreenResolution 'Call to function GetScreenResolution
Factor = Width / m_DesignResolutionX
End Sub
VBA Access. Módulo de clase clsCrypt. Encriptar y Desencriptar texto con RC4. Crypt, Decrypt.
Option Compare Database
Option Explicit
'https://stackoverflow.com/questions/7025644/vb6-encrypt-text-using-password
Public Function Crypt(ByVal sValue As String, sKey As String) As String
On Error GoTo error
Crypt = ToHexDump(CryptRC4(sValue, sKey))
Exit Function
error:
Crypt = sValue
Debug.Print Err.Description
End Function
Public Function DeCrypt(ByVal sValue As String, sKey As String) As String
On Error GoTo error
DeCrypt = CryptRC4(FromHexDump(sValue), sKey)
Exit Function
error:
DeCrypt = sValue
Debug.Print Err.Description
End Function
Private Function CryptRC4(sText As String, sKey As String) As String
Dim baS(0 To 255) As Byte
Dim baK(0 To 255) As Byte
Dim bytSwap As Byte
Dim lI As Long
Dim lJ As Long
Dim lIdx As Long
For lIdx = 0 To 255
baS(lIdx) = lIdx
baK(lIdx) = Asc(Mid$(sKey, 1 + (lIdx Mod Len(sKey)), 1))
Next
For lI = 0 To 255
lJ = (lJ + baS(lI) + baK(lI)) Mod 256
bytSwap = baS(lI)
baS(lI) = baS(lJ)
baS(lJ) = bytSwap
Next
lI = 0
lJ = 0
For lIdx = 1 To Len(sText)
lI = (lI + 1) Mod 256
lJ = (lJ + baS(lI)) Mod 256
bytSwap = baS(lI)
baS(lI) = baS(lJ)
baS(lJ) = bytSwap
CryptRC4 = CryptRC4 & Chr$((pvCryptXor(baS((CLng(baS(lI)) + baS(lJ)) Mod 256), Asc(Mid$(sText, lIdx, 1)))))
Next
End Function
Private Function pvCryptXor(ByVal lI As Long, ByVal lJ As Long) As Long
If lI = lJ Then
pvCryptXor = lJ
Else
pvCryptXor = lI Xor lJ
End If
End Function
Private Function ToHexDump(sText As String) As String
Dim lIdx As Long
For lIdx = 1 To Len(sText)
ToHexDump = ToHexDump & Right$("0" & Hex(Asc(Mid(sText, lIdx, 1))), 2)
Next
End Function
Private Function FromHexDump(sText As String) As String
Dim lIdx As Long
For lIdx = 1 To Len(sText) Step 2
FromHexDump = FromHexDump & Chr$(CLng("&H" & Mid(sText, lIdx, 2)))
Next
End Function
Option Explicit
'https://stackoverflow.com/questions/7025644/vb6-encrypt-text-using-password
Public Function Crypt(ByVal sValue As String, sKey As String) As String
On Error GoTo error
Crypt = ToHexDump(CryptRC4(sValue, sKey))
Exit Function
error:
Crypt = sValue
Debug.Print Err.Description
End Function
Public Function DeCrypt(ByVal sValue As String, sKey As String) As String
On Error GoTo error
DeCrypt = CryptRC4(FromHexDump(sValue), sKey)
Exit Function
error:
DeCrypt = sValue
Debug.Print Err.Description
End Function
Private Function CryptRC4(sText As String, sKey As String) As String
Dim baS(0 To 255) As Byte
Dim baK(0 To 255) As Byte
Dim bytSwap As Byte
Dim lI As Long
Dim lJ As Long
Dim lIdx As Long
For lIdx = 0 To 255
baS(lIdx) = lIdx
baK(lIdx) = Asc(Mid$(sKey, 1 + (lIdx Mod Len(sKey)), 1))
Next
For lI = 0 To 255
lJ = (lJ + baS(lI) + baK(lI)) Mod 256
bytSwap = baS(lI)
baS(lI) = baS(lJ)
baS(lJ) = bytSwap
Next
lI = 0
lJ = 0
For lIdx = 1 To Len(sText)
lI = (lI + 1) Mod 256
lJ = (lJ + baS(lI)) Mod 256
bytSwap = baS(lI)
baS(lI) = baS(lJ)
baS(lJ) = bytSwap
CryptRC4 = CryptRC4 & Chr$((pvCryptXor(baS((CLng(baS(lI)) + baS(lJ)) Mod 256), Asc(Mid$(sText, lIdx, 1)))))
Next
End Function
Private Function pvCryptXor(ByVal lI As Long, ByVal lJ As Long) As Long
If lI = lJ Then
pvCryptXor = lJ
Else
pvCryptXor = lI Xor lJ
End If
End Function
Private Function ToHexDump(sText As String) As String
Dim lIdx As Long
For lIdx = 1 To Len(sText)
ToHexDump = ToHexDump & Right$("0" & Hex(Asc(Mid(sText, lIdx, 1))), 2)
Next
End Function
Private Function FromHexDump(sText As String) As String
Dim lIdx As Long
For lIdx = 1 To Len(sText) Step 2
FromHexDump = FromHexDump & Chr$(CLng("&H" & Mid(sText, lIdx, 2)))
Next
End Function
VBA Access. Módulo de clase clsZip. Comprimir y descomprimir ficheros o carpetas: Zip, Unzip.
Option Compare Database
Option Explicit
'Zip / UnZip file or folder
'http://www.codekabinett.com/rdumps.php?Lang=2&targetDoc=create-zip-archive-vba-shell32
Public Function Zip(ByVal zipArchivePath As String, ByVal addPath As String) As String
On Error GoTo error
Dim sh As Object
Dim fSource As Object
Dim fTarget As Object
Dim iSource As Object
Dim sourceItem As Object
Dim i As Long
Set sh = CreateObject("Shell.Application")
Set fTarget = sh.NameSpace((zipArchivePath))
If fTarget Is Nothing Then
createZipFile zipArchivePath
Set fTarget = sh.NameSpace((zipArchivePath))
End If
Dim containingFolder As String
Dim itemToZip As String
containingFolder = Left(addPath, InStrRev(addPath, "\"))
itemToZip = Mid(addPath, InStrRev(addPath, "\") + 1)
Set fSource = sh.NameSpace((containingFolder))
For i = 0 To fSource.Items.Count - 1
If fSource.Items.Item((i)).Name = itemToZip Then
Set sourceItem = fSource.Items.Item((i))
Exit For
End If
Next i
fTarget.CopyHere sourceItem
Zip = ""
Exit Function
error:
Zip = Err.Number & ": " & Err.Description
Debug.Print Err.Number & ": " & Err.Description, , "Zip"
End Function
Public Function UnZip(ByVal zipArchivePath As String, ByVal extractToFolder As String) As String
On Error GoTo error
Dim sh As Object
Dim fSource As Object
Dim fTarget As Object
Set sh = CreateObject("Shell.Application")
Set fSource = sh.NameSpace((zipArchivePath))
Set fTarget = sh.NameSpace((extractToFolder))
fTarget.CopyHere fSource.Items
UnZip = ""
Exit Function
error:
UnZip = Err.Number & ": " & Err.Description
Debug.Print Err.Number & ": " & Err.Description, , "UnZip"
End Function
Public Sub DeleteFileWithInvokeVerb(ByVal zipArchivePath As String, ByVal deleteFileName As String)
On Error GoTo error
Dim sh As Object
Dim fTarget As Object
Dim iSource As Object
Dim targetItem As Object
Dim i As Long
Set sh = CreateObject("Shell.Application")
Set fTarget = sh.NameSpace((zipArchivePath))
For i = 0 To fTarget.Items.Count - 1
If fTarget.Items.Item((i)).Name = deleteFileName Then
Set targetItem = fTarget.Items.Item((i))
Exit For
End If
Next i
If Not targetItem Is Nothing Then
targetItem.InvokeVerb "Delete"
End If
Exit Sub
error:
MsgBox Err.Number & ": " & Err.Description
End Sub
Private Function createZipFile(ByVal fileName As String) As Boolean
On Error GoTo error
Dim fileNo As Integer
Dim ZIPFileEOCD(22) As Byte
'Signature of the EOCD: &H06054b50
ZIPFileEOCD(0) = Val("&H50")
ZIPFileEOCD(1) = Val("&H4b")
ZIPFileEOCD(2) = Val("&H05")
ZIPFileEOCD(3) = Val("&H06")
fileNo = FreeFile
Open fileName For Binary Access Write As #fileNo
Put #fileNo, , ZIPFileEOCD
Close #fileNo
createZipFile = True
Exit Function
error:
createZipFile = False
Debug.Print Err.Number & ": " & Err.Description
End Function
Option Explicit
'Zip / UnZip file or folder
'http://www.codekabinett.com/rdumps.php?Lang=2&targetDoc=create-zip-archive-vba-shell32
Public Function Zip(ByVal zipArchivePath As String, ByVal addPath As String) As String
On Error GoTo error
Dim sh As Object
Dim fSource As Object
Dim fTarget As Object
Dim iSource As Object
Dim sourceItem As Object
Dim i As Long
Set sh = CreateObject("Shell.Application")
Set fTarget = sh.NameSpace((zipArchivePath))
If fTarget Is Nothing Then
createZipFile zipArchivePath
Set fTarget = sh.NameSpace((zipArchivePath))
End If
Dim containingFolder As String
Dim itemToZip As String
containingFolder = Left(addPath, InStrRev(addPath, "\"))
itemToZip = Mid(addPath, InStrRev(addPath, "\") + 1)
Set fSource = sh.NameSpace((containingFolder))
For i = 0 To fSource.Items.Count - 1
If fSource.Items.Item((i)).Name = itemToZip Then
Set sourceItem = fSource.Items.Item((i))
Exit For
End If
Next i
fTarget.CopyHere sourceItem
Zip = ""
Exit Function
error:
Zip = Err.Number & ": " & Err.Description
Debug.Print Err.Number & ": " & Err.Description, , "Zip"
End Function
Public Function UnZip(ByVal zipArchivePath As String, ByVal extractToFolder As String) As String
On Error GoTo error
Dim sh As Object
Dim fSource As Object
Dim fTarget As Object
Set sh = CreateObject("Shell.Application")
Set fSource = sh.NameSpace((zipArchivePath))
Set fTarget = sh.NameSpace((extractToFolder))
fTarget.CopyHere fSource.Items
UnZip = ""
Exit Function
error:
UnZip = Err.Number & ": " & Err.Description
Debug.Print Err.Number & ": " & Err.Description, , "UnZip"
End Function
Public Sub DeleteFileWithInvokeVerb(ByVal zipArchivePath As String, ByVal deleteFileName As String)
On Error GoTo error
Dim sh As Object
Dim fTarget As Object
Dim iSource As Object
Dim targetItem As Object
Dim i As Long
Set sh = CreateObject("Shell.Application")
Set fTarget = sh.NameSpace((zipArchivePath))
For i = 0 To fTarget.Items.Count - 1
If fTarget.Items.Item((i)).Name = deleteFileName Then
Set targetItem = fTarget.Items.Item((i))
Exit For
End If
Next i
If Not targetItem Is Nothing Then
targetItem.InvokeVerb "Delete"
End If
Exit Sub
error:
MsgBox Err.Number & ": " & Err.Description
End Sub
Private Function createZipFile(ByVal fileName As String) As Boolean
On Error GoTo error
Dim fileNo As Integer
Dim ZIPFileEOCD(22) As Byte
'Signature of the EOCD: &H06054b50
ZIPFileEOCD(0) = Val("&H50")
ZIPFileEOCD(1) = Val("&H4b")
ZIPFileEOCD(2) = Val("&H05")
ZIPFileEOCD(3) = Val("&H06")
fileNo = FreeFile
Open fileName For Binary Access Write As #fileNo
Put #fileNo, , ZIPFileEOCD
Close #fileNo
createZipFile = True
Exit Function
error:
createZipFile = False
Debug.Print Err.Number & ": " & Err.Description
End Function
VBA Access. Módulo de clase clsMail para enviar correo usando CDO.
Option Compare Database
Option Explicit
Const CONNECTION_TIMEOUT = 60
Private m_ServidorSMTP As String
Private m_PuertoSMTP As Integer
Private m_MetodoEnvio As Integer
Private m_UsarAutenticacion As Integer
Private m_UsarSSL As Boolean
Private m_Usuario As String
Private m_Contrasena As String
Private m_From As String
Private m_ToAddress As String
Private m_CC As String
Private m_BCC As String
Public Enum formatBody
Html = 1
Text = 2
End Enum
Public Enum cdoSendMethod
cdoSendUsingPickup = 1
cdoSendUsingPort = 2
End Enum
Public Enum cdoUseAuthentication
cdoAnonymous = 1
cdoBasic = 2
cdoNTLM = 3
End Enum
Private Sub Class_Initialize()
'initialize values
m_ServidorSMTP = ""
m_PuertoSMTP = 25
'1=cdoSendUsingPickup / 2=cdoSendUsingPort
m_MetodoEnvio = cdoSendUsingPort
'0=cdoAnonymous / 1=cdoBasic / 2=cdoNTLM
m_UsarAutenticacion = cdoBasic
m_UsarSSL = False
m_Usuario = ""
m_Contrasena = ""
m_From = ""
m_ToAddress = ""
m_CC = ""
m_BCC = ""
End Sub
Private Sub Class_Terminate()
'deallocate if needed
End Sub
Public Property Get ServidorSMTP() As String
ServidorSMTP = m_ServidorSMTP
End Property
Public Property Let ServidorSMTP(ByVal Value As String)
m_ServidorSMTP = Value
End Property
Public Property Get PuertoSMTP() As Integer
PuertoSMTP = m_PuertoSMTP
End Property
Public Property Let PuertoSMTP(ByVal Value As Integer)
m_PuertoSMTP = Value
End Property
Public Property Get MetodoEnvio() As cdoSendMethod
MetodoEnvio = m_MetodoEnvio
End Property
Public Property Let MetodoEnvio(ByVal Value As cdoSendMethod)
m_MetodoEnvio = Value
End Property
Public Property Get UsarAutenticacion() As cdoUseAuthentication
UsarAutenticacion = m_UsarAutenticacion
End Property
Public Property Let UsarAutenticacion(ByVal Value As cdoUseAuthentication)
m_UsarAutenticacion = Value
End Property
Public Property Get UsarSSL() As Boolean
UsarSSL = m_UsarSSL
End Property
Public Property Let UsarSSL(ByVal Value As Boolean)
m_UsarSSL = Value
End Property
Public Property Get Usuario() As String
Usuario = m_Usuario
End Property
Public Property Let Usuario(ByVal Value As String)
m_Usuario = Value
End Property
Public Property Get Contrasena() As String
Contrasena = m_Contrasena
End Property
Public Property Let Contrasena(ByVal Value As String)
m_Contrasena = Value
End Property
Public Property Get From() As String
From = m_From
End Property
Public Property Let From(ByVal Value As String)
m_From = Value
End Property
Public Property Get ToAddress() As String
ToAddress = m_ToAddress
End Property
Public Property Let ToAddress(ByVal Value As String)
m_ToAddress = Value
End Property
Public Property Get CC() As String
CC = m_CC
End Property
Public Property Let CC(ByVal Value As String)
m_CC = Value
End Property
Public Property Get BCC() As String
BCC = m_BCC
End Property
Public Property Let BCC(ByVal Value As String)
m_BCC = Value
End Property
Public Function SendMail(ByVal sSubject As String, ByVal sBody As String, Optional fBody As formatBody = Text, Optional ByRef sAttachmentsArray As Variant) As String
On Error GoTo error
Dim iMsg As Object
Dim iConf As Object
Dim Flds As Variant
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
'cdo valores por defecto
iConf.Load -1
Set Flds = iConf.Fields
With Flds
.item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = m_ServidorSMTP
.item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = m_PuertoSMTP
'1=cdoSendUsingPickup / 2=cdoSendUsingPort
.item("http://schemas.microsoft.com/cdo/configuration/sendusing") = m_MetodoEnvio
'0=cdoAnonymous / 1=cdoBasic /2=cdoNTLM
.item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = m_UsarAutenticacion
'True/False
.item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = m_UsarSSL
.item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = CONNECTION_TIMEOUT
.item("http://schemas.microsoft.com/cdo/configuration/sendusername") = m_Usuario
.item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = m_Contrasena
.Update
End With
With iMsg
Set .Configuration = iConf
.To = m_ToAddress
.CC = m_CC
.BCC = m_BCC
.From = m_From
.Subject = sSubject
If fBody = Text Then
.TextBody = sBody
Else
.HtmlBody = sBody
End If
If Not IsMissing(sAttachmentsArray) Then
If IsArray(sAttachmentsArray) Then
Dim i As Integer
For i = LBound(sAttachmentsArray) To UBound(sAttachmentsArray)
.AddAttachment sAttachmentsArray(i)
Next i
End If
End If
.Send
End With
Set iMsg = Nothing
Set iConf = Nothing
Set Flds = Nothing
If Err.Number = 0 Then
Debug.Print "Message sent successfully!"
SendMail = ""
End If
Exit Function
Resume
error:
Debug.Print Err.Number & " " & Err.Description
SendMail = Err.Number & " " & Err.Description
End Function
Option Explicit
Const CONNECTION_TIMEOUT = 60
Private m_ServidorSMTP As String
Private m_PuertoSMTP As Integer
Private m_MetodoEnvio As Integer
Private m_UsarAutenticacion As Integer
Private m_UsarSSL As Boolean
Private m_Usuario As String
Private m_Contrasena As String
Private m_From As String
Private m_ToAddress As String
Private m_CC As String
Private m_BCC As String
Public Enum formatBody
Html = 1
Text = 2
End Enum
Public Enum cdoSendMethod
cdoSendUsingPickup = 1
cdoSendUsingPort = 2
End Enum
Public Enum cdoUseAuthentication
cdoAnonymous = 1
cdoBasic = 2
cdoNTLM = 3
End Enum
Private Sub Class_Initialize()
'initialize values
m_ServidorSMTP = ""
m_PuertoSMTP = 25
'1=cdoSendUsingPickup / 2=cdoSendUsingPort
m_MetodoEnvio = cdoSendUsingPort
'0=cdoAnonymous / 1=cdoBasic / 2=cdoNTLM
m_UsarAutenticacion = cdoBasic
m_UsarSSL = False
m_Usuario = ""
m_Contrasena = ""
m_From = ""
m_ToAddress = ""
m_CC = ""
m_BCC = ""
End Sub
Private Sub Class_Terminate()
'deallocate if needed
End Sub
Public Property Get ServidorSMTP() As String
ServidorSMTP = m_ServidorSMTP
End Property
Public Property Let ServidorSMTP(ByVal Value As String)
m_ServidorSMTP = Value
End Property
Public Property Get PuertoSMTP() As Integer
PuertoSMTP = m_PuertoSMTP
End Property
Public Property Let PuertoSMTP(ByVal Value As Integer)
m_PuertoSMTP = Value
End Property
Public Property Get MetodoEnvio() As cdoSendMethod
MetodoEnvio = m_MetodoEnvio
End Property
Public Property Let MetodoEnvio(ByVal Value As cdoSendMethod)
m_MetodoEnvio = Value
End Property
Public Property Get UsarAutenticacion() As cdoUseAuthentication
UsarAutenticacion = m_UsarAutenticacion
End Property
Public Property Let UsarAutenticacion(ByVal Value As cdoUseAuthentication)
m_UsarAutenticacion = Value
End Property
Public Property Get UsarSSL() As Boolean
UsarSSL = m_UsarSSL
End Property
Public Property Let UsarSSL(ByVal Value As Boolean)
m_UsarSSL = Value
End Property
Public Property Get Usuario() As String
Usuario = m_Usuario
End Property
Public Property Let Usuario(ByVal Value As String)
m_Usuario = Value
End Property
Public Property Get Contrasena() As String
Contrasena = m_Contrasena
End Property
Public Property Let Contrasena(ByVal Value As String)
m_Contrasena = Value
End Property
Public Property Get From() As String
From = m_From
End Property
Public Property Let From(ByVal Value As String)
m_From = Value
End Property
Public Property Get ToAddress() As String
ToAddress = m_ToAddress
End Property
Public Property Let ToAddress(ByVal Value As String)
m_ToAddress = Value
End Property
Public Property Get CC() As String
CC = m_CC
End Property
Public Property Let CC(ByVal Value As String)
m_CC = Value
End Property
Public Property Get BCC() As String
BCC = m_BCC
End Property
Public Property Let BCC(ByVal Value As String)
m_BCC = Value
End Property
Public Function SendMail(ByVal sSubject As String, ByVal sBody As String, Optional fBody As formatBody = Text, Optional ByRef sAttachmentsArray As Variant) As String
On Error GoTo error
Dim iMsg As Object
Dim iConf As Object
Dim Flds As Variant
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
'cdo valores por defecto
iConf.Load -1
Set Flds = iConf.Fields
With Flds
.item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = m_ServidorSMTP
.item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = m_PuertoSMTP
'1=cdoSendUsingPickup / 2=cdoSendUsingPort
.item("http://schemas.microsoft.com/cdo/configuration/sendusing") = m_MetodoEnvio
'0=cdoAnonymous / 1=cdoBasic /2=cdoNTLM
.item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = m_UsarAutenticacion
'True/False
.item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = m_UsarSSL
.item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = CONNECTION_TIMEOUT
.item("http://schemas.microsoft.com/cdo/configuration/sendusername") = m_Usuario
.item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = m_Contrasena
.Update
End With
With iMsg
Set .Configuration = iConf
.To = m_ToAddress
.CC = m_CC
.BCC = m_BCC
.From = m_From
.Subject = sSubject
If fBody = Text Then
.TextBody = sBody
Else
.HtmlBody = sBody
End If
If Not IsMissing(sAttachmentsArray) Then
If IsArray(sAttachmentsArray) Then
Dim i As Integer
For i = LBound(sAttachmentsArray) To UBound(sAttachmentsArray)
.AddAttachment sAttachmentsArray(i)
Next i
End If
End If
.Send
End With
Set iMsg = Nothing
Set iConf = Nothing
Set Flds = Nothing
If Err.Number = 0 Then
Debug.Print "Message sent successfully!"
SendMail = ""
End If
Exit Function
Resume
error:
Debug.Print Err.Number & " " & Err.Description
SendMail = Err.Number & " " & Err.Description
End Function
martes, 12 de septiembre de 2017
VBA Access. Módulo de clase clsLog. Escribir en un fichero. Útil para crear ficheros tipo Log o escribir cualquier valor a un fichero.
Option Compare Database
Option Explicit
Private Sub Class_Initialize()
'initialize values
End Sub
Private Sub Class_Terminate()
'deallocate if needed
End Sub
Public Function Log(ByVal sPathFileName As String, ByVal sValueToLog As String, Optional ByVal bAppend As Boolean = True) As String
On Error GoTo error
Dim sValue As String 'valor a escribir en el log
Dim SFName As String 'ruta y nombre completo del fichero de texto
Dim iFNumber As Integer
sValue = sValueToLog
SFName = sPathFileName
'crear la ruta completa si no existe
MakeDirFullPath (Left(SFName, InStrRev(SFName, "\") - 1))
'obtener numero de fichero
iFNumber = FreeFile
'añadir o sobreescribir el fichero
If bAppend Then
Open SFName For Append As #iFNumber
Else
Open SFName For Output As #iFNumber
End If
Print #iFNumber, sValue
Close #iFNumber
Log = SFName
Exit Function
error:
Log = ""
Debug.Print Err.Description
End Function
Private Function MakeDirFullPath(ByVal sPath As String) As Boolean
On Error GoTo error
'crear todo el path de un directorio
If Right(sPath, 1) = "\" Then
sPath = Left(sPath, Len(sPath) - 1)
End If
Dim SplitPath() As String
SplitPath = Split(sPath, "\")
Dim Value As Integer
Dim Merge As String
For Value = 0 To UBound(SplitPath)
If Value <> 0 Then
Merge = Merge & "\"
End If
Merge = Merge & SplitPath(Value)
If Dir(Merge, vbDirectory) = "" Then
MkDir Merge
End If
Next
SetAttr sPath, vbNormal
MakeDirFullPath = True
Exit Function
error:
MakeDirFullPath = False
Debug.Print Err.Description
End Function
Option Explicit
Private Sub Class_Initialize()
'initialize values
End Sub
Private Sub Class_Terminate()
'deallocate if needed
End Sub
Public Function Log(ByVal sPathFileName As String, ByVal sValueToLog As String, Optional ByVal bAppend As Boolean = True) As String
On Error GoTo error
Dim sValue As String 'valor a escribir en el log
Dim SFName As String 'ruta y nombre completo del fichero de texto
Dim iFNumber As Integer
sValue = sValueToLog
SFName = sPathFileName
'crear la ruta completa si no existe
MakeDirFullPath (Left(SFName, InStrRev(SFName, "\") - 1))
'obtener numero de fichero
iFNumber = FreeFile
'añadir o sobreescribir el fichero
If bAppend Then
Open SFName For Append As #iFNumber
Else
Open SFName For Output As #iFNumber
End If
Print #iFNumber, sValue
Close #iFNumber
Log = SFName
Exit Function
error:
Log = ""
Debug.Print Err.Description
End Function
Private Function MakeDirFullPath(ByVal sPath As String) As Boolean
On Error GoTo error
'crear todo el path de un directorio
If Right(sPath, 1) = "\" Then
sPath = Left(sPath, Len(sPath) - 1)
End If
Dim SplitPath() As String
SplitPath = Split(sPath, "\")
Dim Value As Integer
Dim Merge As String
For Value = 0 To UBound(SplitPath)
If Value <> 0 Then
Merge = Merge & "\"
End If
Merge = Merge & SplitPath(Value)
If Dir(Merge, vbDirectory) = "" Then
MkDir Merge
End If
Next
SetAttr sPath, vbNormal
MakeDirFullPath = True
Exit Function
error:
MakeDirFullPath = False
Debug.Print Err.Description
End Function
viernes, 8 de septiembre de 2017
VBA Access. Obtener más datos de ayuda para depurar errores en una aplicación Access en producción.
'VBA Access no ofrece de forma nativa una manera de obtener datos como el nombre del procedimiento que ha causado el error y la línea.
'Si tenemos problemas para depurar los errores de nuestra aplicación Access, podemos añadir un poco de código para ayudar a esta tarea, sobretodo en un entorno de producción.
'NOTA: Numerar las líneas, nos permitirá con la función ERL obtener la línea que ha causado el error
Function ProcName(Arg1 As String, Arg2 As String)
On Error GoTo error
Const METHODNAME = "ProcName"
10 línea de código
30 línea de código
40 línea de código
...
Exit Function
error:
MsgBox "ModName: " & Application.VBE.ActiveCodePane.CodeModule.Name & vbCrLf & _
"ProcCall: " & METHODNAME & vbCrLf & _
"ErrorLine: " & Erl & vbCrLf & _
"ErrorNum: " & Err.Number & vbCrLf & _
"ErrorDesc: " & Err.Description & vbCrLf & _
"SourceCode: " & Err.Source, , "AppName"
End Function
'Si tenemos problemas para depurar los errores de nuestra aplicación Access, podemos añadir un poco de código para ayudar a esta tarea, sobretodo en un entorno de producción.
'NOTA: Numerar las líneas, nos permitirá con la función ERL obtener la línea que ha causado el error
Function ProcName(Arg1 As String, Arg2 As String)
On Error GoTo error
Const METHODNAME = "ProcName"
10 línea de código
30 línea de código
40 línea de código
...
Exit Function
error:
MsgBox "ModName: " & Application.VBE.ActiveCodePane.CodeModule.Name & vbCrLf & _
"ProcCall: " & METHODNAME & vbCrLf & _
"ErrorLine: " & Erl & vbCrLf & _
"ErrorNum: " & Err.Number & vbCrLf & _
"ErrorDesc: " & Err.Description & vbCrLf & _
"SourceCode: " & Err.Source, , "AppName"
End Function
jueves, 7 de septiembre de 2017
VBA Access. Crear un recordset en memoria sin vincular a ninguna tabla y poder modificar sus valores.
'De utilidad si necesitamos añadir un campo adicional que una tabla no tiene.
'En este caso el campo sería: Seleccionadas, que representa el numero de unidades seleccionadas de un determinado lote
'Al hacerlo de esta manera, al asignar al formulario el Recordset construido en memoria, podemos modificar los valores sin ningún problema
...
'Creamos el Recordset en memoria
Dim rsvM As ADODB.Recordset
Set rsM = New ADODB.Recordset
With rsM
.Fields.Append "ReferenciaArtículo", adVarChar, 20, adFldKeyColumn
.Fields.Append "Descripción", adVarChar, 250, adFldMayBeNull
.Fields.Append "Lote", adVarChar, 20, adFldMayBeNull
.Fields.Append "FechaCaducidad", adDate, , adFldMayBeNull
.Fields.Append "Unidades", adDecimal, , adFldMayBeNull
.Fields.Append "Seleccionadas", adDecimal, , adFldMayBeNull
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.LockType = adLockPessimistic
.Open
End With
'Leemos registros de la tabla Lotes en modo solo lectura
Dim rs New As ADODB.RecordSet
rs.Open "SELECT * FROM Lotes Where Referencia = 'XXXXXX'", cadenaconexion, adOpenStatic, adLockReadOnly
Do While Not rs.EOF
'Añadimos registros al recordset en memoria
'NOTA: La columna: Seleccionadas, no existe en la tabla Lotes
With rsM
.AddNew
.Fields("ReferenciaArtículo") = rs.Fields("ReferenciaArtículo")
.Fields("Descripción") = rs.Fields("Descripción")
.Fields("Lote") = rs.Fields("Lote")
.Fields("FechaCaducidad") = rs.Fields("FechaCaducidad")
.Fields("Unidades") = rs.Fields("Unidades")
.Fields("Seleccionadas") = 0
.Update
End With
rs.MoveNext
Loop
'Cerramos y liberamos recursos del recordset de la lectura de la tabla
rs.Close
Set rs = Nothing
'Asignamos el recordset en memoria al formulario para poder modificar el valor del campo: Seleccionadas. En el detalle del formulario deberemos tener en diversos textbox los campos del recordset.
Set Me.Recordset = rsM
...
'En este caso el campo sería: Seleccionadas, que representa el numero de unidades seleccionadas de un determinado lote
'Al hacerlo de esta manera, al asignar al formulario el Recordset construido en memoria, podemos modificar los valores sin ningún problema
...
'Creamos el Recordset en memoria
Dim rsvM As ADODB.Recordset
Set rsM = New ADODB.Recordset
With rsM
.Fields.Append "ReferenciaArtículo", adVarChar, 20, adFldKeyColumn
.Fields.Append "Descripción", adVarChar, 250, adFldMayBeNull
.Fields.Append "Lote", adVarChar, 20, adFldMayBeNull
.Fields.Append "FechaCaducidad", adDate, , adFldMayBeNull
.Fields.Append "Unidades", adDecimal, , adFldMayBeNull
.Fields.Append "Seleccionadas", adDecimal, , adFldMayBeNull
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.LockType = adLockPessimistic
.Open
End With
'Leemos registros de la tabla Lotes en modo solo lectura
Dim rs New As ADODB.RecordSet
rs.Open "SELECT * FROM Lotes Where Referencia = 'XXXXXX'", cadenaconexion, adOpenStatic, adLockReadOnly
Do While Not rs.EOF
'Añadimos registros al recordset en memoria
'NOTA: La columna: Seleccionadas, no existe en la tabla Lotes
With rsM
.AddNew
.Fields("ReferenciaArtículo") = rs.Fields("ReferenciaArtículo")
.Fields("Descripción") = rs.Fields("Descripción")
.Fields("Lote") = rs.Fields("Lote")
.Fields("FechaCaducidad") = rs.Fields("FechaCaducidad")
.Fields("Unidades") = rs.Fields("Unidades")
.Fields("Seleccionadas") = 0
.Update
End With
rs.MoveNext
Loop
'Cerramos y liberamos recursos del recordset de la lectura de la tabla
rs.Close
Set rs = Nothing
'Asignamos el recordset en memoria al formulario para poder modificar el valor del campo: Seleccionadas. En el detalle del formulario deberemos tener en diversos textbox los campos del recordset.
Set Me.Recordset = rsM
...
viernes, 1 de septiembre de 2017
Batch Script cerrar sesiones activas y desconectadas en un Windows Terminal Server para realizar un mantenimiento
rem Ejemplo bacth script para Terminal Server que avisa y cierra sesiones Activas y Desconectadas, exceptuando 1 Sesion y ademas para e inicia un servicio. Funciona correctamente en Windows 2008 Server R2
rem enviar mensajes a las sesiones Activas aviso menos a la sesion de Usuario
for /F "tokens=1,2,3,4,5" %%A in ('"query session | find "Activo""') DO (if NOT %%B==Usuario (msg %%B "Por mantenimiento, en 5 minutos su sesion va a ser cerrada. Conecte de nuevo en unos minutos." 2> nul))
rem espera 5 minutos antes de proceder
timeout /t 300 /nobreak
rem paramos un servicio
net stop nombre_servicio 2> nul
rem Esperar 30 segundos
timeout 30
rem cerramos sesiones Activas y Desconectadas menos la sesion de Usuario
for /F "tokens=1,2,3,4,5" %%A in ('"query session | find "Activo""') DO (if NOT %%B==Usuario (logoff %%C))
for /F "tokens=1,2,3,4,5" %%A in ('"query session | find "Desc""') DO (if NOT %%A==Usuario (logoff %%B))
rem Esperar 30 segundos
timeout 30
rem iniciar servicio
net start nombre_servicio 2> nul
rem Esperar 5 segundos
timeout 5
rem enviar mensajes a las sesiones Activas aviso menos a la sesion de Usuario
for /F "tokens=1,2,3,4,5" %%A in ('"query session | find "Activo""') DO (if NOT %%B==Usuario (msg %%B "Por mantenimiento, en 5 minutos su sesion va a ser cerrada. Conecte de nuevo en unos minutos." 2> nul))
rem espera 5 minutos antes de proceder
timeout /t 300 /nobreak
rem paramos un servicio
net stop nombre_servicio 2> nul
rem Esperar 30 segundos
timeout 30
rem cerramos sesiones Activas y Desconectadas menos la sesion de Usuario
for /F "tokens=1,2,3,4,5" %%A in ('"query session | find "Activo""') DO (if NOT %%B==Usuario (logoff %%C))
for /F "tokens=1,2,3,4,5" %%A in ('"query session | find "Desc""') DO (if NOT %%A==Usuario (logoff %%B))
rem Esperar 30 segundos
timeout 30
rem iniciar servicio
net start nombre_servicio 2> nul
rem Esperar 5 segundos
timeout 5
lunes, 24 de abril de 2017
SQL Server obtener listado de tablas o filtrarlas según un nombre mediante SQL
SELECT * FROM INFORMATION_SCHEMA.TABLES
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%contador%'
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%contador%'
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 'Zip / UnZip file or folder 'http://www.codekabinett.com/rdumps.php?Lang=2&targetDoc...
-
Option Compare Database Option Explicit ' Requisitos: '* Referencia VBA Microsoft Scripting Runtime (filesystemobject) '...