【发布时间】:2014-03-25 03:24:55
【问题描述】:
我正在尝试在 Excel 中使用 VBA 自动将 .txt 文件(制表符分隔)转换为 .xlsx 文件。这是我所拥有的:
Set WB = Workbooks.Open(folder + file, , , 1)
If Right(file, 3) = "txt" Or Right(file, 3) = "xls" Then
Application.DisplayAlerts = False
WB.SaveAs filename:=folder + milestone + "_" + loadtype + "_" + Left(file, Len(file) - 4) + "_" + metricDate + "_.xlsx", _
FileFormat:=51
Application.DisplayAlerts = True
Else
Application.DisplayAlerts = False
WB.SaveAs filename:=folder + milestone + "_" + loadtype + "_" + Left(file, Len(file) - 5) + "_" + metricDate + "_.xlsx", _
FileFormat:=51
Application.DisplayAlerts = True
End If
WB.Close
当然,这只是一段代码,我认为代码的第一部分是最相关的。我才开始检查转换后的 .txt 文件,因为它们的大小是保存后的 10%。结果,二十列被压缩成三列,所有的空格和制表符都被删除了。不知道发生了什么,因为我不经常使用 VBA。
我认为关键在这里:
Set WB = Workbooks.Open(folder + file, , , 1)
末尾的 1 表示制表符分隔。不知道它会对它也打开的 .xls 文件做什么,但接下来我会担心的。
感谢您的指点。
编辑。
我更改了代码以区别对待 .txt 和 .xls,正如我一开始就应该做的那样。这是当前代码:
Dim WB As Workbook
'Dim WBS As Workbooks
If Right(file, 3) = "txt" Then
Set WB = Workbooks.OpenText Filename:=folder + file, DataType:=xlDelimited, Tab:=True
Application.DisplayAlerts = False
WB(1).SaveAs filename:=folder + milestone + "_" + loadtype + "_" + Left(file, Len(file) - 4) + "_" + metricDate + "_.xlsx", _
FileFormat:=51
Application.DisplayAlerts = True
WB.Close
ElseIf Right(file, 3) = "xls" Then
Set WB = Workbooks.Open(folder + file)
Application.DisplayAlerts = False
WB.SaveAs filename:=folder + milestone + "_" + loadtype + "_" + Left(file, Len(file) - 4) + "_" + metricDate + "_.xlsx", _
FileFormat:=51
Application.DisplayAlerts = True
WB.Close
Else
Set WB = Workbooks.Open(folder + file)
Application.DisplayAlerts = False
WB.SaveAs filename:=folder + milestone + "_" + loadtype + "_" + Left(file, Len(file) - 5) + "_" + metricDate + "_.xlsx", _
FileFormat:=51
Application.DisplayAlerts = True
WB.Close
End If
【问题讨论】:
-
你试过
Workbooks.OpenText吗?这似乎对我有用。试试Workbooks.OpenText Filename:="C:\filenameandpath", DataType:=xlDelimited, Tab:=True -
这是一个很好的开始,但之后我不知道如何将其保存为 xlsx。工作簿(复数)没有内置保存功能,仅适用于工作簿(单数)。
-
Excel 对单个工作簿的方法调用是复数
Workbooks。它应该可以正常工作。 -
我只看到您打开 1 个工作簿,因此 saveas 方法应该适合您。将 wb 调暗为工作簿 wb.SaveAs "fileNameHere", Excel.XlFileFormat.xlOpenXMLWorkbook
-
您已经在使用
Workbooks打开您的文件。只需使用Set WB = Workbooks.OpenText Filename:=...,您就可以打开(一个)工作簿。要保存,您可以使用您现在使用的内容,也可以使用FileFormat:=xlOpenXMLWorkbook属性进行保存。