对象'_Worksheet'的方法'范围'失败

时间:2017-11-03 14:50:49

标签: excel vba

直到现在我才从未遇到过这个问题。请查看下面的代码,它位于工作簿中的模块上(不是工作表上的代码),代码在尝试设置范围时会中断。

Private Sub UpdateTickerList()
    Dim MyWS As Worksheet
    Dim a, b, c As Integer
    Dim NewStockRng As Range
    Dim RealTickFeed As Range
    'On Error Resume Next (i took this out to get the error)
    'initializes variables
    a = 0
    b = 0


    'defines the worksheet we are going to work on
    Set MyWS = Workbooks("Portfolio.xlsm").Worksheets("Feed")
    'finds last row
    b = MyWS.Range("a10000").End(xlUp).Row + 1
    'finds how large is the new stock universe
    a = 8 'UBound(NPSeCompran)

    'defines a new range in which to copy the new symbols
    Set NewStockRng = MyWS.Range(Cells(b, 1), Cells(b + a - 1, 1)) 'i need to 
    'use b+a-1 to reflect the fact that if i
    'have row97 as my first row and 11 elements then i need to count row 97 
    'as#1, otherwise i end up with one more row
    'copies the stocks to the range
    NewStockRng.value = Application.Transpose(NPSeCompran)

    'now sort the list
    Set RealTickFeed = MyWS.Range("a3").CurrentRegion
    RealTickFeed.Sort key1:=MyWS.Range("a3"), Header:=xlYes

    'now get rid of duplicates
    RealTickFeed.RemoveDuplicates Columns:=Array(1, 9), Header:=xlYes

    ErrorHandler:
End Sub

1 个答案:

答案 0 :(得分:3)

我会在Cells()上添加

Set NewStockRng = Range(MyWS.Cells(b, 1),MyWS.Cells(b + a - 1, 1))

(可能还有其他问题)

修改#1:

这是一个简单的例子:

Sub qwerty()
    a = 12
    b = 15
    Sheets("Sheet2").Activate
    Set MyWS = Worksheets("Sheet1")

    Set NewStockRng = Range(MyWS.Cells(b, 1), MyWS.Cells(b + a - 1, 1))

    MsgBox NewStockRng.Address(o, o) & vbCrLf & NewStockRng.Parent.Name
End Sub

enter image description here

修改#2:

关键问题是Cells()本身已经很小。因此:

Range(whatever.Cells(1,1), whatever.Cells(3,3))

完全符合资格。