简体   繁体   English

使用VBA将具有隐藏字符的CSV文件导入Excel

[英]Importing csv file with hidden characters into Excel using vba

With the help of this forum have been able to solve most problem but this has me stuck. 在这个论坛的帮助下,已经能够解决大多数问题,但这使我陷于困境。

I have a comma delimited csv file ("xxxx","zzz",) that has hidden chr(10) and chr(13) in the file. 我有一个逗号分隔的csv文件(“ xxxx”,“ zzz”),该文件中隐藏了chr(10)chr(13) If I use a script to replace both these characters, I lose the end of record chr(10) so only imports as one record. 如果使用脚本替换这两个字符, chr(10)丢失记录chr(10)的结尾,因此只能导入为一条记录。

In notepad the file shows perfect - one record per line. 在记事本中,文件显示完美-每行一条记录。 If I open as a an excel file it is ok, its only when I import as a csv delimited file 如果我将其打开为excel文件就可以了,只有当我将其导入为csv分隔文件时才可以

With thanks to other contributors, below is what I have been using. 感谢其他贡献者,以下是我一直在使用的内容。

Ideally what I would like to do is: 理想情况下,我想做的是:

  1. select the csv file 选择csv文件
  2. copy the file to keep the original <<< extra function 复制文件以保留原始<<<额外功能
  3. clean up all hidden characters that would affect the import 清理所有可能影响导入的隐藏字符
  4. then import 然后导入

- -

Private Sub CSV_ImportRepl()
    Dim strFile As String
    Dim strBuffer As String
    Dim ff As Integer
    Dim strFileName As String
    Dim ws As Worksheet

    'ENTRIES CSV FILE ----------------------------------
    ' ---open file ----------
    strFile = Application.GetOpenFilename("Text Files (*.csv),*.*", _
    , "SELECT ENTRIES csv FILE")
    strFileName = strFile
    MsgBox strFileName

    ' ---start cleaning file ----------
    strBuffer = Space(FileLen(strFile))
    ff = FreeFile
    Open strFile For Binary Access Read As #ff
    Get #ff, , strBuffer
    Close #ff

    strBuffer = Replace(strBuffer, Chr(13), "")
    Kill strFile

    Open strFile For Binary Access Write As #ff
    Put #ff, , strBuffer
    Close #ff

    ' --- clear contents & import  ----------
    Sheets("Entries").Cells.ClearContents
    Set ws = ActiveWorkbook.Sheets("Entries") 'set to current worksheet name
    strFile = strFileName

    With ws.QueryTables.Add(Connection:="TEXT;" & strFile, _
    Destination:=ws.Range("A1"))
         .TextFileParseType = xlDelimited
         .TextFileCommaDelimiter = True
         .Refresh
    End With
End Sub

Any help would be most appreciated. 非常感激任何的帮助。

Sub opencsv()

    strFile = Application.GetOpenFilename("Text Files (*.csv),*.*", , "Please selec text file...")
    strFileName = strFile

    Set src = Workbooks.Open(Filename:=strFile, Local:=True)
    Cells.Copy
    ThisWorkbook.Activate
    Sheets("Entries").Activate
    Range("A1").Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
    src.Close

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM