Microsoft Lab
全部软件
Excel应用程序对象(Application Object)约 4 分钟

Write Data to Text File 写入文本文件

重点内容


适用版本

桌面版通用(Excel 365 / 2021 / 2019 等)。


完整代码

Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer

myFile = Application.DefaultFilePath & "\sales.csv"

Set rng = Selection

Open myFile For Output As #1

For i = 1 To rng.Rows.Count
    For j = 1 To rng.Columns.Count
        cellValue = rng.Cells(i, j).Value
        If j = rng.Columns.Count Then
            Write #1, cellValue
        Else
            Write #1, cellValue,
        End If
    Next j
Next i

Close #1

逻辑说明

  • Application.DefaultFilePath:取得 Excel 默认的文件存储路径(在 File›Options›Save里可以调整),拼上文件名 "sales.csv"
  • Set rng = Selection:把使用者目前选中的范围存进 rng
  • Open myFile For Output As #1:以「写入模式」打开文件——📌 如果这个文件已经存在,会被整个覆盖掉,不是追加内容
  • 双层循环逐行逐列走过选中范围:如果这一格不是该行最后一列,用逗号分隔(Write #1, cellValue,);是最后一列就换行(Write #1, cellValue)
  • Close #1:写完一定要关闭文件,内容才会真正存进去

学完你会

常见错误

  • 文件已经存在还用 For Output 打开,没意识到会直接覆盖掉旧文件的内容
  • 写完数据忘记 Close #1,文件可能没有真正写入完整内容
  • 双层循环里最后一列该不该加逗号的判断写反,导致每行末尾多一个逗号或少了换行

Sources

Blog / Website:

  1. Write Data to Text File
只记在你的浏览器里,换设备不会同步。