Accedi alle tabelle VBA: aggiorna, conta, elimina, crea, rinomina, esporta

Questo tutorial ti insegnerà come lavorare con Access Tables usando VBA.

Accedi alle tabelle VBA

Per iniziare dimostreremo i semplici comandi per lavorare con le tabelle in Access. Più avanti in questo tutorial ti mostreremo le funzioni complete sviluppate professionalmente per lavorare con le tabelle in Access.

Crea tabella

Questo codice utilizzerà SQL per creare una tabella denominata "Table1" con i campi "ID" e "Name":

 Dim nome_tabella As String Dim campi As String nome_tabella = "Table1" fields = "([ID] varchar(150), [Nome] varchar(150))" CurrentDb.Execute "CREATE TABLE " & table_name & campi

Chiudi tabella

Questa riga di codice VBA chiuderà una tabella (salvando le modifiche):

DoCmd.Close acTable, "Table1", acSaveSì

Per chiudere una tabella senza salvare:

DoCmd.Close acTable, "Table1", acSaveNo

Elimina tabella

Questo codice cancellerà una tabella (nota: prima la tabella dovrebbe essere chiusa):

DoCmd.Close acTable, "Table1", acSaveYes DoCmd.DeleteObject acTable = acDefault, "Table1"

Rinomina tabella:

Questa riga di codice rinominerà una tabella di accesso:

DoCmd.Rename "Table1", actTable, "Table1_New"

Un'altra opzione consiste nell'usare la proprietà TableDefs di un oggetto di database.

Imposta tdf = db.TableDefs(strOldTableName) tdf.Name = strNewTableName

Svuota / Cancella tabella

Questo codice VBA svuoterà una tabella:

DoCmd.RunSQL "CANCELLA * DA " & "Tabella1"

Tronca tabella/Elimina record

Questa riga di codice VBA utilizza SQL per eliminare i record da una tabella che soddisfano determinati criteri:

DoCmd.RunSQL ("DELETE * FROM " & "Table1" & " WHERE " & "num=2")

Esporta tabella in Excel

Per esportare una tabella in Excel usa il pulsante DoCmd.OutputTo metodo:

DoCmd.OutputTo acOutputTable, "Table1", acFormatXLS, "c:\temp\ExportedTable.xls"

oppure usa il DoCmd.TransferFoglio di calcolo metodo:

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", "c:\temp\ExportedTable.xls", True

Aggiorna tabella

Il codice seguente aggiornerà un record, senza visualizzare il messaggio di avviso:

DoCmd.SetWarnings (False) DoCmd.RunSQL "Aggiorna ProductsT SET ProductsT.ProductName = 'Product AAA' WHERE (((ProductsT.ProductID)=1))"

Accedi alle funzioni della tabella VBA

Gli esempi di codice sopra sono i semplici comandi che puoi utilizzare per interagire con le tabelle utilizzando VBA. Tuttavia, sarà spesso necessario aggiungere molto più codice di supporto (inclusa la gestione degli errori) per utilizzare correttamente questi comandi. Di seguito troverai le funzioni di sviluppo professionale per lavorare con le tabelle in Access.

Contare i record della tabella

Questa funzione conterà il numero di record in una tabella:

Funzione pubblica Count_Table_Records(TableName As String) As Integer On Error GoTo Err: Dim r As DAO.Recordset Dim c As Integer Set r = CurrentDb.OpenRecordset("Select count(*) as rcount from " & TableName).OpenRecordset If (r .EOF) Then c = 0 Else c = Nz(r!rCount, 0) End If Count_Table_Records = c Exit Function Err: Call MsgBox("Si è verificato un errore: " & Err.Description, vbExclamation, "Error") End Function ' Esempio di utilizzo Private Sub Count_Table_Records_Example() MsgBox (Count_Table_Records("Table1")) End Sub

Controlla se la tabella esiste Funzione

Questa funzione verificherà se esiste una tabella, restituendo VERO o FALSO:

Public Function TableExists(ByVal strTableName As String) As Boolean 'Function: Determina se la tabella esiste in un database di Access 'Arguments:strTablename: Name of table to check Dim tdf As DAO.TableDef On Error Resume Next Set tdf = CurrentDb.TableDefs(strTableName ) TableExists = (Err.Number = 0) End Function

Ecco un esempio della funzione in uso:

Private Sub TableExists_Example() If VBA_Access_Checks.TableExists("Table") = True Then MsgBox ("La tabella è stata trovata!") Else MsgBox ("La tabella NON è stata trovata!") End If End Sub

Crea funzione tabella

Questa funzione creerà una tabella in Access VBA nel database corrente:

Public Function CreateTable(table_fields As String, table_name As String) As Boolean Dim strCreateTable As String Dim intCount As Integer Dim strFields() As String Dim strValues() As String Dim strInsertSQL As String Dim intCounter As Integer Dim intData As Integer On Error strFields = Split(table_fields, ",") strCreateTable = "CREATE TABLE " & table_name & "(" For intCounter = 0 To UBound(strFields) - 1 strCreateTable = strCreateTable & "[" & strFields(intCounter) & "] varchar( 150)," Next If Right(strCreateTable, 1) = "," Then strCreateTable = Left(strCreateTable, Len(strCreateTable) - 1) strCreateTable = strCreateTable & ")" End If CurrentDb.Execute strCreateTable intCounter = 0 intData = 0 If Err.Number = 0 Then CreateTable = True Else CreateTable = False End If Exit Function Err: CreateTable = False MsgBox Err.Number & " " & Err.Description End Function

Questa funzione restituirà TRUE se la tabella è stata creata correttamente o FALSE se la tabella non è stata creata.

Puoi chiamare la funzione in questo modo:

Private Sub CreateTable_Example() Chiama CreateTable("f1,f2,f3,f4", "ttest") End Sub

Funzione Elimina/Rilascia tabella

Questa funzione eliminerà una tabella se esiste:

Funzione pubblica DeleteTableIfExists(TableName As String) If Not IsNull(DLookup("Name", "MSysObjects", "Name='" & TableName & "'")) Then DoCmd.SetWarnings False DoCmd.Close acTable, TableName, acSaveYes DoCmd. DeleteObject acTable = acDefault, TableName Debug.Print "Table " & TableName & " cancellò… " DoCmd.SetWarnings True End If End Funzione

Puoi chiamare la funzione in questo modo:

Private Sub DeleteTableIfExists_Example() Chiama DeleteTableIfExists("Table1") End Sub

Funzione tabella vuota

Questa funzione svuoterà una tabella se esiste:

Public Function EmptyTable(TableName As String) If Not IsNull(DLookup("Name", "MSysObjects", "Name='" & TableName & "'")) Then DoCmd.SetWarnings False DoCmd.RunSQL "DELETE * FROM " & TableName Debug.Print "Table " & TableName & " emptied… " DoCmd.SetWarnings True End If End Funzione

Puoi chiamare la funzione in questo modo:

Private Sub EmptyTable_Example() Call EmptyTable("Table1") End Sub

Rinomina funzione tabella

Questa funzione VBA rinominerà una tabella:

Funzione pubblica RenameTable(ByVal strOldTableName As String, ByVal strNewTableName As String, Optional strDBPath As String) As Boolean Dim db As DAO.Database Dim tdf As TableDef ' Trap per eventuali errori. On Error Resume Next ' Se il nome del database è vuoto… If Trim$(strDBPath) = "" Then '… quindi imposta Db al Db corrente. Set db = CurrentDb() Else ' Altrimenti, imposta Db sul database aperto specificato. Set db = DBEngine.Workspaces(0).OpenDatabase(strDBPath) ' Verifica se si è verificato un errore. If Err Then 'MsgBox "Impossibile trovare il database da aprire: " & strDBPath RenameTable = False Exit Function End If End If If ObjectExists("Table", strOldTableName, strDBPath) Then Set tdf = db.TableDefs(strOldTableName) tdf.Name = strNewTableName db.Close RenameTable = True Else RenameTable = False End If End Function 'Esempio di utilizzo Private Sub RenameTable_Example() Call RenameTable("table1", "table2") End Sub

Puoi chiamare la funzione in questo modo:

Private Sub RenameTable_Example() Call RenameTable("table1", "table2") End Sub

Tronca/Elimina i record dalla tabella

Questa funzione eliminerà i record da una tabella con gestione degli errori:

Funzione pubblica Delete_From_Table(TableName As String, Criteria As String) On Error GoTo SubError DoCmd.SetWarnings False DoCmd.RunSQL ("DELETE * FROM " & TableName & " WHERE " & Criteri) DoCmd.SetWarnings True SubExit: Exit Function SubError: MsgBox " Errore Delete_From_Table: " & vbCrLf & Err.Number & ": " & Err.Description Resume SubExit End Function 'Esempio di utilizzo Public Sub Delete_From_Table_Example() Call Delete_From_Table("Table1", "num=2") End Sub

Esporta tabella in Excel

Questa riga di codice esporterà una tabella in Excel (un nuovo foglio di calcolo):

DoCmd.OutputTo acOutputTable, "Table1", acFormatXLS, "c:\temp\ExportedTable.xls"

Oppure puoi usare questa funzione:

Funzione pubblica Export_Table_Excel(TableName As String, FilePath As String) DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, TableName, FilePath, True End Function 'Esempio di utilizzo Sub Export_Table_Excel_Example () Export_Table_Excel("Table1", "c:\tempxls") Fine sottotitolo

Il codice sopra verrà esportato in un nuovo foglio di calcolo. Puoi invece aggiungere una tabella a un foglio di calcolo esistente. Il nostro articolo sull'importazione/esportazione in Access VBA tratta questo aspetto in modo più dettagliato.

Aggiungi/Aggiungi record a una tabella

Questa funzione aggiungerà/aggiungerà un record a una tabella:

Funzione pubblica Append_Record_To_Table(TableName As String, FieldName As String, FieldValue As String) On Error GoTo SubError Dim rs As DAO.Recordset Dim SQL As String Dim CurrentYear As Integer Set rs = CurrentDb.OpenRecordset(TableName) rs.AddNew rs(FieldName) .Value = FieldValue rs.Update rs.Close Set rs = Nothing SubExit: Exit Function SubError: MsgBox "Errore di RunSQL: " & vbCrLf & Err.Number & ": " & Err.Description Resume SubExit End Function 'Esempio di utilizzo Private Sub Append_Record_To_Table_Example () Chiama Append_Record_To_Table("Table1", "num", 3) End Sub

Aggiungi record alla tabella dal modulo

Questa funzione aggiungerà un record a una tabella da un modulo:

Funzione pubblica Add_Record_To_Table_From_Form(TableName As String) On Error GoTo SubError Dim rs As DAO.Recordset Set rs = CurrentDb.OpenRecordset(TableName) rs.AddNew 'rs![Field1] = Value1 'rs![Field2] = Value2 'rs![ Field3] = Value3 rs.Update rs.Close Set rs = Nothing SubExit: Exit Function SubError: MsgBox "Refresh_Form error: " & vbCrLf & Err.Number & ": " & Err.Description End Function

Aiuterete lo sviluppo del sito, condividere la pagina con i tuoi amici

wave wave wave wave wave