用VBA把txt文件导入excel空格的问题
代码如下:
---------------------------------------
Open "d:\log.txt" For Input As #1
i = 1
While Not EOF(1)
Line Input #1, textLine
Cells(i, 1).Value = textLine
i = i + 1
Wend
Close #1
---------------------------------------
我想把txt逐行导入excel中,这样虽然可以实现。
但是有两个问题:
1:“qwe wadawd”导入后就变成“qwewadawd”了,空格没有了,我想保留空格怎么办?
2:tab键&“asdad”导入后是“asdad”,而且显示在第一列,我想把“asdad”表示在第二列,就是前面有记个tab,导入后就能空出记列,这个能实现吗?
[解决办法]
1:如果你确认中间是空格而不是Tab键的话,应该没问题 不会自动合起来的
2:全部代码如下:
- VB code
Sub test() Dim i As Integer Dim nPerCol As Integer Dim textline As String Dim strTemp As String Open "d:\log.txt" For Input As #1 i = 1 While Not EOF(1) Line Input #1, textline strTemp = textline nPerCol = 1 '默认从第一列开始写 Do Until InStr(strTemp, vbTab) = 0 '判断是否含有Tab键 If InStr(strTemp, vbTab) = 1 Then If Len(strTemp) > 1 Then strTemp = Right(strTemp, Len(strTemp) - 1) '去掉第一个Tab Else strTemp = "" End If Else Cells(i, nPerCol) = Left(strTemp, InStr(strTemp, vbTab) - 1) strTemp = Right(strTemp, Len(strTemp) - InStr(strTemp, vbTab) + 1) End If nPerCol = nPerCol + 1 '无论是去掉一个Tab 还是写入一个值,默认写入列+1 Loop If Len(strTemp) > 0 Then Cells(i, nPerCol).Value = strTemp End If i = i + 1 Wend Close #1End Sub