【问题标题】:VBA: How do you handle passing Sheet2!A:A through function parameters?VBA:您如何处理通过函数参数传递 Sheet2!A:A?
【发布时间】:2021-04-17 13:24:03
【问题描述】:

所以我知道 Sheets2!A:A 专门指 Sheet 2 工作簿中的整个 A 列。 但是,当它通过函数传递时,您实际上如何处理它?

Function Function1(cellValue As Variant, cellList As Range) As Variant
Dim cellContent As Variant
Dim list As Range
Dim i As Integer
cellContent = Sheets("Sheet1").Range(CStr(cellValue)).Value2
list = Range(cellList).Value2
For i = 1 To list
    If i = cellContent Then
        Function1 = "Found"
    Else
        Function1 = "Unfound"
    End If
Next i

结束函数

您将如何解析 Sheets2!A:A 以便它使用指定的工作表以及 A:A 中的值范围。 我正在使用一个函数,因此它被用户有效地传递为

=@Function1(A2,Sheet2!A:A)

【问题讨论】:

  • 函数的第二个参数应该是Range 对象,您可以根据需要使用它(尽管通常使用整个列效率低下)。
  • edit 包含minimal reproducible example 的问题。这应该包括一个函数,该函数表示您如何声明变量并表示您尝试对这些变量执行什么操作。
  • @ScottCraner 如果您手动更改值,这将起作用。但是,如果用户使用该函数而不是 =Function1(A5, Sheets2!B:B) 那么我将如何自动执行此操作?
  • @ScottCraner 道歉,我已经编辑了一个我正在尝试做的例子

标签: excel vba function parameters


【解决方案1】:

范围已经是一个范围:

Function Function1(cellValue As range, cellList As Range) As Variant
Dim cellContent As Variant
Dim list As Variant
Dim i As Long
cellContent = cellvalue.Value2
list = intersect(cellList.parent.usedrange,celllist).Value2
Function1 = "Unfound"
For i = 1 To ubound(list,1)
    If list(i,1) = cellContent Then
        Function1 = "Found"
        Exit Function
    End If
Next i
End Function

但这只是重新定义了 MATCH:

=IF(ISNUMBER(MATCH(A2,Sheet2!A:A,0)),"Found","Unfound")

【讨论】:

  • 哇,非常感谢,这非常有效!我必须阅读 Intersect 和 Ubound,因为我以前从未见过
  • @Eynos 请考虑标记为正确。 Intersect 只允许我们循环使用的内容而不是整个列,从而节省一些比较时间。 Ubound() 返回我们创建的变量数组中的项目数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 2016-08-18
相关资源
最近更新 更多