对象需要vba

时间:2016-12-05 19:35:24

标签: vba

我在下面有这个代码,其中Set x不起作用。这就像Set f那样奇怪。我不知道为什么,我在我的代码中间,这根本不起作用。在我看来,它与Set f相同。有什么想法吗?

Sub Macro2()

Dim WsOuput As Worksheet
Dim WsScenarios As Worksheet
Dim ScenarioIDrow As Long
Dim ScenarioIDColumn As Long
Dim ScenarioIDinScenarios As Long
Dim ScenarioIDinScenariosC As Long
Dim p As String
Dim q As String
Dim x As Range
Dim z As String
Dim r As String
Dim RgnScenarioOutput As Range
Dim RgnScenarioScenario As Range
Dim Findsomething As Range
Dim FindAgain As Range
Dim lLastRow As Long
Dim f As Range
Dim fAgainAddress As Range

Set WsOutput = Worksheets("Output")
Set WsScenarios = Worksheets("Scenarios.New")
lLastRow = WsOutput.Cells(Rows.Count, "B").End(xlUp).Row
r = WsOutput.Cells(lLastRow, 2).Address(RowAbsolute:=False, ColumnAbsolute:=False)
Range("B22").Select
    Selection.Copy
    Sheets("Scenarios.New").Select
    Columns("A:A").Select

    Set f = Selection.Find(What:=Worksheets("Output").Range("B22").Value, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False)

    f.Select
    q = f.Address
    Set x = Cells.FindNext(After:=ActiveCell).Activate
    x.Select
    z = x.Address

    Range("F21:M21").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Output").Select
    Range("AFI35").Select
    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=True
End Sub

2 个答案:

答案 0 :(得分:5)

正如Andrew Cheong(和Chrismas007)评论的那样,问题在于你的Activate方法。

Range.Activate命令不返回对象(它只是激活某些内容),因此Set无法Range.Activate

您可能想要更改:

Set x = Cells.FindNext(After:=ActiveCell).Activate

为:

Set x = Cells.FindNext(After:=ActiveCell)
If Not x Is Nothing Then x.Activate

答案 1 :(得分:2)

您可以使用此

Dim x As Range
Dim f As Range
Set f = Selection.Find(What:=Worksheets("Output").Range("B22").Value, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False)

    f.Select
    q = f.Address
    Set x = Range("A:A").FindNext(f)
    x.Select