用VBA把txt文件导入excel空格的问题

sleepbaby123 2010-03-25 09:04:01
代码如下:
---------------------------------------
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,导入后就能空出记列,这个能实现吗?
...全文
402 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
liguicd 2010-03-25
  • 打赏
  • 举报
回复
帮顶咯
倒大霉的上帝 2010-03-25
  • 打赏
  • 举报
回复
1:如果你确认中间是空格而不是Tab键的话,应该没问题 不会自动合起来的
2:全部代码如下:

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 #1
End Sub

舉杯邀明月 2010-03-25
  • 打赏
  • 举报
回复
1. 不会啊!
2. 不行。

2,503

社区成员

发帖
与我相关
我的任务
社区描述
VBA(Visual Basic for Applications)是Visual Basic的一种宏语言,是在其桌面应用程序中执行通用的自动化(OLE)任务的编程语言。
社区管理员
  • VBA
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧