VBA:如何传递包含在另一个子例程中定义的变量的字符串?

时间:2016-11-18 18:34:39

标签: vba excel-vba excel

我遇到了一个excel VBA编程问题。我有一张包含id列表(列A)和另外2列(level1(列B)和level2(列C))表示其类别。我需要做的是,在VBA中,循环遍历子组列表(group1,group2,group3),以便每次在level1和level2上应用过滤器字符串时,例如:group1 = And(B&CStr(r) = abc, C&CStr(r) = 123), group2 = And(B&Cstr(r) = xyz, C&CStr(r) = 789),其中变量& #34; r"是主子例程中定义的行号。

因为对于每个组,我需要对工作表中的每一行应用相同的过滤器并将满足条件的id保存到数组中,我将过滤器放在单独的 FUNCTION 中,返回选择组时的过滤字符串。我遇到的问题是变量" r"是定义的,只在主子程序中赋值,所以我得到一个未定义的"变量"定义每个组的过滤器的函数中的错误。如果我在过滤器中设置了包括函数中双引号的CStr(r)中的所有内容,那么" r"不会用作变量,也不会在主子程序中动态分配行号。

有没有办法以抽象的方式定义过滤器字符串,并让" r"仅在主子程序中动态分配?

以下是功能代码的示例:

Function getsectorlist_example() As Dictionary
Set sectorlist = New Dictionary
categoryname = "Group1"
level1 = "= " & """ABC"""
level2 = "= " & """123"""
level3 = "and(F" & CStr(r) & level1 & ", G" & CStr(r) & level2 & ")"
filter = level3
sectorlist.Add categoryname, filter
categoryname = "Group2"
level1 = "= " & """XYZ"""
level2 = "= " & """789"""
level3 = "and(F" & CStr(r) & level1 & ", G" & CStr(r) & level2 & ")"
filter(2) = level3
sectorlist.Add categoryname, filter`enter code here`
Set getsectorlist = sectorlist
End Function

以下是主要代码的示例:

Function Main_example(sectorfilter As Variant) As Dictionary

Dim ws_alldata As Worksheet
Dim seclist As Dictionary
Dim values(2) As Double
Dim r As Long, currentIDs As String, wgt As Double, ctr As Double
Dim fullfilter As String

Set ws_alldata = Sheets("Sheet1")
Set seclist = New Dictionary

r = 2
currentIDs = ws_alldata.Cells(r, 2)
  wgt = ws_alldata.Cells(r, 3)
  ctr = ws_alldata.Cells(r, 4)


ws_alldata.Activate

While Len(ws_alldata.Cells(r, 1)) > 0


    fullfilter = sectorfilter
    If Eval(fullfilter) = True Then

        If seclist.Exists(currentIDs) Then
            values(0) = wgt + seclist(currentIDs)(0)
            values(1) = ctr + seclist(currentIDs)(1)
            values(2) = values(1) / values(0)

            seclist.Remove (currentIDs)
        Else
            values(0) = wgt
            values(1) = ctr
            values(2) = values(1) / values(0)

        End If

        seclist.Add currentIDs, values

    End If

  r = r + 1
  currentIDs = ws_alldata.Cells(r, 2)
  wgt = ws_alldata.Cells(r, 3)
  ctr = ws_alldata.Cells(r, 4)

Wend

Set getseclistinsector = seclist

End Function

0 个答案:

没有答案