[VBA] How to Import Fixed-Width Text Files Without Auto-Conversion

目次

Introduction

Excel is very convenient, but it has a troublesome habit of automatically converting data into numbers or dates when opening external files. For example, an ID code like “A01” might become “A1”, and a section number like “B-01” might be treated as a date (e.g., “Feb-01”).

In this article, I will introduce a method using VBA to import fixed-width text files while keeping the values exactly as they are, without any automatic conversion.

File Structure

Assume we are reading the following fixed-width text file (e.g., autoconvertdata.txt). The data is separated by specific character positions.

A01   B-01  20250725  PROD-XYZ          12345  **Unwanted**
A02   B-02  20250726  ITEM-123          98765  **Unwanted**

The goal is to import this file while keeping the ID codes and section numbers exactly as text, rather than letting Excel convert them.

VBA Code: Import Fixed-Width Data as String

Sub ImportFixedFileWithoutConversion()
    Dim filePath As String
    filePath = ThisWorkbook.Path & "\autoconvertdata.txt"
    
    Workbooks.OpenText _
        Filename:=filePath, _
        DataType:=xlFixedWidth, _
        FieldInfo:=Array( _
            Array(0, xlTextFormat), _
            Array(6, xlTextFormat), _
            Array(10, xlYMDFormat), _
            Array(20, xlTextFormat), _
            Array(40, xlGeneralFormat), _
            Array(49, xlSkipColumn))
    
    ActiveSheet.Range("A1").CurrentRegion.EntireColumn.AutoFit
End Sub

Explanation of Parameters

The FieldInfo parameter defines how each column is handled based on its starting position.

Start PositionFormat TypeDescription
0xlTextFormatID Code. Keeps the value as text (preserves “A01”).
6xlTextFormatSection Number. Prevents “B-01” from becoming a date.
10xlYMDFormatDate. Correctly interprets “20250725” as a date.
20xlTextFormatProduct Code. Treated as text.
40xlGeneralFormatAmount. Treated as a standard number.
49xlSkipColumnSkip. Ignores unnecessary columns.

Execution Result (Excel)

When you run the macro, the data appears in Excel as follows:

IDSectionDateProductAmount
A01B-012025/07/25PROD-XYZ12345
A02B-022025/07/26ITEM-12398765

Important Notes

  1. xlTextFormat: Using this prevents Excel’s automatic conversion (to numbers or dates).
  2. xlYMDFormat: This ensures that date strings (YYYYMMDD) are recognized correctly as dates.
  3. xlSkipColumn: Use this to ignore columns you do not need to import.
  4. Encoding: This method may not support UTF-8 encoding properly. If your file is UTF-8, you might need a different approach (like ADODB.Stream).

Advanced Tips

  • CSV Files: You can apply similar logic to CSV files using Workbooks.OpenText to prevent data corruption.
  • Formatting: You can add code to adjust fonts and borders after the import is complete, making it ready for reporting immediately.
  • Flexibility: You can adjust the FieldInfo array to match any file format you encounter in your work.

Summary

When importing fixed-width files in Excel, VBA control is essential to prevent important strings like “A01” or “B-01” from being changed automatically. By mastering the usage of FieldInfo introduced in this article, you can prevent unintended conversions and ensure accurate data processing.

If you have ever struggled with “values changing just by opening the file,” please give this method a try.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次