我创建了一个VBA代码,用于将数据从单个硬编码工作表导出到export.txt文件。我不得不使用两个For循环,因为我不知道以什么不同(和简单)的方式我会跳过由导出透视图中的不必要信息组成的两行(文件类型和另一个宏的主键)。尽管如此,宏还是有它的作用......
Sub VBA_Write_to_a_text_file()
Dim filename As String
Dim rng As Range
Dim cellValue As Variant
Dim i As Integer
Dim j As Integer
filename = Application.ThisWorkbook.Path & "/export.txt"
Open filename For Output As #1
Set rng = Sheets(22).Range("A1:G1")
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
Set rng = Sheets(22).Range("A4:G18")
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
......除了两个问题外:
答案 0 :(得分:1)
使用FileSystemObject创建文本文件并随意写入:
Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
Dim oFile : Set oFile = oFso.CreateTextFile("C:\temp\myfile.txt")
然后,您可以使用以下命令编写任何内容:
oFile.WriteLine "This will write a line and end it with a vbNewLine"
oFile.Write "Where this write method will "
oFile.Write "just write to the file without the new line on the end of the text."
oFile.WriteLine "You|can|send|pipe|delimited|text|or|whatever|else|you|like"
oFile.Close 'close and save the updated text file
您可以根据需要通过加倍来控制是否发送报价,例如:
oFile.WriteLine """This is quoted text"""
将打印"这是引用的文字"在你的文件中。
答案 1 :(得分:0)
完全同意Dave建议使用FileSystemObject
- 它可以在Microsoft Scripting Runtime库中找到,您应该将其添加到项目中。我的另一个建议是迭代数据行并为每一行创建一个数组。然后,您可以使用Join
函数将该数组转换为字符串,每个值都用您选择的分隔符分隔,例如|
。
将一行Range
变为一维数组需要使用Transpose
函数进行一些小技巧。它确实可以使您不必总是检查最后一个字段,而不是在该迭代上输出分隔符。它还可以节省您使用嵌套循环的时间。
以下是代码:
Option Explicit
Sub Export()
'for file system
Dim objFs As New FileSystemObject
Dim tsOut As TextStream
'for data
Dim rngHeaders As Range
Dim rngData As Range
Dim rngRow As Range
Dim varRowData As Variant
Dim strRowData As String
Dim strDelimiter As String
'counters
Dim lngCounter As Long
'set up data
Set rngHeaders = Sheet2.Range("A1:F1")
Set rngData = Sheet2.Range("A3:F10")
'set delimiter
strDelimiter = "|"
'set up file system
Set tsOut = objFs.CreateTextFile("c:\temp\out.txt", True)
'output header
varRowData = WorksheetFunction.Transpose(WorksheetFunction.Transpose(rngHeaders.Value))
strRowData = VBA.Join(varRowData, strDelimiter)
tsOut.WriteLine strRowData
'output data
For lngCounter = 1 To rngData.Rows.Count
Set rngRow = rngData.Rows(lngCounter)
varRowData = WorksheetFunction.Transpose(WorksheetFunction.Transpose(rngRow.Value))
strRowData = VBA.Join(varRowData, strDelimiter)
tsOut.WriteLine strRowData
Next lngCounter
'clean up
tsOut.Close
Set tsOut = Nothing
Set objFs = Nothing
End Sub