gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:12:19 24 4
gpt4 key购买 nike

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

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

成功代码:
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

最佳答案

尝试改变
If WS.Name Like "TUBA*" Then

If sh.Name Like "TUBA*" Then
或将您的 For Each 更改为 WS in...

关于vba - Excel VBA 错误 91,试图将某些工作表的数据导出到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40747831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com