Hay muchas formas de importar archivos de texto a la hoja actual. Aquí están tres (incluido el método que está utilizando anterior)
- El uso de un
- Abrir el archivo de texto QueryTable en la memoria y luego escribir en la hoja actual y, finalmente, la aplicación de Texto en columnas si es necesario.
- Si desea utilizar el método que está utilizando actualmente a continuación, después de abrir el archivo de texto en un nuevo libro, simplemente copiarlo en la hoja actual usando
Cells.Copy
El uso de un QueryTable
Aquí hay una macro simple que grabé. Por favor modifíquelo para satisfacer sus necesidades.
Sub Sample()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
)
.Name = "Sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Abrir el archivo de texto en la memoria
Sub Sample()
Dim MyData As String, strData() As String
Open "C:\Sample.txt" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
End Sub
Una vez que tenga los datos de la matriz puede exportarlo a la hoja actual.
Usando el método que ya está utilizando
Sub Sample()
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import
Set wbO = Workbooks.Open("C:\Sample.txt")
wbO.Sheets(1).Cells.Copy wsI.Cells
wbO.Close SaveChanges:=False
End Sub
FOLLOWUP
Puede utilizar el Application.GetOpenFilename
para elegir el archivo correspondiente. Por ejemplo ...
Sub Sample()
Dim Ret
Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")
If Ret <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=Range("$A$1"))
'~~> Rest of the code
End With
End If
End Sub
Parece que el método QueryTable es el más simple pero ¿hay alguna forma de agregarle un cuadro de diálogo, así que tendré la opción de elegir archivos de texto de diferentes fuentes? –
Sí. Un momento ... actualizando la publicación –
Actualizada la publicación :) Ver 'SEGUIMIENTO ' –