excel vba试验函数和数组

我正在试验一些东西:

有一个名称列表,我想要做的是读取数组中的单元格值(这部分工作)比运行检查工作表中的每个单元格,如果给定的单元格是一样的string在一个数组中,做一些事情。

但不幸的是我得到了“types不匹配”的错误。

PS。 我知道这没有多大意义,我可以在服务器function内部的东西,但相信我,我有我的理由。 🙂

编辑:修正了几件事,现在看起来像这样(现在我得到的对象不支持这个属性的方法)

如果有帮助,你也可以尝试。 你只需要添加一个名为“服务器”的单元格,在它下面写一些随机单词。 现在它应该在msgbox“ok”中写入x次,其中x是您在单元格下命名为“Servers”的单元格的行数,

1

'server name Function server(ByVal issrvname As String) Dim j As Integer Dim c As Range Dim x As Integer, y As Integer For Each c In Sheets("Topology").UsedRange.Cells Dim srvname() As String j = 0 If c.Cells.Value = "Servers" Then y = c.Column: x = c.Row + 1 Do Until IsEmpty(Cells(x, y)) ReDim Preserve srvname(0 To j) As String srvname(j) = Cells(x, y).Value x = x + 1 j = j + 1 Loop End If Next c For Each c In Sheets("Topology").UsedRange.Cells If IsInArray(c.Cell.Value, srvname) Then issrvname = True Else issrvname = False End If Next c End Function 

2

 Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1) End Function 

3

 Sub test() Dim c As Range For Each c In Sheets("Topology").UsedRange.Cells If server(c) = True Then MsgBox "ok" End If Next c End Sub 

我认为你可以浓缩你的function:

首先,您需要将您的数组生成块包含到您的主分支中。
将它包含在函数服务器中会减慢代码的执行速度,因为它需要在服务器函数的每次调用中生成数组

编辑1:这是现在在testing中尝试。 我已经重新编写了你的​​function,并提高了你的分数。

 Sub test() Dim j As Integer Dim c As Range, c1 As Range Dim x As Integer, y As Integer Dim i As Long '~~> added it just to check how many is shown in MsgBox For Each c In Sheets("Topology").UsedRange.Cells '~~> generate array if "Servers" is encountered If c.Value = "Servers" Then Dim srvname() As String j = 0 y = c.Column: x = c.Row + 1 With Sheets("Topology").UsedRange Do Until IsEmpty(.Cells(x, y)) ReDim Preserve srvname(j) srvname(j) = .Cells(x, y).Value x = x + 1 j = j + 1 Loop End With '~~> use the generated Array of values here i = 1 For Each c1 In Sheets("Topology").UsedRange.Cells If IsInArray(c1.Value, srvname) Then MsgBox "ok" & i i = i + 1 End If Next c1 End If Next c End Sub 

这里是新的function:(实际上,你不需要它,你可以直接在主Sub中调用Match函数)

 Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0)) End Function 

也许你这样做只是为了testing? 我只是认为用于生成数组的表单必须与要比较服务器名称的工作表不同。

我想这可能是你定义c作为范围在testing,但调用服务器与c当服务器期待一个布尔值。