Anthony47 ha scritto:Chi vuole approfondire puo' fare una ricerca su google con la stringa "import data from a closed workbook using ado" oppure "import data from a closed workbook using dao".
Beh non mi son lasciato scappare l'occasione e ho provato...
- Codice: Seleziona tutto
Sub prova()
GetDataFromClosedWorkbook "C:\Pippo.xls", "A1:B21", ActiveCell, False
GetDataFromClosedWorkbook "C:\Pippo.xls", "MyDataRange", Range("B3"), True
End Sub
Sub GetDataFromClosedWorkbook(SourceFile As String, SourceRange As String, _
TargetRange As Range, IncludeFieldNames As Boolean)
Dim dbConnection As ADODB.Connection, rs As ADODB.Recordset
Dim dbConnectionString As String
Dim TargetCell As Range, i As Integer
dbConnectionString = "DRIVER={Microsoft Excel Driver (*.xls)};" & _
"ReadOnly=1;DBQ=" & SourceFile
Set dbConnection = New ADODB.Connection
On Error GoTo InvalidInput
dbConnection.Open dbConnectionString ' open the database connection
Set rs = dbConnection.Execute("[" & SourceRange & "]")
Set TargetCell = TargetRange.Cells(1, 1)
If IncludeFieldNames Then
For i = 0 To rs.Fields.Count - 1
TargetCell.Offset(0, i).Formula = rs.Fields(i).Name
Next i
Set TargetCell = TargetCell.Offset(1, 0)
End If
TargetCell.CopyFromRecordset rs
rs.Close
dbConnection.Close ' close the database connection
Set TargetCell = Nothing
Set rs = Nothing
Set dbConnection = Nothing
On Error GoTo 0
Exit Sub
InvalidInput:
MsgBox "The source file or source range is invalid!", _
vbExclamation, "Get data from closed workbook"
End Sub
Effettivamente si copiano i dati senza aprire il foglio ma...
le celle non corrispondo a quelle impostate (devo dire che ho fatto tutto con molta fretta, tanto era la curiosità)
Ciao