用vba打开txt时,excel的左边的零

我想用Excel打开一个.txt文件,将它复制到我的.xls文件,并使用一些vba函数。 事实上,它正在工作。 主要的问题是,当数字左边有一些零时,Excel删除它们,程序失败(因为实际上没有int,所以有一个string必须有完全相同的字符)。

我怎样才能将它们复制到零? 当我使用Excel打开.txt文件时,打开时不会显示零,因此我无法在此处设置任何格式。

.txt是dynamic的,就像数字的字符数一样。 .txt内容的随机示例可以是:H 00013 SUPB4 00551 LEM 2252.554 00548 00540 00

主要代码是:

Workbooks.OpenText ThisWorkbook.Path & "\Text.txt", Origin:=xlWindows, StartRow:=1, FieldInfo:=Array(1, 1) UltLinea = Range("A" & Rows.Count).End(xlUp).Row Range("A1:Z" & UltLinea).Copy Hoja1Text = ActiveWorkbook.Name Workbooks(Hoja1GenDocs).Activate Worksheets("Hoja1").Range("A1").PasteSpecial xlPasteAll Application.CutCopyMode = False Workbooks(Hoja1Text).Activate ActiveWorkbook.Close Savechanges:=False Range("A1").Select 

我也尝试修改“正常”样式,将数字更改为@(文本),但是当打开一个新文件时,Excel将丢失此configuration。

还有什么想法? 谢谢

不要使用.OpenText打开文本文件。 使用.QueryTable导入文件。 例如,如果你的文本文件看起来像这样

 H 00013 SUPB4 00551 LEM 2252.554 00548 00540 00 

那我们这个

 Option Explicit Sub Sample() Dim wb As Workbook Dim ws As Worksheet Dim fName As String Set wb = Workbooks.Add Set ws = wb.Sheets(1) fName = ThisWorkbook.Path & "\Text.txt" With ws.QueryTables.Add(Connection:= _ "TEXT;" & fName, Destination:=ws.Range("$A$1")) .Name = "tempfile" .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .TextFilePromptOnRefresh = False .TextFilePlatform = 437 .TextFileStartRow = 1 .TextFileParseType = xlDelimited .TextFileTextQualifier = xlTextQualifierDoubleQuote .TextFileConsecutiveDelimiter = True .TextFileTabDelimiter = True .TextFileSemicolonDelimiter = False .TextFileCommaDelimiter = False .TextFileSpaceDelimiter = True .TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, 2, 2) .TextFileTrailingMinusNumbers = True .Refresh BackgroundQuery:=False End With End Sub