引用UDF中的特定单元格

时间:2018-08-21 07:40:07

标签: vba excel-vba for-loop user-defined-functions

UDF目标:将范围的值与同一张纸上的特定单元格进行比较。

发生错误#Value!

我认为,设置此单元格ThisWorkbook.ThisWorksheet的通行证的问题。如何才能胜任?

Function Fav(Diapozon As Range) As Long
    Application.Volatile

    Dim n As Long

    For x = 1 To 4
        For y = 0 To 1
            If Diapozon.Value = ThisWorkbook.Thisworksheet.Cells(x + 29, y + 10).Value Or  _
               Diapozon.Offset(0, 1).Value = ThisWorkbook.Thisworksheet.Cells(x + 29, y + 10).Value Then
                n = 1
            End If
        Next y
    Next x

    Fav = n
End Function

1 个答案:

答案 0 :(得分:2)

正确。也许您是说Activesheet?

Public Function Fav(ByVal Diapozon As Range) As Long
    Application.Volatile
    Dim n As Long, x As Long, y As Long
    For x = 1 To 4
        For y = 0 To 1
            If Diapozon.Value = ThisWorkbook.ActiveSheet.Cells(x + 29, y + 10).Value Or Diapozon.Offset(0, 1).Value = ThisWorkbook.ActiveSheet.Cells(x + 29, y + 10).Value Then
                n = 1
            End If
        Next y
    Next x
    Fav = n
End Function

如果仅在表单中将其用作UDF,则删除表单参考:

Public Function Fav(ByVal Diapozon As Range) As Long
    Application.Volatile
    Dim n As Long, x As Long, y As Long
    For x = 1 To 4
        For y = 0 To 1
            If Diapozon.Value = Cells(x + 29, y + 10).Value Or Diapozon.Offset(0, 1).Value = Cells(x + 29, y + 10).Value Then
                n = 1
            End If
        Next y
    Next x
    Fav = n
End Function