在将其指定为“byref工作表”之前选择或激活工作表?

时间:2014-04-08 15:02:24

标签: excel-vba vba excel

我有一个问题。我有以下类属性:

Private myLanguage As String

Public Property Get Language() As String
Language = myLanguage
End Property
Public Property Let Language(ByVal Value As String)
myLanguage = Value
End Property

Public Property Get LanguageColumn(ByRef LanguageWs As Worksheet, _
ByVal LanguageRow As Integer) As Integer
LanguageColumn = LanguageWs.Range(Cells(LanguageRow, 1), Cells(LanguageRow, 250)).Find(myLanguage).Column
End Property

调用我使用

Dim cls as new Cls1
cls.LanguageColumn(ThisWorkbook.Worksheets(1), 1)

我收到错误:

  

" 1004' - 方法'范围'对象' _Workseet'失败

当我将执行代码更改为:

Dim cls as new Cls1
Worksheets(1).Activate
cls.LanguageColumn(ThisWorkbook.Worksheeets(1), 1)

它正在发挥作用。任何人都可以告诉我为什么以及在使用.Activate时我是否总是必须使用.Selectbyref worksheet

1 个答案:

答案 0 :(得分:0)

您应该完全符合Cells的资格,即指定Cells所属的工作表。变化:

LanguageColumn = LanguageWs.Range(Cells(LanguageRow, 1), Cells(LanguageRow, 250)).Find(myLanguage).Column

LanguageColumn = LanguageWs.Range(LanguageWs.Cells(LanguageRow, 1), LanguageWs.Cells(LanguageRow, 250)).Find(myLanguage).Column

或更好:

With LanguageWs
    LanguageColumn = .Range(.Cells(LanguageRow, 1), Cells(.LanguageRow, 250)).Find(myLanguage).Column
End With

另外,我建议您将ByVal LanguageRow As Integer更改为ByVal LanguageRow As Long以及返回您的媒体资源类型(因为Integer仅为32768时的最大值)。

实际上我会使用这个来确保可靠性(如果找不到myLanguage):

Public Property Get LanguageColumn(ByRef LanguageWs As Worksheet, _
       ByVal LanguageRow As Long) As Long
    Dim rng As Range

    With LanguageWs
        Set rng = .Range("A" & LanguageRow).Resize(, 250).Find(myLanguage)
    End With

    If Not rng Is Nothing Then
        LanguageColumn = -1
    Else
        LanguageColumn = rng.Column
    End If
End Property