Excel VBA错误91,试图导出某些工作表的数据到文本文件
我试图编写一个macros来检查所有的sheetnames是否符合某些条件(特别是在这个名字里包含了'TUBA'),如果符合的话,将这些表格中的范围导出到表格名称为文件名的文本文件中。 我得到错误91:对象variables或块variables未设置,并在debuggingIf WS.name Like "TUBA*" Then
线被突出显示。 我怎样才能解决这个问题? 有问题的代码如下。 我以前用几乎相同的代码,但没有If
语句(显示在下面的第二个块)成功,所以我认为它是我join这个的方式。如果我需要设置一个variables,哪一个我错过了?
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...
注意:这只是一个想法,而不是一个答案,因为@Rdster解释了为什么你的第一个代码不工作。
如果你只使用一列(就像你的两个代码一样),你可以replace这部分代码:
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
用这一行:
output = Join(Application.Transpose(sh.Range("F3:F200").Value), vbNewLine)