VBA - 难以使用数组

时间:2018-02-05 16:08:16

标签: excel vba excel-vba autofilter

我正在尝试编写一个宏来打开另一个工作表,并在单击另一个工作表上的元素时自动过滤它。它的工作方式如下:

Sub Link_erzeugen()
'
' Link_erzeugen Makro
'
' Tastenkombination: Strg+Umschalt+L
'
    Dim CostFactor As String
    CostFactor = ActiveCell

    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'2017 P&L'!A1", TextToDisplay:=CostFactor

    Dim CostElements As Variant
    Dim CostElementsNoSpaces As Variant
    CostElements = Array()
    CostElementsNoSpaces = Array()

    Dim MatchedCostFactors As String

    Dim myKey As Worksheet
    Set myKey = Worksheets("Allocation Key")
    Dim i As Long

    Dim strRange As String
    Dim Elements As String
    For i = 1 To 26
        With myKey
            strRange = Chr(i + 64) & "8"
             MatchedCostFactors = Range(strRange).Value
               If StrComp(MatchedCostFactors, CostFactor, vbTextCompare) = 0 Then
                    Elements = Chr(i + 64) & "9:" & Chr(i + 64) & "22"
                   CostElements = Sheets("Allocation Key").Range(Elements).Value
                   Exit For
               End If
        End With
    Next i

    ReDim CostElementsNoSpaces(0 To 0)
    Dim Counter As Long
    Dim NoBlankSize As Long
    NoBlankSize = 0

    For Counter = LBound(CostElements) To UBound(CostElements)
        If CostElements(Counter, 1) <> "" Then
            NoBlankSize = NoBlankSize + 1
            CostElementsNoSpaces(UBound(CostElementsNoSpaces)) = CostElements(Counter, 1)
            ReDim Preserve CostElementsNoSpaces(0 To UBound(CostElementsNoSpaces) + 1)
        End If
    Next Counter



    Dim PandL As Worksheet
    Set PandL = ActiveWorkbook.Worksheets("2017 P&L")
    With PandL
       .Range("D1").AutoFilter _
      Field:=1, _
      Criteria1:=CostElementsNoSpaces, _
      Operator:=xlFilterValues, _
      VisibleDropDown:=True
    End With

    Worksheets("2017 P&L").Activate

End Sub

当用户单击第一张工作表上的成本元素时,宏会在不同的工作表(分配键)上搜索成本要素的名称,并在将其作为数组找到后,取名称下面的值。然后我想用数组中的值自动过滤2017 P&amp; L表。

到目前为止,我遇到了很多问题,因为我对VBA很新,所以我会感激一些帮助。

就目前而言,我面临的错误是返回运行时错误1004,表明范围对象的自动过滤方法失败。我一直在尝试一些事情,但我真的不确定如何解决这个问题。可能是CostElementsNoSpaces数组只有垂直值,而自动过滤方法需要水平值,所以转发变量可能会有所帮助。但是,即使我只输入一个值作为过滤条件,我也会返回运行时错误。

有没有人知道我怎么能接近这个?

非常感谢!

莱昂

0 个答案:

没有答案