Copying lines from Wordpad into Excel using VBA

我只是一个虾纸丫 提交于 2019-12-12 02:56:13

问题


I am writing some code where I import some files under TMX (a form of xml). I tried various options

a) using the Open FileName For input, but this messes up the character encoding

b) opening the file and copying the data using the msoDialog, but this return an error if the file is too large (which is often the case) and this put the data in an utterly messy manner.

c) opening the file using notepad, but there are the same limitations in so far as copying the entirety of the file into Excel as the previous option. I am not trying to use a shell function calling onto Wordpad.

My issue right now, is that I need to copy the file line by line to treat its content according to my needs (hopefully without losing the character encoding

Would someone know how to copy every single line from the file opened in WordPad and paste it post treatment (selection of the relevant elements) into Excel?

Thank you


回答1:


For large files you can use this solution:

Public Sub ImportTMXtoExcel()

Call Application.FileDialog(msoFileDialogOpen).Filters.Clear
Call Application.FileDialog(msoFileDialogOpen).Filters.Add("TMX Files", "*.tmx")
Application.FileDialog(msoFileDialogOpen).Title = "Select a file to import..."
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
    strFileToImport = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
    Exit Sub
End If

intPointer = FreeFile()
Open strFileToImport For Input Access Read Lock Read As #intPointer

intCounter = 0
Do Until EOF(intPointer)
    Line Input #intPointer, strLine
    intCounter = intCounter + 1
    Worksheets(1).Cells(intCounter + 1, 1).Value2 = strLine
Loop

Close intPointer

End Sub

For other encodings you can use ADO's Stream as described in this solution: VB6/VBScript change file encoding to ansi

If you have large files which require ADO's Stream then you might want to consider breaking down the large files first as described in this solution: How to split a large text file into smaller files with equal number of lines?

The following website provides a tool which mimics the Unix command split for Windows in command prompt: https://www.fourmilab.ch/splits/



来源:https://stackoverflow.com/questions/30564147/copying-lines-from-wordpad-into-excel-using-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!