Excel VBA - 在End Sub之后保持变量相同

时间:2017-07-27 12:24:03

标签: excel vba variables

我有一些代码可以给我一些变量 - Champ。我希望能够运行这个程序,然后在我的下一个Sub()引用这些变量。代码是:

  Sub CreateUniqueList()
  Dim dict As Object, lastRow As Long, Champ, c
  Set dict = CreateObject("Scripting.dictionary")
  With Sheets("Raw Data")
      lastRow = .Cells(.Rows.count, "D").End(xlUp).row
      For Each c In .Range("D7:D" & lastRow).SpecialCells(xlCellTypeVisible)
        dict(c.text) = 0
      Next
  End With
  Champ = dict.Keys

  ' Now you have the "variables". To create the new sheet:
  With Sheets.Add(After:= Sheets(Sheets.Count))
    .Name = "Unique Champions"
    .Range("A2").Resize(dict.count).Value = Application.Transpose(dict.keys)
    .Range("A1").Value = Sheets("Raw Data").Range("D6").Value
  End With
End Sub


Sub Criteria ()
If (Cells(i, 2).Value = Champ3) Then...............................
End Sub

问题是,当我尝试运行" Sub Criteria"时,Champ3会返回值Empty。

我怎样才能使变量进入单独的程序?

由于

编辑:第二个Sub就是一个例子

1 个答案:

答案 0 :(得分:1)

尝试将其作为函数编写

Function CreateUniqueList() As Variant()
    Dim dict As Object, lastRow As Long, c

    Set dict = CreateObject("Scripting.dictionary")
    With Sheets("Raw Data")
        lastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
        For Each c In .Range("D7:D" & lastRow).SpecialCells(xlCellTypeVisible)
            dict(c.Text) = 0
        Next c
    End With
    CreateUniqueList = dict.keys
End Function
Sub Criteria()
    Dim Champ As Variant

    Champ = CreateUniqueList

    ' Now you have the "variables". To create the new sheet:
    With Sheets.Add(After:=Sheets(Sheets.Count))
        .Name = "Unique Champions"
        .Range("A2").Resize(UBound(Champ)).Value = Application.Transpose(Champ)
        .Range("A1").Value = Sheets("Raw Data").Range("D6").Value
    End With

    If IsInArray(Cells(i, 2).Value, Champ) Then

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