PDA

View Full Version : [excel vba] aggiungere fogli di lavoro


john_revelator
02-02-2008, 16:53
Ciao a tutti. La mia necessità è quella di aggiungere dei fogli ad un file di excel tramite vba. Dovrò creare un foglio per ciascuna tabella presente in un mio database access ma qui posto un codice semplificato giusto per rendere l'idea. Finchè importo i dati di sole 3 tabelle funziona bene. I problemi sorgono quando devo aggiungere i fogli.

Di seguito il mio codice semplificato al massimo:


Option Compare Database

Private Sub Comando0_Click()

Dim dbs As Database
Dim strSQL As String
Dim strQueryName As String
Dim qryDef As QueryDef
Dim xlApp As Excel.Application
Dim xlSheet As Excel.Worksheet
Dim xlWorkbook As Excel.Workbook
Dim objRST As Recordset


Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkbook = xlApp.Workbooks.Add

' Foglio 1 ****************************************************************
Set xlSheet = xlWorkbook.Sheets(1)
With xlSheet
.Range("A1").Value = "valore1"
End With
' Rinomino il foglio di lavoro di excel
xlSheet.Name = "Tabella_uno"

' Fine foglio 1 **************************************************************


'Foglio 4 *********************************************************************
Set xlSheet = Excel.Worksheets.Add(After:=Sheets(Sheets.Count))

'Altre prove fatte
'Set xlSheet = Worksheets.Add(After:=Sheets(Sheets.Count))
'Set xlSheet = Sheets.Add(After:=Sheets(Sheets.Count))

' ActiveSheet.Name = "Tabella_quattro"

With xlSheet
.Range("A1").Value = "valore4"
End With

' Rinomino il foglio di lavoro di excel
xlSheet.Name = "Tabella_quattro"
' Fine foglio 4 *************************************************************


' Libero le risorse
Set xlSheet = Nothing
Set xlWorkbook = Nothing
Set xlApp = Nothing

End Sub


La prima volta funziona ma se lo rieseguo ottengo un errore di runtime 1004 Metodo 'sheets' dell'oggetto '_global' non riuscito e a quanto vedo il foglio viene accodato al file precedentemente creato e non a quello attuale.

Come posso fare in modo che il codice funzioni sempre?
Grazie a tutti fin da ora. :)