VBA 将选定的列从 csv 文件导入到 excel 作为文本格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19066327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:32:50  来源:igfitidea点击:

VBA to import selected columns from csv file to excel as text format

excelvbacsvimportfilesystemobject

提问by user2826139

I have following VBA code to import selected columns from a csv file to excel. The selected columns should be imported as text. For Ex: 000001 should be imported as it is.it should not truncate the leading 0's. I wrote a VBA using file System object to select entire file. But, it is selecting only first 2.

我有以下 VBA 代码将选定的列从 csv 文件导入到 excel。所选列应作为文本导入。例如: 000001 应按原样导入。它不应截断前导 0。我使用文件系统对象编写了一个 VBA 来选择整个文件。但是,它只选择前 2 个。

My requirement: 1. Selecting only certain columns 2. All should be imported as text

我的要求: 1. 仅选择某些列 2. 所有应作为文本导入

My Code:

我的代码:

Sub Read_Text_File()
Dim fsoObj As Scripting.FileSystemObject
Dim fsoFile As Scripting.File
Dim fsoTS As Scripting.TextStream
Dim vaData As Variant
Dim i As Long, j As Long

Set fsoObj = New Scripting.FileSystemObject
Set fsoFile = fsoObj.GetFile("C:\Users\Sandeep\Downloads\TestFile.csv")
Set fsoTS = fsoFile.OpenAsTextStream(ForReading, TristateFalse)


j = 1
Do Until fsoTS.AtEndOfStream
vaData = Split(fsoTS.ReadLine, Chr(44))
Range(Cells(j, 1), Cells(j, 2)).Value = vaData
j = j + 1
Loop

fsoTS.Close
Set fsoFile = Nothing
Set fsoObj = Nothing
End Sub

回答by Teeracroptus

I'm currently mobile, so I cannot provide any example code, but you can automate excel to open the .csv file, format all cells as text and use excel's own ability to split the lines into columns. Finally, you can delete unwanted columns or process only the columns that you want. I suggest that you carry out the above steps manually, recording a macro. Then you can edit the generated code as you desire. If you need more information, please tell me so I can post some code once I have access to vba de.

我目前正在移动,所以我无法提供任何示例代码,但您可以自动使用 excel 打开 .csv 文件,将所有单元格格式化为文本,并使用 excel 自己的功能将行拆分为列。最后,您可以删除不需要的列或仅处理您想要的列。我建议你手动执行上述步骤,录制一个宏。然后您可以根据需要编辑生成的代码。如果您需要更多信息,请告诉我,以便我可以在可以访问 vba de 后发布一些代码。