在这个论坛的帮助下已经能够解决大部分问题,但这让我陷入困境。
我有一个逗号分隔的csv
文件(“xxxx”,“zzz”),该文件隐藏了chr(10)
和chr(13)
。如果我使用脚本替换这两个字符,我将丢失记录chr(10)
的结尾,因此只导入一条记录。
在记事本中,文件显示完美 - 每行一条记录。如果我打开一个excel文件就可以,只有当我导入为csv分隔文件时
感谢其他贡献者,以下是我一直在使用的内容。
理想情况下,我想做的是:
-
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
非常感谢任何帮助。
答案 0 :(得分:1)
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