Condividi:        

Problema macro EXCEL

Vuoi potenziare i tuoi documenti Word? Non sai come si fa una macro in Excel? Devi creare una presentazione in PowerPoint?
Oppure sei passato a OpenOffice e non sei sicuro di come lavorare al meglio?

Moderatori: Anthony47, Flash30005

Problema macro EXCEL

Postdi stevetriple » 01/04/14 11:09

Buongiorno a tutti!
Ho un problema con una macro EXCEL ed essendomi avvicinato da poco al programma vorrei una mano...

All'interno di una cartella ho N file ".txt", all'interno dei quali ho dei parametri. I file si chiamano "DISCO1.txt", "DISCO2.txt", "DISCO3.txt" ecc. Devo importare il contenuto di questi file, ognuno in un diverso foglio EXCEL appartenente allo stesso file.
Una volta importato il contenuto, la macro mi fa vedere il grafico corrispondente, quindi ogni foglio avrà il suo grafico.

Con la registrazione macro riesco a farlo, ma c'è un altro step: se nella mia cartella sparisce DISCO1 e si aggiunge DISCO4 la mia macro non deve più creare il foglio + grafico del DISCO1 ma del DISCO4 e così via... Questo non so proprio come farlo!

Spero di essere stato chiaro e spero possiate aiutarmi!

Grazie!
stevetriple
Utente Junior
 
Post: 17
Iscritto il: 01/04/14 10:32

Sponsor
 

Re: Problema macro EXCEL

Postdi ricky53 » 01/04/14 12:15

Ciao,
puoi allegare il codice che hai prodotto e che utilizzi
Dice il vecchio saggio provare e riprovare è l'unica strada per imparare

Più chiara è la vostra spiegazione
Più immediata sarà la nostra soluzione


. . . . . . . . . .
S.O. W10; Office 2003-10-13-16-19
Avatar utente
ricky53
Utente Senior
 
Post: 4565
Iscritto il: 11/04/09 19:29
Località: Italia

Re: Problema macro EXCEL

Postdi stevetriple » 01/04/14 12:24

Ciao, questo è il codice:

Codice: Seleziona tutto
Sub prova()
'
' prova Macro
'

'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Documents and Settings\...\Desktop\DISCA.txt", Destination:= _
        Range("$A$1"))
        .Name = "DISCA"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 850
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = True
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Range("A2:C8").Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.SetSourceData Source:=Range("Foglio1!$A$2:$C$8")
    ActiveChart.ChartType = xlAreaStacked100
    Sheets("Foglio2").Select
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Documents and Settings\cte0141\Desktop\DISCB.txt", Destination:= _
        Range("$A$1"))
        .Name = "DISCB"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 850
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = True
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Range("A2:C8").Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.SetSourceData Source:=Range("Foglio2!$A$2:$C$8")
    ActiveChart.ChartType = xlPie
    Sheets("Foglio3").Select
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Documents and Settings\cte0141\Desktop\DISCJ.txt", Destination:= _
        Range("$A$1"))
        .Name = "DISCJ"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 850
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = True
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Range("A2:C8").Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.SetSourceData Source:=Range("Foglio3!$A$2:$C$8")
    ActiveChart.ChartType = xlColumnClustered
    Sheets("Foglio1").Select
End Sub

Però non vede automaticamente i file all'interno della cartella, questa è semplicemente una registrazione macro di una cosa eseguita manualmente.
stevetriple
Utente Junior
 
Post: 17
Iscritto il: 01/04/14 10:32

Re: Problema macro EXCEL

Postdi Anthony47 » 01/04/14 19:06

Un "paio" di domande per capire...
Si sa oppure no quanti file .txt sono in quella directory?
I fogli sono tutti uguali o tutti diversi, a parte il contenuto che viene preso da file txt diversi?
Bisogna fare una associazione tipo Disco1.txt=Foglio1, per cui quando invece di Disco1 comparisse Disco4 bisogna creare un foglio nuovo (lasciando Foglio1 col contenuto di Disco1)? Oppure ogni Foglio puo' essere popolato dai dati di un Txt, basta che da qualche parte sia scritto chiaramente "questi dati provengono da xyz.txt"?

Ciao.
Avatar utente
Anthony47
Moderatore
 
Post: 19228
Iscritto il: 21/03/06 16:03
Località: Ivrea

Re: Problema macro EXCEL

Postdi Zer0Kelvin » 01/04/14 20:56

Ciao.
Il sistema più semplice è usare l'istruzione Dir per leggere i nomi dei files di testo ed utilizzzare una sub con parametri per creare i grafici
Codice: Seleziona tutto
Sub prova2(Sh As Worksheet, fPath As String, qName As String)
    With Sh.QueryTables.Add(Connection:="TEXT;" & fPath, Destination:=Sh.Range("A1"))
        .Name = qName
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 850
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = True
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
'    Range("A2:C8").Select
    Sh.Shapes.AddChart.Select
    ActiveChart.SetSourceData Source:=Range("Foglio1!$A$2:$C$8")
    ActiveChart.ChartType = xlAreaStacked100
End Sub
a cui passare: il foglio, il percorso completo del file ed il nome della connessione.
[Win7,Office2010]
Condividere la conoscenza aumenta la ricchezza di tutti(Z0°K)
Dai ad un uomo un pesce e lo avrai sfamato per un giorno;insegnagli a pescare e lo avrai sfamato per sempre(Confucio)
Il sonno della ragione genera mostri(Francisco Goya)
Avatar utente
Zer0Kelvin
Utente Senior
 
Post: 388
Iscritto il: 08/04/12 11:23

Re: Problema macro EXCEL

Postdi stevetriple » 02/04/14 09:18

Zer0Kelvin ha scritto:Ciao.
Il sistema più semplice è usare l'istruzione Dir per leggere i nomi dei files di testo ed utilizzzare una sub con parametri per creare i grafici a cui passare: il foglio, il percorso completo del file ed il nome della connessione.


Ciao, con un po' di aiuto ho creato questo codice, con il Dir:

Codice: Seleziona tutto
Sub ListFiles()

    'Declare the variables
    Dim strPath As String
    Dim strFile As String
    Dim nomeDisco As String
    Dim connessione As String
    Dim NextRow As Long
   
    'Specify the path to the folder
    strPath = "C:\Documents and Settings\cte0141\Desktop\dischi\"
   
    'Make sure that the path ends in backslash
    If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
   
    'Get the first file from the folder
    strFile = Dir(strPath & "*.*", vbNormal)
   
    'If no files were found, exit the sub
    If Len(strFile) = 0 Then
        MsgBox "No files were found...", vbExclamation
        Exit Sub
    End If
   
    'Loop through each file in the folder
    Do While Len(strFile) > 0
        connessione = "TEXT;" & strPath & strFile
'MsgBox connessione
        nomeDisco = UCase(Left(strFile, InStr(1, strFile, ".", vbTextCompare) - 1))
       
        Sheets(Sheets.Count).Select
        Sheets(Sheets.Count).Name = nomeDisco
       
        'List the name, size, and date/time of the current file
        With ActiveSheet.QueryTables.Add(Connection:=connessione, Destination:=Range("$A$1"))
            .Name = nomeDisco
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 850
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = True
            .TextFileTabDelimiter = True
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = True
            .TextFileColumnDataTypes = Array(1, 1, 1)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
        End With
        Range("A2:C8").Select
        ActiveSheet.Shapes.AddChart.Select
        'ActiveChart.SetSourceData Source:=Range(nomeDisco & "!$A$2:$C$8")
        ActiveChart.SetSourceData Source:=Range("$A$2:$C$8")
        ActiveChart.ChartType = xlAreaStacked100
       
        'Get the next file from the folder
        strFile = Dir
       
        'aggiungi un foglio
        If Len(strFile) > 0 Then
            Sheets.Add After:=Sheets(Sheets.Count)
            Sheets(Sheets.Count).Activate
        End If
   
    Loop
   
    'Change the width of the columns to achieve the best fit
    Columns.AutoFit
   
    'Turn screen updating back on
    Application.ScreenUpdating = True
       
End Sub


Era quello che volevo, grazie per le dritte, si può chiudere ;)
stevetriple
Utente Junior
 
Post: 17
Iscritto il: 01/04/14 10:32


Torna a Applicazioni Office Windows


Topic correlati a "Problema macro EXCEL":


Chi c’è in linea

Visitano il forum: Nessuno e 67 ospiti