excel - 导入文本文件内容和文本文件名称,然后使用宏分隔到 Excel
问题描述
由于使用宏将文本文件内容和文本文件名称导入 Excel,我有此代码
Option Explicit
Sub Import_video_txt_files()
' ADD REFERENCE TO MICROSOFT FILE SYSTEM OBJECT
Dim objFSO As FileSystemObject
Dim objFolder As folder
Dim objFile As file
Dim objTextStream As TextStream
Dim strPath As String
Dim i As Long
' Specify the folder...
strPath = "C:\Users\User\Desktop\TEST\"
' Use Microsoft Scripting runtime.
Set objFSO = New FileSystemObject
Set objFolder = objFSO.GetFolder(strPath)
' Check extension of each file in folder.
For Each objFile In objFolder.Files
If objFSO.GetExtensionName(objFile.Name) = "txt" Then
Cells(i + 2, 1) = objFile.Name
Set objTextStream = objFile.OpenAsTextStream(ForReading)
Cells(i + 2, 2) = objTextStream.ReadAll
i = i + 1
End If
Next
End Sub
但是现在我需要扩展功能。
文本文件在一行中包含所有信息。
例如:灰色、红色、蓝色|408.95|14165.849841859
我正在使用这个分隔符|
我希望能够从文本文件中导入所有信息并使用|将它们分开。并将它们放入相应的单元格中,如下图所示。
解决方案
尝试,
Sub Import_video_txt_files()
' ADD REFERENCE TO MICROSOFT FILE SYSTEM OBJECT
Dim objFSO As FileSystemObject
Dim objFolder As folder
Dim objFile As file
Dim objTextStream As TextStream
Dim strPath As String
Dim i As Long
Dim s As String, vSplit
' Specify the folder...
strPath = "C:\Users\User\Desktop\TEST\"
' Use Microsoft Scripting runtime.
Set objFSO = New FileSystemObject
Set objFolder = objFSO.GetFolder(strPath)
' Check extension of each file in folder.
For Each objFile In objFolder.Files
If objFSO.GetExtensionName(objFile.Name) = "txt" Then
Cells(i + 2, 1) = objFile.Name
Set objTextStream = objFile.OpenAsTextStream(ForReading)
'Cells(i + 2, 2) = objTextStream.ReadAll
s = objTextStream.ReadAll
vSplit = Split(s, "|")
Range("b" & i + 2).Resize(1, UBound(vSplit) + 1) = vSplit
i = i + 1
End If
Next
End Sub
推荐阅读
- sockets - 不能再在 XCode 中进行网络编程了
- kerberos - 带有 Kerberos 的 WSO2 IWA – 无法解密 kerberos 令牌异常
- javascript - 如何使用 java 脚本访问此字典中的字段 1 值?
- python - Pandas 中的子字符串元素
- java - android - 当应用程序未运行时通过 Intent 从通知中获取数据
- apache-spark - 如何将日志从纱线容器转发到 s3?
- php - 字符串和重音 PHP 的问题
- javascript - 手风琴按钮不会在 WordPress 中切换
- c# - 如何在文本框中设置 DateFormat(语言)?
- python - 在 Jupyter Notebook 中运行 Python 脚本,并传递参数