案例:
Public Sub Example1()
'dialog result
Dim intDialogResult As Integer
'path selected by user
Dim strPath As String
'single line of data from the text file
Dim strLine As String
'string seperated by the delmiter
Dim arrString() As String
'curren row in excel sheet
Dim i As Integer
Dim FileName As String
'disallow user from selecting multiple files
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'remove previous filters
Call Application.FileDialog(msoFileDialogOpen).Filters.Clear
'display the open file dialog
intDialogResult = Application.FileDialog(msoFileDialogOpen).Show
'if the user selected a file
If intDialogResult <> 0 Then
'path selected by the user
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
'close the file index #1 if its already opened
Close #1
'open the file for reading
Open strPath For Input As #1
i = 1
'loop while the end of file has not been reached
While EOF(1) = False
'read one line of data from the text file
Line Input #1, strLine
'split string based on delimiter
arrString = Split(strLine, " ")
'I only need the 6th column values
ActiveCell(i, 2) = arrString(6)
i = i + 1
Wend
End If
Close #1
ActiveCell.Offset(0, 1).Activate
End Sub
它的作用基本上是从.txt文件的第6列获取值,并在每次宏运行时将它们放在一起。
问题1:我想水平存储它们(.txt文件中每列最多200个值)
问题2:我想将第一个单元格设置为文件名
答案 0 :(得分:0)
您可以使用快捷键执行此操作。如果要查看代码,请启用“录制宏”:
在表1中:
选择阵列中的任何单元格
Ctrl + a
&lt; -select all
Ctrl + c
&lt; - copy
转到第2页:
选择单元格A1
Ctrl + Alt + v
&lt; - 特殊粘贴
e
&lt; - Transpose
输入&lt; - 粘贴
答案 1 :(得分:0)
要跨列而不是向下填充数据,您可以更改
ActiveCell(i, 2) = arrString(6)
到
ActiveCell(1, i) = arrString(6)
。
要从StrPath中提取文件名,请使用
FileName = StrReverse(Left(StrReverse(strPath), InStr(1, StrReverse(strPath), Application.PathSeparator) - 1))
(您声明FileName as String
但未使用它)
要将FileName
放在第一个单元格上,只需在输入ActiveCell = FileName
循环前的行添加While
,然后将i
设置为从2开始(即{{ 1}})
对于相关部分,整个更改将如下(注释已删除):
i = 2
最后,如果我的猜测是正确的,要激活下一行的第一个单元格,请使用
FileName = StrReverse(Left(StrReverse(strPath), InStr(1, StrReverse(strPath), Application.PathSeparator) - 1))
ActiveCell = FileName
i = 2
While EOF(1) = False
Line Input #1, strLine
arrString = Split(strLine, " ")
ActiveCell(1, i) = arrString(6)
i = i + 1
Wend