使用VBA代码的Problom引发“未定义用户定义的类型”错误

时间:2019-02-16 14:32:17

标签: excel vba

我无法弄清楚为什么以下代码会引发编译错误,并显示消息“用户定义的类型未定义”。它突出显示了Set fso = FileSystemObject

Sub S()     
Dim fso As FileSystemObject
    Dim ts As TextStream
    Dim i As Integer
    Dim myCell As Range

    Set fso = FileSystemObject

    For i = 0 To TotalColumnNumber
       ' last argument, True, says to create the text file if it doesnt exist, which is
       ' good for us in this case
       Set ts = fso.OpenTextFile("column_" & i, ForWriting, True)

       ' set mycell to the first cell in the ith column
       Set myCell = SheetName.Cells(1, i)

       ' continue looping down the column until you reach a blank cell
       ' writing each cell value as you go
       Do Until myCell.Value = ""
           ts.writeline myCell.Value
           Set myCell = myCell.Offset(1, 0)
       Loop

       ts.Close
    Next

    Set ts = Nothing
    Set fso = Nothing


    End Sub

谢谢

2 个答案:

答案 0 :(得分:2)

代码有很多个问题:

  1. 您需要设置参考

enter image description here

  1. 使用:设置fso = New FileSystemObject
  2. 在使用变量之前建立变量的值;其中包括TotalColumnNumberSheetName等。

答案 1 :(得分:0)

您是否在工具/参考中引用了正确的名称空间?