【问题标题】:How to keep zeroes to the left of a number when opening a txt file with VBA?使用VBA打开txt文件时如何在数字左侧保留零?
【发布时间】:2019-09-19 11:08:54
【问题描述】:

我用 Excel 打开一个 .txt,将它复制到我的 .xls 文件中,然后运行一些 VBA 函数。

当数字左边有零时,Excel 会删除它们,程序会失败,因为数字实际上是一个字符串。

如何用零复制它们?

当我用 Excel 打开 .txt 时,它打开时没有零,所以我无法格式化任何内容。

.txt 是动态的,作为数字的字符数。
.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 会丢失此配置。

【问题讨论】:

  • 以 = 开头并用引号括起来的数字工作不确定这如何与您当前的流程一起使用,即 ="00001230" 您还应该将新工作簿中的列格式化为文本,即 @987654323 @
  • FieldInfo 参数中将第二个数字更改为 2,这应该将数据视为文本。不同的数字对应不同类型的数据。请注意,这只会影响您的第一列

标签: excel vba


【解决方案1】:

不要使用.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多