excel vba试验函数和数组

时间:2014-07-17 00:48:36

标签: arrays excel function vba excel-vba

我正在尝试一些事情:

有一个包含名称的列表,我想要做的是读取数组中的单元格值(此部分有效),而不是检查工作表中的每个单元格以及给定的单元格是否相同作为数组中的字符串,做一些事情。

但不幸的是我得到了#34;类型不匹配"错误。

聚苯乙烯。我知道这没有多大意义,我可以在服务器内部运行这个功能,但是相信我,我有我的理由。 : - )

编辑:修改了一些东西,现在它看起来像这样(现在我得到的对象并不支持这个方法的属性)

如果有帮助,你也可以尝试一下。您只需要添加一个名为" Servers"并在它下面写一些随机的单词。现在它应该写在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

2 个答案:

答案 0 :(得分:2)

我认为你可能在c中将c定义为一个范围,但是当服务器期望一个布尔值时,用c调用服务器。

答案 1 :(得分:2)

我认为你可以压缩你的功能:

首先,您需要将数组生成块包含在主子组中 将它包含在Function server 中会降低代码执行速度,因为它需要在每次调用 server 函数时生成数组

编辑1:现在已经过测试。我已经重新编写了你的​​功能并改进了你的功能。

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

这是新功能:(实际上,您不需要它,您可以直接在主Sub中调用匹配功能)

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

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