excel - 如何改进从 Excel 选择到文本文件的导出?
问题描述
我正在尝试将 Excel 数据导出到单个文本文件。目前,我下面的代码将 Excel 中的选择导出到名为“AgreementText.txt”的文件中。我想做两件事来改进它,但我不确定如何:
首先,我想为每个 .txt 文件命名不同的名称。文件的标题列在每个选择左侧的第 4 列中。有什么方法可以让我每次都从该列中获取标题?
其次,文本当前出现在文本文件中,并带有引号。有什么办法可以删除这些吗?
编辑:第三,我还需要为默认指定不同的文件路径,但我不确定如何。
提前致谢!
Sub TextFileExport()
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
myFile = Application.DefaultFilePath & "\AgreementText.txt"
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
End Sub
解决方案
首先,标题可以很容易地通过获取单元格值来检索。假设它将与您选择的顶部在同一行,但右侧有 4 列,您可以按以下方式进行操作:
myFile = Application.DefaultFilePath & "\" & Selection.Cells(1, Selection.Columns.Count + 4) & ".txt"
Open myFile For Output As #1
其次,您可以使用Print
而不是Write
不带引号的打印。我发现最简单的方法是将要编写的整行构建为一个字符串,然后Print
为每一行执行一个命令。
把它们放在一起:
Sub TextFileExport()
Dim myFile As String
Dim rng As Range
Dim line
Dim i As Integer
Dim j As Integer
Set rng = Selection
myFile = Application.DefaultFilePath & "\" & rng.Cells(1, rng.Columns.Count + 4) & ".txt"
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
line = ""
For j = 1 To rng.Columns.Count
line = line & rng.Cells(i, j).Value
If j < rng.Columns.Count Then
line = line & ","
End If
Next
Print #1, line
Next
Close #1
End Sub
推荐阅读
- python-3.x - 运行长度编码python;字符串索引超出范围错误
- excel - Excel FORECAST 函数来自多行中的历史数据
- typescript - 玩笑(与 tsjest)+ 打字稿 outDir 没有按预期工作
- php - 如何获取从 MySQL 查询中检索到的全部文档/对象?
- python - PyDev 中 fftconvolve 的 ImportError
- html - Bootstrap 导航栏汉堡图标不垂直对齐
- c++ - C++ 属性命名空间?
- discord.js - 使用机器人帐户获取用户配置文件连接
- git - 无法过滤 jenkins 中的 github webhook 触发器
- oracle - PLS-00049:蟾蜍中的错误绑定变量“D_DEPT_ID”