将工作表写入制表符分隔文件的VBA代码失败

时间:2014-01-13 00:17:45

标签: excel-vba vba excel

我有以下VBA代码

sub aemaketxtfile(className As String, rosterFileHandle As String)
Dim i As Long
Dim j As Long
Dim cellContent As String
Dim gradebookContent As String
With Worksheets(className).UsedRange
    gradebookContent = "  % seating" & vbCrLf
    For i = 1 To .Rows.Count
      For j = 1 To .Columns.Count
        cellContent = "a"
        cellContent = .Cells(i, j).Value
        gradebookContent = gradebookContent & cellContent & vbTab
       ' gradebookContent = gradebookContent & vbCrLf & Join$(Application.Transpose(Application.Transpose(.Rows(i).Value)), vbTab)
    Next
       gradebookContent = gradebookContent & vbCrLf
    Next
    End With

 Open Replace(ThisWorkbook.FullName, "seating_chart.xlsm", rosterFileHandle) For Output As #1
 'Open rosterFileHandle For Output As #1
     Print #1, Mid$(gradebookContent, Len(vbCrLf) + 1)
Close #1
End Sub

Sub makeALLtxt()
Call aemaketxtfile("all students", "rosterAllStudents.txt")
End Sub

每次我运行它都会收到错误:“运行时错误'52':错误的文件名或数字

我在其他Excel文档中使用此代码没有任何问题。我不明白为什么它不在这里工作。

如果我注释掉第一个Open Replace ....并取消注释第二个,我可以让事情发挥作用,但我对此不满意,因为有些时候Excel似乎将文件保存到随机目录。

1 个答案:

答案 0 :(得分:1)

尝试替换

Replace(ThisWorkbook.FullName, "seating_chart.xlsm", rosterFileHandle)

ThisWorkbook.Path & "\" & rosterFileHandle

我认为这会在不依赖ThisWorkbook名称的情况下提供您所寻求的结果