使用Excel VBA宏写入新的.txt文件,代码片段无法编译(Expected =)

时间:2015-08-18 18:53:42

标签: excel excel-vba vba

我试图编写循环遍历单元格的Excel宏(4列,一些行数),并将内容写入文本文件,每个单元格由回车符分隔。我收到了编译错误" = expect"创建文本文件:

Sub GenerateFile()
    'get last row with data
    Dim lastRow As Integer
    lastRow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row

    'loop through rows to build string
    Dim textFile As String
    For i = 2 To lastRow
        textFile = textFile & ActiveSheet.Cells(i, 1) & Chr(13) & ActiveSheet.Cells(i, 2) & Chr(13) & ActiveSheet.Cells(i, 3) & Chr(13) & ActiveSheet.Cells(i, 4) & Chr(13)
    Next i

    'write string to file
    Dim filePath As String
    filePath = Application.ActiveWorkbook.Path
    If Not System.IO.file.Exists(filePath) Then
        System.IO.file.Create(filePath).Dispose()
    End If
End Sub

完整代码:

{{1}}

[编辑]所以我认为可能是因为我试图使用VB代码片段,我在这里找到了一个指南(http://www.wiseowl.co.uk/blog/s211/writeline.htm)来使用FileSystemObject和TextStream,但这些需要启用图书馆。我需要与其他人分享这个工具,不能让他们全部启用库:(任何其他建议?

2 个答案:

答案 0 :(得分:0)

感谢http://www.wiseowl.co.uk/blog/s211/writeline.htm和@JohnColeman:

使用下面的代码并启用了对Microsoft Scripting Runtime'库(工具>参考资料>' Microsoft Scripting Runtime')

'get filePath, fileName
Dim filePath As String
filePath = Application.ActiveWorkbook.Path
fileName = "\file.txt"

'create file
Dim fso As New FileSystemObject
Dim ts As TextStream
Set ts = fso.CreateTextFile(filePath & fileName, True)
ts.WriteLine (fileString)
ts.Close

答案 1 :(得分:0)

您可以尝试使用以下内容在VBA中无需添加引用

.app1 {
    background-image: url(../img/photo1.png), 
                      url(../img/photo2.png);
    background-size: 17em, 27em;