Vorrei un’analisi dettagliata di questo codice in italiano, focalizzandosi sui seguenti…
- User
Vorrei un’analisi dettagliata di questo codice in italiano, focalizzandosi sui seguenti aspetti:
- Ridondanza di codice o controlli logici: Evidenziare eventuali duplicazioni o controlli logici non necessari.
- Ottimizzazioni: Indicare possibili miglioramenti per aumentare l’efficienza del codice.
- Compattazioni: Suggerire modi per rendere il codice più compatto.
- Miglioramento dell’efficienza e della velocità di esecuzione: Consigli su come ottimizzare le prestazioni del codice. Per ciascuno dei punti da 1 a 4, sarebbero graditi suggerimenti specifici specifici indicando il PRIMA, cioe' il codice orginale e il DOPO, con le modifiche da te proposte. Option Explicit
Dim wsOdierno As Worksheet Dim wsAnalyze As Worksheet Dim wsData As Worksheet Dim wsStorico As Worksheet
Sub ToggleApplicationSettings(ByVal enable As Boolean) Application.Calculation = IIf(enable, xlCalculationAutomatic, xlCalculationManual) Application.ScreenUpdating = enable Application.EnableEvents = enable End Sub
Sub Analyze_Data() Dim myRanges() As Range
ToggleApplicationSettings False Set wsOdierno = ThisWorkbook.Worksheets("Odierno") Set wsAnalyze = ThisWorkbook.Worksheets("Analyze") Set wsData = ThisWorkbook.Worksheets("Data") Set wsStorico = ThisWorkbook.Worksheets("Storico") CreateRanges myRanges Elabora_Dati myRanges StoricizzaDatieVar ToggleApplicationSettings TrueEnd Sub
Sub CreateRanges(ByRef myRanges() As Range) Dim i As Integer Dim baseRange As String Dim rangesAddresses(1 To 5) As Variant
baseRange = "E12:E49,E51:E62,E64:E81,E84:E96,E98:E111" For i = 1 To 5 rangesAddresses(i) = Split(Replace(baseRange, "E", Chr(69 + i - 1)), ",") Next i ReDim myRanges(1 To 5) ' Usa Join per creare il range senza usare Union For i = 1 To 5 Set myRanges(i) = wsOdierno.Range(Join(rangesAddresses(i), ",")) Next iEnd Sub
Sub Elabora_Dati(ByRef myRanges() As Range) Dim i As Integer
ToggleApplicationSettings True ' Riabilita solo per la parte visiva ' Procedi normalmente con il resto delle operazioni For i = 2 To 6 wsAnalyze.Select myRanges(i - 1).Copy wsAnalyze.Range("D13") AnalyzeOnly Sheets("VAR").Cells(26, i).Resize(11).Value = Application.Transpose(Sheets("Analyze").Range("F10:P10").Value) Next i ToggleApplicationSettings False ' Disabilita di nuovo una volta che la visione non è più richiestaEnd Sub
Sub StoricizzaDatieVar() Dim myMultiAreaPrice As Range Dim wsVAR As Worksheet Dim wsDestinations(1 To 5) As Worksheet Dim col As Integer Dim lastRows As Variant
' Copia dati di sicurezza ed immagazzina dati chiusi precedenti Set wsVAR = ThisWorkbook.Worksheets("VAR") wsVAR.Range("R22:V24").Value = wsVAR.Range("B22:F24").Value ' Incolla su Foglio Data Set myMultiAreaPrice = Union(wsOdierno.Range("A10:A49"), wsOdierno.Range("A51:A62"), wsOdierno.Range("A64:A81"), wsOdierno.Range("A84:A96"), wsOdierno.Range("A98:A111")) myMultiAreaPrice.Copy wsData.Range("A1").End(xlDown).Offset(1, 0).PasteSpecial Paste:=xlValues, Transpose:=True ' Incolla su Foglio Storico wsOdierno.Range("A9:A111").Copy wsStorico.Range("A10").End(xlDown).Offset(1, 0).PasteSpecial Paste:=xlValues, Transpose:=True ' Incolla su altri fogli Set wsDestinations(1) = Sheets("Cass") Set wsDestinations(2) = Sheets("Tr") Set wsDestinations(3) = Sheets("Tot") Set wsDestinations(4) = Sheets("BCC") Set wsDestinations(5) = Sheets("Gen") lastRows = Array(52, 52, 52, 52, 60) ' Colonna 6 ha 60 righe, le altre 52 OrdinaVAR For col = 11 To 15 wsVAR.Range(wsVAR.Cells(3, col), wsVAR.Cells(lastRows(col - 11), col)).Copy wsDestinations(col - 10).Range("A10").End(xlDown).Offset(1, 0).PasteSpecial Paste:=xlValues, Transpose:=True Next col ' Copia dati di sicurezza wsVAR.Range("R61:V68").Value = wsVAR.Range("B61:F68").Value wsVAR.Range("B61:F68").Value = wsVAR.Range("B53:F60").Value Sheets("Gen").Select Application.ScreenUpdating = TrueEnd Sub
Sub OrdinaVAR() Dim ws As Worksheet Dim lookupRange As Range Dim foundCell As Range Dim rowIndex As Long Dim i As Long Dim azione As String Dim sourceValues As Variant Dim sourceFormats As Variant Dim destRange As Range Dim j As Integer Dim cell As Range
Set ws = ThisWorkbook.Sheets("VAR") Set lookupRange = ws.Range("G3:G52") ' Imposta l'indice di riga di destinazione iniziale 3 rowIndex = 3 With ws For i = 3 To 52 ' Ottiene il valore di lookup dalla colonna H (8) Dim lookupValue As Variant lookupValue = .Cells(i, "H").Value ' H3:H52 ' Definisce l'intervallo di destinazione nella riga corrente Set destRange = .Range("J" & rowIndex & ":O" & rowIndex) ' Verifica se ci sono celle unite e le scompatta If destRange.MergeCells Then destRange.UnMerge End If ' Esegue il controllo del valore di lookup If Not IsEmpty(lookupValue) Then ' Cerca il valore di lookup nell'intervallo di ricerca Set foundCell = lookupRange.Find(What:=lookupValue, LookIn:=xlValues, LookAt:=xlWhole) If Not foundCell Is Nothing Then sourceValues = .Range("A" & foundCell.Row & ":F" & foundCell.Row).Value ' Verifica le dimensioni If UBound(sourceValues, 1) = destRange.Rows.Count And _ UBound(sourceValues, 2) = destRange.Columns.Count Then destRange.Value = sourceValues Else ' Gestisci la discrepanza Debug.Print "Mismatch nelle dimensioni per rowIndex " & rowIndex destRange.ClearContents End If ' Copia i formati sourceFormats = .Range("A" & foundCell.Row & ":F" & foundCell.Row).NumberFormat If IsArray(sourceFormats) Then For j = 1 To UBound(sourceFormats, 2) On Error Resume Next destRange.Cells(1, j).NumberFormat = sourceFormats(1, j) If err.Number <> 0 Then destRange.Cells(1, j).NumberFormat = "General" err.Clear End If On Error GoTo 0 Next j Else ' Se sourceFormats è una stringa, applica lo stesso formato a tutte le celle On Error Resume Next destRange.NumberFormat = sourceFormats If err.Number <> 0 Then destRange.NumberFormat = "General" err.Clear End If On Error GoTo 0 End If Else destRange.ClearContents End If Else destRange.ClearContents End If Select Case UCase(Trim(.Cells(i, "I").Value)) Case "B" azione = "ARROTONDA_1000" Case "C" azione = "ARROTONDA_4" Case "D" azione = "ARROTONDA_100" Case Else azione = "NESSUNA" End Select Select Case azione Case "ARROTONDA_1000" For Each cell In destRange If IsNumeric(cell.Value) And cell.Value > 1000 Then cell.Value = Application.WorksheetFunction.MRound(cell.Value, 1000) End If Next cell Case "ARROTONDA_4" For Each cell In destRange If IsNumeric(cell.Value) Then cell.Value = Application.WorksheetFunction.Round(cell.Value, 4) End If Next cell Case "ARROTONDA_100" For Each cell In destRange If IsNumeric(cell.Value) And cell.Value > 100 Then cell.Value = Application.WorksheetFunction.MRound(cell.Value, 100) End If Next cell Case "NESSUNA" ' Non eseguire alcuna operazione End Select ' Incrementa l'indice di riga di destinazione per la prossima iterazione rowIndex = rowIndex + 1 ' Verifica che rowIndex non superi il numero di righe del foglio If rowIndex > ws.Rows.Count Then MsgBox "Riga di destinazione supera il limite del foglio.", vbCritical Exit Sub End If Next i ' Copia i valori e i formati da F53:F60 a O53:O60 senza usare Copy/PasteSpecial .Range("O53:O60").Value = .Range("F53:F60").Value For j = 1 To .Range("F53:F60").Rows.Count On Error Resume Next .Range("O53:O60").Cells(j, 1).NumberFormat = .Range("F53:F60").Cells(j, 1).NumberFormat If err.Number <> 0 Then .Range("O53:O60").Cells(j, 1).NumberFormat = "General" err.Clear End If On Error GoTo 0 Next j ' Aggiorna i dati di sicurezza (backup) .Range("R22:V24").Value = .Range("B22:F24").Value .Range("B61:F68").Value = .Range("B53:F60").Value End With Application.CutCopyMode = FalseEnd Sub
- Assistant
Certamente! Analizzerò il codice fornito focalizzandomi sui quattro aspetti richiesti: ridondanza, ottimizzazioni, compattazioni e miglioramento dell’efficienza e della velocità di esecuzione. Per ciascun punto, fornirò esempi specifici con il codice originale (PRIMA) e le modifiche proposte (DOPO).
1. Ridondanza di codice o controlli logici
Osservazioni:
- Uso eccessivo di
SelecteActivate: L'uso diSelectper selezionare fogli o celle è ridondante e rallenta l'esecuzione del codice. - Ripetizione di accessi al foglio di lavoro: Accedere ripetutamente ai fogli di lavoro all'interno dei cicli può essere ottimizzato memorizzando i riferimenti una volta.
Esempi Specifici:
Esempio 1: Eliminazione di
SelectPRIMA:
For i = 2 To 6 wsAnalyze.Select myRanges(i - 1).Copy wsAnalyze.Range("D13") AnalyzeOnly Sheets("VAR").Cells(26, i).Resize(11).Value = Application.Transpose(Sheets("Analyze").Range("F10:P10").Value) Next iDOPO:
For i = 2 To 6 myRanges(i - 1).Copy wsAnalyze.Range("D13") AnalyzeOnly wsVAR.Cells(26, i).Resize(11).Value = Application.Transpose(wsAnalyze.Range("F10:P10").Value) Next iAssunzione:
wsVARè stato precedentemente definito come riferimento al foglio "VAR".Esempio 2: Minimizzazione degli accessi ai fogli di lavoro
PRIMA:
wsVAR.Range("R22:V24").Value = wsVAR.Range("B22:F24").Value ' ... wsVAR.Range("B61:F68").Value = wsVAR.Range("B53:F60").ValueDOPO:
Dim backupRange1 As Variant Dim backupRange2 As Variant backupRange1 = wsVAR.Range("B22:F24").Value wsVAR.Range("R22:V24").Value = backupRange1 backupRange2 = wsVAR.Range("B53:F60").Value wsVAR.Range("B61:F68").Value = backupRange2Motivazione: Riduce il numero di accessi diretti al foglio di lavoro memorizzando i dati in variabili temporanee.
2. Ottimizzazioni
Osservazioni:
- Uso inefficiente delle funzioni di copia e incolla: L'uso di
CopyePasteSpecialpuò essere sostituito con assegnazioni dirette dei valori per migliorare le prestazioni. - Ciclo
For Eachall'interno diOrdinaVAR: L'applicazione di formati cella per cella può essere ottimizzata applicando il formato all'intervallo intero quando possibile.
Esempi Specifici:
Esempio 1: Sostituzione di
CopyePasteSpecialcon assegnazioni direttePRIMA:
wsOdierno.Range("A9:A111").Copy wsStorico.Range("A10").End(xlDown).Offset(1, 0).PasteSpecial Paste:=xlValues, Transpose:=TrueDOPO:
Dim sourceData As Variant Dim destCell As Range sourceData = wsOdierno.Range("A9:A111").Value Set destCell = wsStorico.Range("A10").End(xlDown).Offset(1, 0) destCell.Resize(UBound(sourceData, 1), UBound(sourceData, 2)).Value = Application.Transpose(sourceData)Motivazione: Evita l'uso di
CopyePasteSpecial, riducendo il tempo di esecuzione.Esempio 2: Ottimizzazione dell'applicazione dei formati
PRIMA:
For j = 1 To .Range("F53:F60").Rows.Count On Error Resume Next .Range("O53:O60").Cells(j, 1).NumberFormat = .Range("F53:F60").Cells(j, 1).NumberFormat If err.Number <> 0 Then .Range("O53:O60").Cells(j, 1).NumberFormat = "General" err.Clear End If On Error GoTo 0 Next jDOPO:
With .Range("F53:F60") .Copy .Offset(0, 9).PasteSpecial Paste:=xlNumberFormats End With Application.CutCopyMode = FalseMotivazione: Applica i formati a tutto l'intervallo in una sola operazione invece di cella per cella.
3. Compattazioni
Osservazioni:
- Uso di
Withper ridurre la ripetizione del riferimento al foglio di lavoro. - Unificazione di condizioni simili per evitare codice ridondante.
Esempi Specifici:
Esempio 1: Utilizzo di blocchi
WithPRIMA:
Set wsVAR = ThisWorkbook.Worksheets("VAR") wsVAR.Range("R22:V24").Value = wsVAR.Range("B22:F24").Value ' ... wsVAR.Range("B61:F68").Value = wsVAR.Range("B53:F60").ValueDOPO:
With wsVAR .Range("R22:V24").Value = .Range("B22:F24").Value .Range("B61:F68").Value = .Range("B53:F60").Value End WithMotivazione: Riduce la ripetizione del riferimento
wsVAR.Esempio 2: Compattazione delle condizioni nei
Select CasePRIMA:
Select Case azione Case "ARROTONDA_1000" For Each cell In destRange If IsNumeric(cell.Value) And cell.Value > 1000 Then cell.Value = Application.WorksheetFunction.MRound(cell.Value, 1000) End If Next cell Case "ARROTONDA_4" For Each cell In destRange If IsNumeric(cell.Value) Then cell.Value = Application.WorksheetFunction.Round(cell.Value, 4) End If Next cell Case "ARROTONDA_100" For Each cell In destRange If IsNumeric(cell.Value) And cell.Value > 100 Then cell.Value = Application.WorksheetFunction.MRound(cell.Value, 100) End If Next cell Case "NESSUNA" ' Non eseguire alcuna operazione End SelectDOPO:
Select Case azione Case "ARROTONDA_1000", "ARROTONDA_100", "ARROTONDA_4" Dim roundFactor As Variant Dim minValue As Variant Select Case azione Case "ARROTONDA_1000" roundFactor = 1000 minValue = 1000 Case "ARROTONDA_100" roundFactor = 100 minValue = 100 Case "ARROTONDA_4" roundFactor = 4 minValue = 0 ' Nessun minimo End Select For Each cell In destRange If IsNumeric(cell.Value) Then If azione <> "ARROTONDA_4" Then If cell.Value > minValue Then cell.Value = Application.WorksheetFunction.MRound(cell.Value, roundFactor) End If Else cell.Value = Application.WorksheetFunction.Round(cell.Value, roundFactor) End If End If Next cell Case "NESSUNA" ' Non eseguire alcuna operazione End SelectMotivazione: Riduce la ripetizione del ciclo
For Eache centralizza la logica di arrotondamento.
4. Miglioramento dell’efficienza e della velocità di esecuzione
Osservazioni:
- Evitare l'uso di
Application.SelecteActivate: Migliora le prestazioni evitando operazioni non necessarie. - Utilizzare variabili oggetto per ridurre il numero di accessi alle celle.
- Ridurre la dimensione degli intervalli elaborati quando possibile.
Esempi Specifici:
Esempio 1: Eliminazione di
Selecte utilizzo diretto dei riferimentiPRIMA:
Sheets("Gen").Select Application.ScreenUpdating = TrueDOPO:
' Non è necessario selezionare il foglio per operazioni successive ' Assicurarsi che tutte le operazioni siano fatte tramite variabili oggetto Application.ScreenUpdating = TrueMotivazione: Evita di selezionare fogli inutilmente, riducendo il tempo di esecuzione.
Esempio 2: Utilizzo di array per elaborare i dati in blocco
PRIMA:
For j = 1 To .Range("F53:F60").Rows.Count On Error Resume Next .Range("O53:O60").Cells(j, 1).NumberFormat = .Range("F53:F60").Cells(j, 1).NumberFormat If err.Number <> 0 Then .Range("O53:O60").Cells(j, 1).NumberFormat = "General" err.Clear End If On Error GoTo 0 Next jDOPO:
Dim sourceFormats As Variant Dim destFormats As Variant Dim k As Long sourceFormats = .Range("F53:F60").NumberFormat ReDim destFormats(1 To UBound(sourceFormats, 1), 1 To 1) For k = 1 To UBound(sourceFormats, 1) destFormats(k, 1) = sourceFormats(k, 1) If destFormats(k, 1) = "" Then destFormats(k, 1) = "General" End If Next k .Range("O53:O60").NumberFormat = destFormatsMotivazione: Elabora i formati in blocco utilizzando array, riducendo il numero di interazioni con il foglio di lavoro.
Esempio 3: Conversione diretta dei valori senza
CopyePasteSpecialPRIMA:
Set myMultiAreaPrice = Union(wsOdierno.Range("A10:A49"), wsOdierno.Range("A51:A62"), wsOdierno.Range("A64:A81"), wsOdierno.Range("A84:A96"), wsOdierno.Range("A98:A111")) myMultiAreaPrice.Copy wsData.Range("A1").End(xlDown).Offset(1, 0).PasteSpecial Paste:=xlValues, Transpose:=TrueDOPO:
Dim combinedData As Variant Dim destCell As Range combinedData = Application.Transpose(wsOdierno.Range("A10:A49,A51:A62,A64:A81,A84:A96,A98:A111").Value) Set destCell = wsData.Range("A1").End(xlDown).Offset(1, 0) destCell.Resize(UBound(combinedData, 1), UBound(combinedData, 2)).Value = combinedDataMotivazione: Elimina l'uso di
CopyePasteSpecial, assegnando direttamente i valori all'intervallo di destinazione.
Conclusioni
Le modifiche proposte mirano a ridurre la ridondanza, ottimizzare e compattare il codice, nonché migliorare l'efficienza e la velocità di esecuzione. Implementando queste modifiche, il codice non solo diventa più leggibile e manutenibile, ma migliora anche le prestazioni complessive, specialmente su dataset di grandi dimensioni.
Suggerimenti Generali:
- Evita di utilizzare
SelecteActivatea meno che non siano strettamente necessari. - Utilizza variabili oggetto per riferimenti frequenti ai fogli di lavoro e agli intervalli.
- Approfitta delle capacità di array di VBA per elaborare dati in blocco.
- Usa blocchi
Withper ridurre la ripetizione di riferimenti agli oggetti.
Implementando queste best practice, si può ottenere un codice VBA più efficiente, veloce e facilmente manutenibile.
- Uso eccessivo di