Hay muchas maneras de obtener datos en Excel. Querytables (como lo demuestra The_Barman), SQL, Asistente de importación, etc.
Por lo general, el método depende de cuán limpia se presentan los datos en los archivos que necesita importar y si sabe exactamente cómo está distribuido. Por ejemplo, si hay filas vacías, tipos de datos mixtos, celdas combinadas, etc., puede ser una pesadilla.
A continuación se muestra un método de "fuerza bruta" más lento que generalmente obtendrá todos los datos al abrir primero el archivo en Excel. A menudo es lo último que se puede hacer cuando otros métodos fallan.
Option Explicit
Public Sub ImportData()
Dim CSVFilename As String
Dim writeToFilename As String
Dim writeToSheet As String
Dim readXL As Workbook
Dim readWS As Worksheet
Dim writeXL As Workbook
Dim writeWS As Worksheet
Dim UsedRng As Range
CSVFilename = Environ$("USERPROFILE") & "\Desktop" & "\SO2PO.csv"
writeToFilename = Environ$("USERPROFILE") & "\Desktop" & "\Open Order.xlsx"
writeToSheet = "PO Data"
Set writeXL = GetObject(writeToFilename)
Set writeWS = writeXL.Sheets(writeToSheet)
'writeWS.Parent.Windows(1).Visible = True
Set readXL = GetObject(CSVFilename)
With readXL
Set readWS = readXL.Sheets(1)
Set UsedRng = RealUsedRange(readWS)
writeWS.Range(UsedRng.Address).Value = UsedRng.Value
End With
'close CSV without saving
readXL.Close SaveChanges:=False
Set readWS = Nothing
Set readXL = Nothing
'close template with save
writeXL.Close SaveChanges:=True
Set writeWS = Nothing
Set writeXL = Nothing
End Sub
Public Function RealUsedRange(ByVal WS As Worksheet) As Range
'Find used range
Dim FirstRow As Long
Dim LastRow As Long
Dim FirstColumn As Integer
Dim LastColumn As Integer
On Error Resume Next
With WS
FirstRow = .Cells.Find(What:="*", After:=.Cells(.Rows.Count, .Columns.Count), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext).Row
FirstColumn = .Cells.Find(What:="*", After:=.Cells(.Rows.Count, .Columns.Count), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column
LastRow = .Cells.Find(What:="*", After:=.Range("A1"), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastColumn = .Cells.Find(What:="*", After:=.Range("A1"), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Set RealUsedRange = .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn))
End With
On Error GoTo 0
End Function
odio decir esto, pero me dijo específicamente que intento esto en una hoja de Excel ... que pensé que, además de las etiquetas, Excel y Excel VBA habría indicios de que Excel es la aplicación que estaba usando y que Excel-VBA era una posibilidad ... de una solución. Si iba a hacer esto usando otra aplicación, probablemente hubiera dicho ... –
Sí, era evidente que Excel era la aplicación. No era evidente el mecanismo * externo * que desea utilizar, ya sea que haya incluido la escritura de una aplicación separada e independiente en algo como C# o VB.Net, o quizás como parte de una aplicación más grande que utiliza SQL Server. Tu conoces tu sistema Nosotros no. Realmente disfruto ayudando aquí, pero las respuestas como esta cuando intento brindar la ayuda no son muy alentadoras. Buena suerte con tu proyecto. –
Si iba a haber C# y VB.Net, lo pondría en las etiquetas ... Soy bastante literal cuando pido cosas. –