[英]excel vba selecting cells
I have to fill several comboboxes depending on selected values in other comboboxes. 我必须根据其他组合框中的选定值来填充几个组合框。 What I want is to fill the boxes with activities for a selected name. 我想要的是用所选名称的活动填充框。 I compare if a certain name is in a row and then use offset to get the activity name and write it to an array. 我比较是否在行中使用某个名称,然后使用offset获取活动名称并将其写入数组。 It is not working probably has something to do with offset or maybe the merging of activity cells is a problem. 它不起作用可能与偏移量有关,或者可能是活动单元的合并是一个问题。 Here is my code: 这是我的代码:
Function FindingActivities(ExpName)
Dim ActNames(500) As String
Dim i As Integer
Dim CurrContent As String
For Each cell In Range("B7").EntireColumn.cells
If cell.Value <> "" Then
If ExpName = cell.Value Then
CurrContent = Left(cell.Offset(0, -1).Value, 2)
If CurrContent = "Ac" Then
ActNames(i) = cell.Offset(0,-1).Value
i = i + 1
End If
End If
End If
Next cell
FindingActivities = ActNames()
End Function
This is the code to fill the combobox: 这是填充组合框的代码:
Private Sub ComboBox1_Change()
Dim ExpName As String
ExpName = ComboBox1.Value
Dim ActNames() As String
ActNames = FindingActivities(ExpName)
For i = 0 To UBound(ActNames)
If ActNames(i) <> "" Then
ComboBox3.AddItem ActNames(i)
End If
Next
End Sub
Anyone has an idea? 有人有主意吗?
UPDATE : Rewritten for clarity 更新 :为清楚起见重写
It's a little unclear where you are stuck, but I offer a rewrite that should work well: 尚不清楚您在哪里卡住,但我提供了一个重写,应该可以正常工作:
Here's the code: 这是代码:
Private Sub ComboBox1_Change()
Dim ExpName As String
ExpName = ComboBox1.Value
Dim ActNames As Variant
ActNames = FindingActivities(ExpName)
'Add this so you aren't just adding results upon results
ComboBox3.Clear
For i = LBound(ActNames) To UBound(ActNames)
ComboBox3.AddItem ActNames(i)
Next
End Sub
... ...
Function FindingActivities(ByVal ExpName As String)
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")
Dim i As Long
Dim cell As Range
Dim varray As Variant
varray = Range("A1:B" & Range("B" & Rows.Count).End(xlUp).Row).Value
For i = 1 To UBound(varray, 1)
If Len(varray(i, 2)) <> 0 Then
If varray(i, 2) = ExpName Then
If Left$(varray(i, 1), 2) = "Ac" Then
dict.Add i, varray(i, 1)
End If
End If
End If
Next
FindingActivities = dict.items
End Function
Basically using a string array of fixed length on a column of unfixed lenght is asking for trouble. 基本上,在长度不固定的列上使用固定长度的字符串数组会带来麻烦。 It's bad for memory, slow, and can cause bugs. 这对内存不利,速度慢,并可能导致错误。 Dictionaries are just like collections except you can filter to unique entries only if you like (which I did not in this case) and output the keys or items as an array. 字典就像集合一样,只是字典只有在您愿意时才可以过滤到唯一条目(在这种情况下我不喜欢),然后将键或项输出为数组。 Very effecient. 非常有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.