Creare nuovo file excel estraendo i dati da altri file excel

Anonimo
2014-12-04T23:55:26+00:00

Ciao,

premetto che non conosco praticamente nulla di VBA.

Nel corso degli anni ho creato innumerevoli file Excel strutturati nel medesimo modo.

Ogni file è composto da diversi fogli, tutti uguali nella struttura tranne i fogli Pippo e Pluto (che sono diversi nella struttura e non ho necessità di prendere in considerazione).

Ogni foglio è strutturato in modo identico all'altro.

Il nome di questi fogli è composto da strighe che (ahimè) contengono anche punti (.) e parentesi e segni +-

Ora vorrei estrarre tutti i dati da questi fogli e riepilogarli in un unico foglio.

Esempio di un file

cartellann.xls

foglio23.5                 voglio prendere il contenuto della cella E8,E9,E10............

foglio2Ø3.5ES44      voglio prendere il contenuto della cella E8,E9,E10...........

foglio23.5+23(3)      voglio prendere il contenuto della cella E8,E9,E10............

pippo                       non voglio considerare

pluto                        non voglio considerare

vorrei creare una nuova cartella suppergiù così.

cartellann.xls             foglio23.5                contenuto cella E8                contenuto cella E9              contenuto cella E10 ................

cartellann.xls            foglio2Ø3.5ES44      contenuto cella E8                contenuto cella E9              contenuto cella E10 ................

cartellann.xls            foglio23.5+23(3)      contenuto cella E8                contenuto cella E9              contenuto cella E10 ................

cartellannnnnn.xls    così via.....

Come posso fare?

Microsoft 365 e Office | Excel | Per la casa | Windows

Domanda bloccata. Questa domanda è stata eseguita dalla community del supporto tecnico Microsoft. È possibile votare se è utile, ma non è possibile aggiungere commenti o risposte o seguire la domanda.

0 commenti Nessun commento
Risposta accettata dall'autore della domanda
Anonimo
2014-12-16T11:35:30+00:00

Ciao Red Mud,

     Const sAddress = "F2,K2,C4,H4,C6,H6,E8,I7,I8,J8,L8," _

          & "E9,I9,E10,E11,E12,E13,I14,J15,E16,J17,J18," _

    & "B21,E21,H21,J21,O21,B22,E22,H22,J22,O22," _

& "B23,E23,H23,J23,O23,B24,E24,H24,J24,O24," _

& "B25,E25,H25,J25,O25,B26,E26,H26,J26,O26,B28,J28,I30," _

& "L30,L32,D36,F36,I36,D37,F37,I37,D38,F38,I38," _

& "P15,P16,P17,P18"                     '<<==== Modifica

Credo che il tuo problema sia dovuto alla lunghezza della stringa sAddress e il numero di caratteri linebreak (_).

Pertanto, prova invece:

      Const sAddress As String = "F2,K2,C4,H4,C6,H6,J8,L8,I7:I9," _

& "E8:E13,I14,J15,E16,J17:J18,B21:B26,E21:E26," _

& "H21:H26,J21:J26,O21:O26,B28,J28,I30,L30,L32," _

& "D36:D38,F36:F38,I36:I38,P15:P18"                                

===

Regards,

Norman

La risposta è stata utile?

0 commenti Nessun commento

36 risposte aggiuntive

Ordina per: Più recente
  1. Anonimo
    2014-12-15T10:52:29+00:00

    Ciao Red Mud,

    Avrei dovuto anche spiegare il mio uso dell'istruzione Attributes:

                    If UCase(oFile.Name) Like UCase("thumbs.db") Then

                        With oFile

    .Attributes = 0

                            Kill oFile

                        End With

                    Else

    Perché tu non eri in grado di vedere o eliminare il file problematico thumbs.db, è probabile che questo file è un file nascosto. Al fine di rendere il file visible e di eliminarlo, ho usato l'istruzione Attributes per convertire gli attributi del file a normale, che è un valore pari a 0. A questo proposito vedi il seguente file help VBScript:

    '--------->>

    Attributes Attributes Property  [VBScript]

    Sets or returns the attributesof files or folders. Read/write or read-only, depending on the attribute.

    object.Attributes [= newattributes]

    Arguments

    • object
      • Required. Always the name of a File or Folder object.
    • newattributes
      • Optional. If provided, newattributes is the new value for the attributes of the specified object.

    Settings

    The newattributes argument can have any of the following values or any logical combination of the following values:

    Constant Value Description
    Normal 0 Normal file. No attributes are set.
    ReadOnly 1 Read-only file. Attribute is read/write.
    Hidden 2 Hidden file. Attribute is read/write.
    System 4 System file. Attribute is read/write.
    Volume 8 Disk drive volume label. Attribute is read-only.
    Directory 16 Folder or directory. Attribute is read-only.
    Archive 32 File has changed since last backup. Attribute is read/write.
    Alias 64 Link or shortcut. Attribute is read-only.
    Compressed 128 Compressed file. Attribute is read-only.

    Remarks

    The following code illustrates the use of the Attributes property with a file:

    [VBScript]
    

    Function ToggleArchiveBit(filespec)

       Dim fso, f

       Set fso = CreateObject("Scripting.FileSystemObject")

       Set f = fso.GetFile(filespec)

       If f.attributes and 32 Then

          f.attributes = f.attributes - 32

          ToggleArchiveBit = "Archive bit is cleared."

       Else

          f.attributes = f.attributes + 32

          ToggleArchiveBit = "Archive bit is set."

       End If

    End Function

    '<<---------

    ===

    Regards,

    Norman

    La risposta è stata utile?

    0 commenti Nessun commento
  2. Anonimo
    2014-12-15T10:22:32+00:00

    Ciao Red Mud,

    Ho lanciato questo codice e ha fatto l'analisi di tutte le cartelle.

    Tutto regolare!

    Bene!

    Ha elencato 61 volte un file presente nelle stessa cartella (la prima dell'estrazione).

    Il file è sempre il solito...elencato 61 volte....thumbs.db

    Questo mi sorprende molto, in quanto l'istruzione

    If oFile.Name Like "*.xls*" Then

    dovrebbe assicurarsi che solo i file con un'estensione che comprende .xls siano elaborati sul primo foglio riepilogativo. Sei sicuro che in realtà il file  thumbs.db non sia elencato sul secondo foglio ripielogativo AltriFile? Ho creato quest'ultimo foglio al fine di elencare tutti i file di tipo non Excel. A questo proposito, le istruzioni  rilevanti sono:

    If oFile.Name Like "*.xls*" Then

                 

    [CUT]

    Else

    i = i + 1

    ReDim Preserve arrAltriFile(1 To i)

    arrAltriFile(i) = oFile.Path

    End If 

    Se il file thumbs.db è stato elencato 61 volte sul foglio  AltriFile, questo suggerirebbe che questo file esiste in 61 sottodirectory.

    TI invio il file in pvt.

    Purtroppo, questo non è utile: sarebbe invece necessario inviare una copia di tutte le 61 sottodirectory e anche i piu' di 1100 file! Ti prego di non farlo!

    Come posso eliminarlo definitivamente?

    Non lo vedo, nella directory.

    Non sono riuscito ad eliminarlo nemmeno con cmd.exe.

    Al fine anche  di eliminare ogni istanza di un file nominato  thumbs.db  in qualsiasi delle sottodirectory di interesse, prova la seguente versione del codice:

    '=========>>

    Option Explicit

    '--------->>

    Public Sub Tester()

        Dim FSO As Object

        Dim oFile As Object

        Dim oFiles As Object

        Dim oFolder As Object

        Dim oSubFolder As Object

        Dim srcWB As Workbook, destWB As Workbook

        Dim srcSH As Worksheet, destSH As Worksheet, aSH As Worksheet

        Dim Rng As Range, rCell As Range

        Dim arrExclude As Variant, arrHeaders As Variant

        Dim arrAltriFile() As Variant

        Dim iRow As Long

        Dim i As Long, j As Long, k As Long

        Dim myFile As String, myFolder As String

        Dim Res As Variant

        Dim dDate As Date

        Dim sPrompt As String, iButtons As Long, sTitle As String

        Const sAddress = "F2,K2,C4,H4,C6,H6,E8,I7,I8,J8,L8," _

              & "E9,I9,E10,E11,E12,E13,I14,J15,E16,J17,J18"                                           '<<==== Modifica

        Const sFolder As String = "X:\SCHEDE PREZZO"

        Const sHeaders As String = "CARTELLA ORIGINE,FILE ORIGINE," _

              & "ULTIMA MODIFICA,FOGLIO DI ORIGINE,CLIENTE,DATA," _

              & "DESCRIZIONE,CODICE,DIMENSIONE,REVISIONE DISEGNO," _

              & "PESO BARRA,BARRA EXT,MISURA EXT,BARRA INT,MISURA INT," _

              & "LUNGH SPEZZ,MATERIALE,BASE METALLO,EXTRA MISURA," _

              & "TOTALE METALLO,VALORE SFRIDO,PESO OCCORRENTE," _

              & "COSTO MATERIALE,PESO FINITO,RECUPERO SFRIDO," _

              & "COSTO MATERIA PRIMA"                                                                   '<<==== Modifica

        Set destWB = ThisWorkbook

        Set destSH = destWB.Sheets(1)

        iRow = 1

        arrExclude = VBA.Array("Calcolo peso", "Forme")

        arrHeaders = Split(sHeaders, ",")

        With destSH.Range("A1").Resize(1, UBound(arrHeaders) + 1)

            .Value = arrHeaders

            .Font.Bold = True

            .Font.Underline = True

        End With

        On Error GoTo XIT

        Application.ScreenUpdating = False

        Set FSO = CreateObject("Scripting.FileSystemObject")

        Set oFolder = FSO.GetFolder(sFolder)

        For Each oSubFolder In oFolder.SubFolders

            Set oFiles = oSubFolder.Files

            For Each oFile In oFiles

                If oFile.Name Like "*.xls*" Then

                    dDate = oFile.DateLastModified

                    Application.StatusBar = "Processing il file " & oFile.Path

                    Set srcWB = Workbooks.Open(oFile)

                    With srcWB

                        For Each srcSH In .Worksheets

                            With srcSH

                                j = 1

                                Res = Application.Match(.Name, arrExclude, 0)

                                If IsError(Res) Then

                                    iRow = iRow + 1

                                    With destSH

                                        .Cells(iRow, "A").Value = oSubFolder.Path

                                        .Cells(iRow, "B").Value = oFile.Path

                                        .Cells(iRow, "C").Value = dDate

                                        .Cells(iRow, "D").Value = srcSH.Name

                                        Set Rng = srcSH.Range(sAddress)

                                        For Each rCell In Rng.Cells

                                            j = j + 1

                                            .Cells(iRow, j + 3).Value = rCell.Value

                                        Next rCell

                                    End With

                                End If

                            End With

                        Next srcSH

                        .Close savechanges:=False

                    End With

                Else

                    If UCase(oFile.Name) Like UCase("thumbs.db") Then

    With oFile

    .Attributes = 0

    Kill oFile

    End With

    Else

                        i = i + 1

                        ReDim Preserve arrAltriFile(1 To i)

                        arrAltriFile(i) = oFile.Path

                    End If

                End If

            Next oFile

        Next oSubFolder

        destSH.UsedRange.EntireColumn.AutoFit

        If CBool(i) Then

            With destWB

      On Error Resume Next

    Set aSH = .Sheets("AltriFile")

    On Error GoTo XIT

      If Not aSH Is Nothing Then

    aSH.Cells.ClearContents

    Else

                    Set aSH = .Sheets.Add(after:=.Sheets(1))

          End If

            End With

            With aSH

                .Name = "AltriFile"

                .Range("A2").Resize(i).Value = arrAltriFile

            End With

        End If

    XIT:

        With Application

            .ScreenUpdating = True

            .StatusBar = False

        End With

        If Err.Number = 0 Then

            sPrompt = "La procedura è stata completata senza alcun problema"

            iButtons = 64

            sTitle = "Finito"

        Else

            sPrompt = "Errore " _

                      & Err.Number _

                      & " (" _

                      & Err.Description _

                      & ") nella routine: Tester"

            iButtons = 16

            sTitle = "ERRORE"

        End If

        Call MsgBox(sPrompt, iButtons, sTitle)

    End Sub

    '<<=========

    Prima di eseguire questo codice, verifica che i file  thumbs.db non sono necessari o importanti! In caso di dubbio, crea una copia di backup!

    Nel codice precedente, le nuove istruzioni sono evidenziate in grassetto.

    ===

    Regards,

    Norman

    La risposta è stata utile?

    0 commenti Nessun commento
  3. Anonimo
    2014-12-15T08:24:56+00:00

    Ciao Norman.

    Grazie!

    Ho lanciato questo codice e ha fatto l'analisi di tutte le cartelle.

    Tutto regolare!

    Ha elencato 61 volte un file presente nelle stessa cartella (la prima dell'estrazione).

    Il file è sempre il solito...elencato 61 volte....thumbs.db

    TI invio il file in pvt.

    Come posso eliminarlo definitivamente?

    Non lo vedo, nella directory.

    Non sono riuscito ad eliminarlo nemmeno con cmd.exe.

    Saluti.

    Red Mud

    La risposta è stata utile?

    0 commenti Nessun commento
  4. Anonimo
    2014-12-12T11:49:00+00:00

    Ciao  Red Mud,

     Risposta

    ? oFile.Path

    X:\Schede prezzo\Adam Pumps\Thumbs.db

    Ma io questo file non lo vedo nella cartella quindi non riesco ad aprirlo.

    Perché?

    Ecco il problema! Nella directory ci sono anche file di tipo non Excel ...

    Per superare questo problema e anche individure tali altri file, prova la seguente versione del codice:

    '=========>>

    Option Explicit

    '--------->>

    Public Sub Tester()

        Dim FSO As Object

        Dim oFile As Object

        Dim oFiles As Object

        Dim oFolder As Object

        Dim oSubFolder As Object

        Dim srcWB As Workbook, destWB As Workbook

        Dim srcSH As Worksheet, destSH As Worksheet, aSH As Worksheet

        Dim Rng As Range, rCell As Range

        Dim arrExclude As Variant, arrHeaders As Variant

        Dim arrAltriFile() As Variant

        Dim iRow As Long

        Dim i As Long, j As Long, k As Long

        Dim myFile As String, myFolder As String

        Dim Res As Variant

        Dim dDate As Date

        Dim sPrompt As String, iButtons As Long, sTitle As String

        Const sAddress = "F2,K2,C4,H4,C6,H6,E8,I7,I8,J8,L8," _

    & "E9,I9,E10,E11,E12,E13,I14,J15,E16,J17,J18"                                     '<<==== Modifica

        Const sFolder As String = "**X:\SCHEDE PREZZO**"                                          '<<==== Modifica

        Const sHeaders As String = "CARTELLA ORIGINE,FILE ORIGINE," _

    & "ULTIMA MODIFICA,FOGLIO DI ORIGINE,CLIENTE,DATA," _

    & "DESCRIZIONE,CODICE,DIMENSIONE,REVISIONE DISEGNO," _

    & "PESO BARRA,BARRA EXT,MISURA EXT,BARRA INT,MISURA INT," _

    & "LUNGH SPEZZ,MATERIALE,BASE METALLO,EXTRA MISURA," _

    & "TOTALE METALLO,VALORE SFRIDO,PESO OCCORRENTE," _

    & "COSTO MATERIALE,PESO FINITO,RECUPERO SFRIDO," _

    & "COSTO MATERIA PRIMA"                                                                    '<<==== Modifica

        Set destWB = ThisWorkbook

        Set destSH = destWB.Sheets(1)

        iRow = 1

        arrExclude = VBA.Array("Calcolo peso", "Forme")                                       '<<==== Modifica

        arrHeaders = Split(sHeaders, ",")

        With destSH.Range("A1").Resize(1, UBound(arrHeaders) + 1)

            .Value = arrHeaders

            .Font.Bold = True

            .Font.Underline = True

        End With

        On Error GoTo XIT

        Application.ScreenUpdating = False

        Set FSO = CreateObject("Scripting.FileSystemObject")

        Set oFolder = FSO.GetFolder(sFolder)

        For Each oSubFolder In oFolder.SubFolders

            Set oFiles = oSubFolder.Files

            For Each oFile In oFiles

    If oFile.Name Like "*.xls*" Then

                    dDate = oFile.DateLastModified

                    Application.StatusBar = "Processing il file " & oFile.Path

                    Set srcWB = Workbooks.Open(oFile)

                    With srcWB

                        For Each srcSH In .Worksheets

                            With srcSH

                                j = 1

                                Res = Application.Match(.Name, arrExclude, 0)

                                If IsError(Res) Then

                                    iRow = iRow + 1

                                    With destSH

                                        .Cells(iRow, "A").Value = oSubFolder.Path

                                        .Cells(iRow, "B").Value = oFile.Path

                                        .Cells(iRow, "C").Value = dDate

                                        .Cells(iRow, "D").Value = srcSH.Name

                                        Set Rng = srcSH.Range(sAddress)

                                        For Each rCell In Rng.Cells

                                            j = j + 1

                                            .Cells(iRow, j + 3).Value = rCell.Value

                                        Next rCell

                                    End With

                                End If

                            End With

                        Next srcSH

                        .Close savechanges:=False

                    End With

    Else

    i = i + 1

    ReDim Preserve arrAltriFile(1 To i)

    arrAltriFile(i) = oFile.Path

    End If

            Next oFile

        Next oSubFolder

        destSH.UsedRange.EntireColumn.AutoFit

    If CBool(i) Then

    With destWB

    Set aSH = .Sheets.Add(after:=.Sheets(1))

    End With

    With aSH

    .Name = "AltriFile"

    .Range("A2").Resize(i).Value = arrAltriFile

    End With

    End If

    XIT:

        With Application

            .ScreenUpdating = True

            .StatusBar = False

        End With

        If Err.Number = 0 Then

            sPrompt = "La procedura è stata completata senza alcun problema"

            iButtons = 64

            sTitle = "Finito"

        Else

            sPrompt = "Errore " _

                      & Err.Number _

                      & " (" _

                      & Err.Description _

                      & ") nella routine: Tester"

            iButtons = 16

            sTitle = "ERRORE"

        End If

        Call MsgBox(sPrompt, iButtons, sTitle)

    End Sub

    '<<=========

    Con questa versione del codice, un nuovo foglio (denominato AltriFile) verra' creato e tutti i file di tipo non-Excel saranno elencati nella colonna A su quel foglio.

    I significativi cambiamenti nel corpo del codice sono evidenziate in grassetto.

    ===

    Regards,

    Norman

    La risposta è stata utile?

    0 commenti Nessun commento