Excel VBA错误91,尝试将某些工作表的数据导出到文本文件

Ric*_*rag 1 excel vba excel-vba

我正在尝试编写一个宏,它根据某些条件检查所有工作表名称(特别是在名称中包含'TUBA'),如果符合,则将这些工作表上的范围导出为文件夹名称为文件名的文本文件.我收到错误91:对象变量或未设置块变量,并在调试时If WS.name Like "TUBA*" Then突出显示该行.我怎样才能解决这个问题?有问题的代码如下.我以前使用几乎相同的代码但没有If声明(在下面的第二个块中显示)成功,所以我假设我添加它的方式.如果我需要设置一个变量,哪一个我错过了?

Sub ExportTubatoText()

Dim c As Range, r As Range
Dim output As String
Dim lngcount As Long
Dim WS As Worksheet
Dim Name As String
Dim strFolder As String
strFolder = GetFolder("L:TUBA\")

'\ dialog box opens in that folder as default
'strFolder = GetFolder("L:TUBA\")

If strFolder <> "" Then

    MsgBox strFolder

End If

For Each sh In ThisWorkbook.Worksheets
'if worksheet has 'TUBA' in the title, then it is exported to text
    If WS.Name Like "TUBA*" Then
        output = ""
        For Each r In sh.Range("F3:F200").Rows
            For Each c In r.Cells
             output = output & c.Value
            Next c
            output = output & vbNewLine
        Next r
        Name = sh.Name
        Open strFolder & "\" & Name & ".txt" For Output As #1
        Print #1, output
        Close
    End If
Next
End Sub
Run Code Online (Sandbox Code Playgroud)

成功的代码:

For Each sh In ThisWorkbook.Worksheets
    output = ""
    For Each r In sh.Range("O2:O500").Rows
        For Each c In r.Cells
         output = output & c.Value
        Next c
        output = output & vbNewLine
    Next r
    Name = sh.Name
    Open strFolder & "\" & Name & ".txt" For Output As #1
    Print #1, output
    Close
Next
Run Code Online (Sandbox Code Playgroud)

Rds*_*ter 6

尝试改变

If WS.Name Like "TUBA*" Then

If sh.Name Like "TUBA*" Then

或者将您的For Each更改为 WS in...

  • 正如后续的那样 - "Option Explicit"会立即标记出这个错误...... (2认同)