0

我正在制作一个宏,它将搜索列表并在第一个具有“spectraseven”的列中找到所有条目。这会将这些记录复制到每个条目的工作表中。

当工作簿中只有一张工作表时,此宏有效,但当工作簿中有更多工作表时,它会object or variable with block not set在末尾带有箭头的行给出错误。( If FoundCell.Address = FirstAddr Then)

Function mySheetData(SheetName As String) As Boolean

'
'By Joe Was
    'This adds a sheet and names it "Test."
    'SheetName = Sheets(1).Range("a1")
    Sheets.Add.Name = SheetName

    'This selects your new sheet and moves it after sheet "Sheet3," which could be any sheet name.
    Sheets(SheetName).Select
    Sheets(SheetName).Move After:=Sheets(Worksheets.Count)

    'this selects the sheet with the data and its range.
    Sheets(1).Select
    Range("A1:c20").Select

    'This will copy and paste the data to your new sheet "Test."
    Selection.Copy
    Sheets(SheetName).Select
    ActiveSheet.Paste

    'At this point your data will be on the new sheet and selected for the next step.

End Function
'copy from template sheet
'add information from each summary sheet to the tech sheets

'Function MoveToTables(manName As String, startCell As Integer, cellRange As String) As Boolean
Sub testWild()
startCell = 1
Dim FoundCell As Range
Dim LastCell As Range
Dim FirstAddr As String
Dim technum As String

cellRange = "e1:e500"
topCount = startCell
With Range("e1:e500")
    Set LastCell = .Cells(.Cells.Count)
End With
Dim findString As String
findString = "SPECTRASEVEN*"
Set FoundCell = Sheets(1).Range(cellRange).Find(what:=findString, After:=LastCell)

If Not FoundCell Is Nothing Then
    FirstAddr = FoundCell.Address
End If
Do Until FoundCell Is Nothing
    Debug.Print FoundCell.Address
    Count = FoundCell.Row
    technum = Right(FoundCell, 4)
    Set FoundCell = Range(cellRange).FindNext(After:=FoundCell)
    temp = mySheetData(technum)
    ' vv This is the line with the error vv
    If FoundCell.Address = FirstAddr Then
             Exit Do
    End If
Loop
End Sub
4

1 回答 1

0

Nothing问题是在测试有机会发生之前,您正在前进到下一个单元格。

此示例用于打印单个数字:

Sub test1()

Dim j

j = 1
Do Until j = 10
    Debug.Print j
    j = j + 1
    If j = 10 Then Debug.Print "oops, why no exit?"
    Debug.Print j
Loop

End Sub

如果您运行此代码,您将看到当 j=10 时打印的消息,即使看起来循环应该结束。
将增量固定在循环结束时,以便测试可以工作,给出:

Sub test2()

Dim j

j = 1

j = j + 1
Do Until j = 10
    Debug.Print j
    If j = 10 Then Debug.Print "oops, why no exit?"
    Debug.Print j
    j = j + 1
Loop

End Sub

请注意,我现在有 2 个增量,一个在循环开始之前(以防 j 在我开始测试之前恰好是 9)和一个在末尾,因此循环可以在正确的点进行测试

于 2012-08-23T17:38:58.777 回答