无法将工作簿变量设置为ActiveWorkbook

时间:2015-03-13 10:36:20

标签: excel vba excel-vba

这让我大吃一惊。我找不到我做错了什么。我希望这只是隧道视觉的一个例子。 我收到错误消息“对象变量或使用块变量未设置-1”

Option Explicit:
Public mWB As Workbook
Public Sub runCSSBatch()
  On Error GoTo Errorcatch

1    mWB = ActiveWorkbook
     Call createTempSheet
     Call findworksheet

  Errorcatch:
     MsgBox Err.Description & "-" & Erl
     Application.DisplayAlerts = False
     mWB.Sheets("TEMP").Delete
     Application.DisplayAlerts = True

End Sub

2 个答案:

答案 0 :(得分:1)

而不是ActiveWorkbook,它可能是,ThisWorkbook

set mwb=thisworkbook

答案 1 :(得分:0)

我最终发现我的脚本有很多问题。

  • 我最终在ActiveWorkbook前面使用了Set(使用ThisWorkbook 没有必要)
  • 我相信关于使用1:而不是1来捕捉错误的评论 是有效的。
  • 我现在运行的脚本比我少了很少 之前。
  • 我还犯了在Range()中使用Cells()的错误 排除其他
  • 我试图将工作表变量传递给Sub(显然你不能 那样做。)。
  • 我确定还有更多,但我无法回忆。

我打算把它弄得白痴。 :/ 正如您所看到的,下面的代码与我最初发布的内容完全不同。

Option Explicit:
Public mWB As Workbook
Public Sub runCSSBatch()
   Set mWB = ActiveWorkbook
    mWB.Sheets.Add.Name = "TEMP"
    Dim WSh As Worksheet
    For Each WSh In mWB.Worksheets
        If InStr(WSh.Name, "CSS") = 1 Then
            Call parseRowText(WSh.Name)
        End If
    Next
End Sub
Private Sub parseRowText(WSName As String)
Dim rowCount As Long
Dim I As Long
Dim columnCount As Long
Dim B As Long
Dim dataString As String
Dim WS As Worksheet
Set WS = mWB.Worksheets(WSName)

columnCount = mWB.Sheets(WSName).UsedRange.Columns.Count
rowCount = mWB.Sheets(WSName).UsedRange.Rows.Count

For I = 2 To rowCount
    For B = 1 To columnCount
        dataString = ""
        If mWB.Sheets(WSName).Cells(1, B).Value = "STOP" Then
            dataString = "}"
            Call addToTempSheet(dataString)
            Exit For
        Else
         If B = 1 Then
             dataString = mWB.Sheets(WSName).Cells(I, B).Value & "{"
             Call addToTempSheet(dataString)
         Else
            If dataString & mWB.Sheets(WSName).Cells(I, B).Value = "" Then
            Else
                dataString = mWB.Sheets(WSName).Cells(1, B).Value & ":"
                dataString = dataString & mWB.Sheets(WSName).Cells(I, B).Value & ";"
                Call addToTempSheet(dataString)
            End If
         End If
        End If
    Next B
Next I
End Sub
Private Sub addToTempSheet(dString As String)
    mWB.Sheets("TEMP").Range("A" & Rows.Count).End(xlUp).Offset(1).Value = dString
End Sub