我有从其他系统自动导出到我的txt文件(我无法更改此系统)。当我尝试使用以下代码将这些txt文件转换为excel时(我手动创建了一个子文件夹xlsx):
Sub all()
Dim sourcepath As String
Dim sDir As String
Dim newpath As String
sourcepath = "C:\Users\PC\Desktop\Test\"
newpath = sourcepath & "xlsx\"
'make sure subfolder xlsx was created before
sDir = Dir$(sourcepath & "*.txt", vbNormal)
Do Until Len(sDir) = 0
Workbooks.Open (sourcepath & sDir)
With ActiveWorkbook
.SaveAs Filename:=Replace(Left(.FullName, InStrRev(.FullName, ".")), sourcepath, newpath) & "xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
.Close
End With
sDir = Dir$
Loop
End Sub
它确实可以工作,但是某些特殊字符(如ä,ö和Ü等)无法正确显示。即,以后我打开xlsx文件时,可以看到它们已被替换为ä等。我可以解决,现在开始替换这些,但是我想将txt改进为xlsx代码。根据这一职位或这一个应该使用ADODB.Stream是可能的。但是,我不知道如何在我的代码(循环)中实现它,以使其在我的情况下在这里工作?如果还有其他方法代替ADOB.Stream,我也可以。对我来说,没有必要使用ADOB.Stream。
您是否尝试过使用参数强制执行代码页Origin
?我不知道您是否需要一个特定的常量,但是UTF-8常量可能是一个起点。我个人喜欢此页面作为参考源:https : //docs.microsoft.com/zh-cn/windows/win32/intl/code-page-identifiers
因此,解决方案可能像这样简单-在我的虚拟测试中有效:
Option Explicit
Private Const CP_UTF8 As Long = 65001
Public Sub RunMe()
Dim sDir As String, sourcePath As String, fileName As String
Dim fso As Object
sourcePath = "C:\anyoldpath\"
Set fso = CreateObject("Scripting.FileSystemObject")
sDir = Dir(sourcePath & "*.txt", vbNormal)
Do While Len(sDir) > 0
fileName = sourcePath & "xlsx\" & fso.GetBaseName(sDir) & ".xlsx"
Application.Workbooks.OpenText sourcePath & sDir, CP_UTF8
ActiveWorkbook.SaveAs fileName, xlOpenXMLWorkbook
ActiveWorkbook.Close False
sDir = Dir()
Loop
End Sub
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句