作者:乔山办公网日期:
返回目录:excel表格制作
制表分隔符格式的文件不是csv扩展名的.
csv扩展名的文件是以逗号分隔的.
txt扩展名的文件是以制表分隔符分隔的.
存为csv 和txt 的代码我都给你你 看需要吧
在要转换的目录新建一个excel文件.
打开这个新的excel文件
ALT+F11进入vba编辑窗口 新建一个模块 粘贴636f70797a686964616f362以下代码.
存为制表分隔符的文件
Sub 转换TXT()
Dim FilePath, MyFile, iPath As String
iPath = ThisWorkbook.Path
MyFile = Dir(iPath & "\*.xls")
If MyFile <> "" Then
Do
On Error Resume Next
If MyFile = ThisWorkbook.Name Then MyFile = Dir
Workbooks.Open (iPath & "\" & MyFile)
MyFile = Replace(MyFile, ".xls", ".txt")
Name = "\" & MyFile
FilePath = iPath & Name
ActiveWorkbook.SaveAs Filename:=FilePath, FileFormat:= _
xlText, CreateBackup:=False
Workbooks(MyFile).Close True
MyFile = Dir
Loop While MyFile <> ""
End If
End Sub
Sub 转换CSV()
Dim FilePath, MyFile, iPath As String
iPath = ThisWorkbook.Path
MyFile = Dir(iPath & "\*.xls")
If MyFile <> "" Then
Do
On Error Resume Next
If MyFile = ThisWorkbook.Name Then MyFile = Dir
Workbooks.Open (iPath & "\" & MyFile)
MyFile = Replace(MyFile, ".xls", ".csv")
Name = "\" & MyFile
FilePath = iPath & Name
ActiveWorkbook.SaveAs Filename:=FilePath, FileFormat:= _
xlCSV, CreateBackup:=False
Workbooks(MyFile).Close True
MyFile = Dir
Loop While MyFile <> ""
End If
End Sub
第一步:ATL+F11
第二步:在复左边当前工作制簿双击当前工作表
第三步:在右边百空白处粘贴如下代码度
Sub txt()
On Error Resume Next
MkDir "d:\导出TXT"
Dim i As Long, a As String, b As String
For i = 1 To Cells(65536, 1).End(xlUp).Row
a = Cells(i, 1)
b = Cells(i, 2)
Open "d:\导出TXT\" & a & ".txt" For Output As #1
Print #1, b
Close #1
Next i
MsgBox "完成问" & i & "条数据导出"
End Sub
第四步:F5运行,导出的TXT文件答在:d:\导出TXT
建一个文件夹,把目标txt文件和excel文件放入其中,在excel的宏编辑器中写入以下代码,有些地方可根据你的实际情况做相7a686964616fe78988e69d83338应改动:
Sub import_from_txt()
Dim file_name As String, my_path As String
Dim lines, cols
Dim i As Integer, j As Integer, k As Integer, q As Integer
Application.ScreenUpdating = False
Worksheets("Sheet1").Range("A1:Z65536").ClearContents
my_path = ThisWorkbook.Path
file_name = "test.txt"
'读取文件
Open my_path & "\" & file_name For Input As #1
lines = Split(StrConv(InputB(LOF(1), 1), vbUnicode), vbCrLf)
Close #1
k = UBound(lines) + 1 '文件的行数
'遍历每一行
For i = 1 To k
cols = Split(lines(i - 1), ",") '以逗号作为分隔,将每行字符分割,分隔符可根据实际情况自己修改
q = UBound(cols) + 1 '分隔成的列数
For j = 1 To q '遍历该行的每一列
Worksheets("Sheet1").Cells(i, j) = cols(j - 1) '输出到表格中
Next
Next
MsgBox ("文件" & file_name & "读取完成,共" & k & "行")
Application.ScreenUpdating = True
End Sub
将你百语句度中问的saveas语句答改为版权
ActiveWorkbook.SaveAs Filename:=mypathtxt & Left(myfilename, Len(myfilename) - 4) & "@" & ActiveSheet.Name & ".txt", FileFormat:=xlCSV