Professional Documents
Culture Documents
Capitolo 1 – Il linguaggio
Interpretato o compilato?
Function DebugMode() As Boolean
On Error Resume Next
Debug.Print 1 / 0
DebugMode = (Err <> 0)
Err.Clear
End Function
' una struttura UDT d'esempio che contiene praticamente ogni possibile tipo di dato
Private Type MyUDT
item1 As Boolean
item2(10) As Integer
item3 As Long
item4 As Single
item5 As Double
item6 As Currency
item7 As String * 20
End Type
Dim udt1 As MyUDT, udt2 As MyUDT
End Function
If ExactAge Then
' sottrae uno se la data del compleanno dell'anno corrente deve ancora arrivare
If DateSerial(Year(CurrentDate), Month(BirthDate), _
Day(BirthDate)) > CurrentDate Then
Age = Age - 1
End If
End If
End Property
End Function
retval = GetTimeZoneInformationAny(buffer(0))
End Function
retval = GetTimeZoneInformationAny(buffer(0))
End Function
' se Include è True o omesso, restituisce la prima occorrenza di uno dei caratteri
' specificati in Table, oppure zero se la ricerca fallisce
' se Include è False, restituisce la prima occorrenza di un qualsiasi carattere
' che NON compare in Table
End Function
re.Pattern = "january|february|march|april|may|june|july|september|october" _
& "|november|december"
' si assume che la stringa da analizzare sia contenuta nella variabile sourceText
For Each ma In re.Execute(sourceText)
Print "Found '" & ma.Value & "' at index " & ma.FirstIndex
Next
' ricerca tutte le parole specificate nel vettore passato come secondo argomento
' restituisce una matrice bidimensionale di Variant, dove arr(0,n) è l'n-esima
' parola corrispondente ed arr(1,n) è l'indice al quale è stata trovata la parola
End Function
Do
distance = distance \ 3
For index = distance + firstEl To lastEl
value = arr(index)
index2 = index
Do While (arr(index2 - distance) > value) Xor descending
arr(index2) = arr(index2 - distance)
index2 = index2 - distance
If index2 - distance < firstEl Then Exit Do
Loop
arr(index2) = value
Next
Loop Until distance = 1
End Sub
numEls = 10000
ReDim words(numEls) As String
ReDim hashTable(2 * numEls) As Integer
' legge le parole da un file
Open "words.dat" For Input As #1
For index = 1 To numEls
Line Input#1, words(index)
Next
Close #1
search = Text1.Text
hashIndex = Checksum(search)
Do
hashIndex = (hashIndex Mod numEls) + 1
Loop While hashTable(hashIndex) And words(hashTable(hashIndex)) <> search
If hashTable(hashIndex) Then
Print "Item found at index " & hashTable(hashIndex)
Else
Print "Item not found"
End If
Il numero di dimensioni di una matrice
Function ArrayDims(arr As Variant) As Integer
Dim i As Integer, bound As Long
On Error Resume Next
For i = 1 To 60
bound = LBound(arr, i)
If Err Then
ArrayDims = i - 1
Exit Function
End If
Next
End Function
Const SM_CXVSCROLL = 2
Const SM_CYHSCROLL = 3
End Sub
' Imposta il numero massimo di caratteri che possono essere immessi in un controllo ComboBox
Sub List1_Click()
' l'utente ha selezionato un nuovo elemento
' (attivato anche da Text1_KeyDown)
Text1.text = List1.text
End Sub
Sub Text1_Change()
Static active As Boolean
Dim index As Integer
Dim search As String
Dim found As Integer
' utilizza un metodo Move per impedire più eventi Resize e Paint
frm.Move GetSetting(AppName, frm.Name, "Left", frm.Left), _
GetSetting(AppName, frm.Name, "Top", frm.Top), GetSetting(AppName, _
frm.Name, "Width", frm.Width), GetSetting(AppName, frm.Name, "Height", _
frm.Height)
frm.WindowState = GetSetting(AppName, frm.Name, "WindowState", _
currWindowState)
End Function
End Sub
' Imposta i tabulatori. Ogni elemento della matrice viene espresso in unità dialog,
' dove ogni unità dialog è pari ad 1/4 della larghezza media del carattere.
End Function
Dim i As Integer
Dim child As Node
' limita a 10 caratteri il testo che può essere immesso in un elemento di un ListView
' Limita a 20 caratteri il testo che può essere immesso in un nodo di TreeView1
If SaveAsPlainText Then
Text = BW.Document.Body.innerHTML
Else
Text = BW.Document.documentElement.OuterHTML
End If
' questo evento viene scatenato quando alla form si invia un messaggio
If Err.Number Then
MsgBox "No default printer installed." & vbCrLf & _
"To install and select a default printer, select the " & _
"Setting / Printers command in the Start menu, and then " & _
"double-click on the Add Printer icon.", vbExclamation, _
"Printer Error"
PrinterIsInstalled = False
Else
PrinterIsInstalled = True
End If
End Function
With obj
' converte le coordinate in pixel
x2 = .ScaleX(X, .ScaleMode, vbPixels)
y2 = .ScaleY(Y, .ScaleMode, vbPixels)
' salva le proprietà FillStyle e FillColor
saveFillStyle = .FillStyle
saveFillColor = .FillColor
' imposta valori opportuni per queste proprietà
.FillStyle = 0
.FillColor = colorCode
If IsMissing(borderColor) Then
' leggi il colore alle coordinate date
borderColor = .Point(X, Y)
' modifica tutti i pixel di quel colore
ExtFloodFill .hDC, x2, y2, borderColor, FLOODFILLSURFACE
Else
' modifica tutti i pixel fino ad incontrare il bordo
ExtFloodFill .hDC, x2, y2, borderColor, FLOODFILLBORDER
End If
' ripristina le proprietà
.FillStyle = saveFillStyle
.FillColor = saveFillColor
End With
End Sub
Private Command1_Click()
MsgBox "Your mouse has " & GetNumMouseButtons & " buttons."
End Sub
End Sub
Unsupported:
' non tutte le versioni di Windows supportano questa funzione
MsgBox "SearchTreeForFile non supportata su questo sistema"
End Function
'----------------------------------------------------
' Un template per le classi Collection
'----------------------------------------------------
'
' Cosa fare dopo aver aggiunto questo template
' al programma corrente:
'
' 1) modificare il nome della classe a seconda delle necessità
' 2) utilizzare il comando "search and replace" per sostituire tutte le
' istanze di "BaseClassName" (senza virgolette) con il nome effettivo
' della classe di base
' 3) modificare eventualmente il metodo ADD in modo da inizializzare
' le proprietà dell'oggetto NEWITEM prima di aggiungerlo
' alla collezione privata
' 4) eliminare questi commenti
'------------------------------------------------------
Option Explicit
; ActiveX DLLs
[HKEY_CLASSES_ROOT\.dll]
@="dllfile"
[HKEY_CLASSES_ROOT\dllfile\shell\regdll]
@="Register ActiveX DLL"
[HKEY_CLASSES_ROOT\dllfile\shell\regdll\command]
@="regsvr32.exe \"%L\""
[HKEY_CLASSES_ROOT\dllfile\shell\unregdll]
@="Unregister ActiveX DLL"
[HKEY_CLASSES_ROOT\dllfile\shell\unregdll\command]
@="regsvr32.exe /u \"%L\""
; ActiveX Controls
[HKEY_CLASSES_ROOT\.ocx]
@="ocxfile"
[HKEY_CLASSES_ROOT\ocxfile\shell\regocx]
@="Register OCX Control"
[HKEY_CLASSES_ROOT\ocxfile\shell\regocx\command]
@="regsvr32.exe \"%L\""
[HKEY_CLASSES_ROOT\ocxfile\shell\unregocx]
@="Unregister OCX Control"
[HKEY_CLASSES_ROOT\ocxfile\shell\unregocx\command]
@="regsvr32.exe /u \"%L\""
; ActiveX EXEs
[HKEY_CLASSES_ROOT\.exe]
@="exefile"
[HKEY_CLASSES_ROOT\exefile\shell\regexe]
@="Register ActiveX EXE"
[HKEY_CLASSES_ROOT\exefile\shell\regexe\command]
@="\"%L\" /regserver"
[HKEY_CLASSES_ROOT\exefile\shell\unregexe]
@="Unregister Active EXE"
[HKEY_CLASSES_ROOT\exefile\shell\unregexe\command]
@="\"%L\" /unregserver"
' questa variabile viene condivisa dalle due routine che seguono
Dim m_ClientIsInterpreted As Boolean
' questa è una funzione di callback che viene eseguita per ogni
' finestra appartenente allo stesso thread della DLL
' l'istruzione seguente rende la proprietà modale rispetto alla form corrente
dataLink.hWnd = Me.hWnd
' visualizza la finestra di dialogo
On Error Resume Next
connString = dataLink.PromptNew
If Err = 0 Then
' Crea un oggetto Connection su questa stringa di connessione
cn.ConnectionString = connString
Else
' L'utente ha cancellato l'operazione
End If
If rs.EOF Then
' elimina le doppie virgolette in eccesso
tmp = Left$(tmp, Len(tmp) - 1)
End If
Print #1, tmp;
Loop
Close #1
' Aggiunge nuovi record alla tabella Authors del database Pubs
' utilizzando un Recordset disconnesso e senza una connessione iniziale
' (più precisamente, questo codice eseguirà una connessione iniziale extra
' solo quando viene eseguito per la prima volta).
fnum = FreeFile
Open filename For Binary As fnum
' Leggi il file in blocchi di 8K e appendi il contenuto al Field
bytesLeft = LOF(fnum)
Do While bytesLeft
bytes = bytesLeft
If bytes > ChunkSize Then bytes = ChunkSize
ReDim tmp(1 To bytes) As Byte
Get #1, , tmp
fld.AppendChunk tmp
bytesLeft = bytesLeft - bytes
Loop
Close #fnum
End Sub
' Esegue l'azione solo se viene aggiunto un DSN che non esiste
' oppure rimuove un DSN esistente
If (sDBQ = "" And lAction = ODBC_ADD_DSN) Or (sDBQ <> "" And lAction = _
ODBC_REMOVE_DSN) Then
fnum = FreeFile
Open DSNFile For Output As #fnum
isOpen = True
ErrorHandler:
If isOpen Then Close #fnum
Err.Raise Err.Number, , Err.Description
End Sub
' Apre una connessione – sostituire "myserver" con il nome del SQL Server da usare
connString = "Provider=SQLOLEDB;Data Source=myserver;Initial Catalog=Pubs"
cn.Open connString, "sa", ""
' Apre il recordset
sql = "Select * from sysobjects where type = 'P' and category = 0"
rs.Open sql, cn, adOpenStatic, adLockReadOnly, adCmdText
' Carica i risultati in un controllo DataGrid
Set DataGrid1.DataSource = rs
DataGrid1.Refresh
rs.Open "SELECT * FROM " & tblName & " WHERE " & strFilter, mCn, _
adOpenStatic, adLockPessimistic
Set rs = Nothing
End Property
rs.Open "SELECT * FROM " & tblName & " WHERE " & strFilter, mCn, _
adOpenStatic, adLockPessimistic
rs!Data = CVar(pb.Contents)
rs.Update
Else
If Not rs.EOF And Not rs.BOF Then
rs.Delete
End If
End If
Set rs = Nothing
End Property
For i = 1 To UBound(vArray)
vArray(i) = i
Next
For i = 1 To UBound(vArray2)
Debug.Print vArray2(i)
Next
OPEN tblnames
FETCH NEXT FROM tblnames INTO @obj_name, @obj_type
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN
IF @obj_type = 'U'
SELECT @message = 'Checking the rights for the Table '
IF @obj_type = 'V'
SELECT @message = ' Checking the rights for the Vable '
IF @obj_type = 'P'
SELECT @message = ' Checking the rights for the Stored Procedure '
SELECT @message = @message + RTRIM(UPPER(@obj_name))
PRINT @message
EXEC ('sp_helprotect ' + @obj_name )
END
FETCH NEXT FROM tblnames INTO @obj_name, @obj_type
END
CLOSE tblnames
DEALLOCATE tblnames
Condivisione di connessioni
/* Begin of script InstallCS.Sql */
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Dim SQL As String
-- WordApplication.Visible = True
IF @hr = 0
BEGIN
EXEC @hr = sp_OASetProperty @WordApplication, 'Visible', 1
waitfor delay '00:00:10'
END
use master
go
IF EXISTS( SELECT name FROM sysobjects WHERE name = 'sp_ExBlockingLocks' AND type = 'P')
drop proc sp_ExBlockingLocks
go
create procedure sp_ExBlockingLocks
as
set nocount on
select DISTINCT
sp.hostname HostName,
sp.program_name "Prg Name",
sp.hostprocess "PID",
sp.nt_domain "DOMAIN",
sp.nt_username "Usr Name",
sp.net_address "Net Addr",
sp.loginame "Login",
convert (smallint, l1.req_spid) As spid,
l1.rsc_dbid As dbid,
(SELECT name from master.dbo.sysdatabases (nolock) where dbid = l1.rsc_dbid) As Db,
l1.rsc_objid As ObjId,
(select name from sysobjects (nolock) where id = l1.rsc_objid) As Obj,
l1.rsc_indid As IndId,
substring (v.name, 1, 4) As Type,
substring (l1.rsc_text, 1, 16) as Resource,
substring (u.name, 1, 8) As Mode,
substring (x.name, 1, 5) As Status
where
l1.rsc_type = v.number
and v.type = 'LR'
and l1.req_status = x.number
and x.type = 'LS'
and l1.req_mode + 1 = u.number
and u.type = 'L'
and l1.rsc_type <>2 /* not a DB lock */
and l1.rsc_dbid = l2.rsc_dbid
and l1.rsc_bin = l2.rsc_bin
and l1.rsc_objid = l2.rsc_objid
and l1.rsc_indid = l2.rsc_indid
and l1.req_spid <> l2.req_spid
and l1.req_status <> l2.req_status
and sp.spid = l1.req_spid
order by
substring (l1.rsc_text, 1, 16),
substring (x.name, 1, 5)
return (0)
With MMControl1
' Inizializza il controllo Multimedia
.DeviceType = "CDAudio"
.TimeFormat = 10
.Command = "Open"
' i secondi sono memorizzati nel byte più significativo
Value = (.Length \ 256) And 255
TotalTime = Right$("0" & CStr(Value), 2) & """"
' i minuti sono memorizzati nel byte meno significativo
Value = (.Length And 255) Mod 60
TotalTime = Right$("0" & CStr(Value), 2) & "' " & TotalTime
Value = (.Length And 255) \ 60
If Value > 0 Then
' visualizza la durata solo se necessario
TotalTime = CStr(Value) & "h " & TotalTime
End If
MsgBox TotalTime
End With
End Sub
Capitolo 15 - Le funzioni API di Windows
Determinare l'utilizzo della memoria
Private Type MEMORYSTATUS
dwLength As Long
dwMemoryLoad As Long
dwTotalPhys As Long
dwAvailPhys As Long
dwTotalPageFile As Long
dwAvailPageFile As Long
dwTotalVirtual As Long
dwAvailVirtual As Long
End Type
Private Declare Sub GlobalMemoryStatus Lib "kernel32" Alias "GlobalMemoryStatus" _
(lpBuffer As MEMORYSTATUS)
Sub ShowMemory()
Dim ms As MEMORYSTATUS
Dim msg As String
Sub ALengthyTask()
Dim hNewCursor As Long
Dim hSavCursor As Long
End Sub
[HKEY_CLASSES_ROOT\Directory\Shell\DosPrompt]
@="Run MS-DOS Prompt here"
[HKEY_CLASSES_ROOT\Directory\Shell\DosPrompt\Command]
@="Cmd /k CD \"%L\" "
:ExitCodeTwo
REM process here exit code equals to two
REM ...
GOTO EndBatch
:ExitCodeOne
REM process here exit code equals to one
REM ...
:EndBatch
ECHO goodbye.
' uno shortcut per Internet è semplicemente un file di testo di due righe
fnum = FreeFile
Open FileName For Output As #fnum
Print #fnum, "[InternetShortcut]"
Print #fnum, "URL=" & URL
Close #fnum
End Sub
url = "http://www.vb2themax.com/default.asp"
' Questo è necessario in quanto viene passata una stringa Unicode
b = url & vbNullChar
dwState = 0
dwSize = LenB(dwState)
' Questo file è di 2MB, pertanto si potrebbe voler tentare con qualcosa di più semplice
Dim errcode As Long
Dim url As String
Dim localFileName As String
url = "http://www.vb2themax.com/vbmaximizer/files/vbm_demo.zip"
localFileName = "c:\vbm_demo.zip"
' Apre il programma predefinito per l'invio dei messaggi di posta elettronica
' Restituisce True in caso di successo, altrimenti False
If offLineMode Then
ci.dwConnectedState = INTERNET_STATE_DISCONNECTED_BY_USER
ci.dwFlags = ISO_FORCE_DISCONNECTED
Else
ci.dwConnectedState = INTERNET_STATE_CONNECTED
End If
HTMLEncode = Text