[英]Comparing values of cells in a column with ComboBox value input by user
I am not able to compare the values of a cells in a column with combobox value input. 我无法将列中单元格的值与组合框值输入进行比较。
I have 2 workbooks tests (contains ComboBox2) and test1 (contains a column whose cells are compared with ComboBox2.value) 我有2个工作簿测试 (包含ComboBox2)和test1 (包含一个列,其单元格与ComboBox2.value进行比较)
I have a for loop to achieve this. 我有一个for循环来实现这一目标。
For i = 1 To LastRow
If wkbSource.Worksheets(sheet_no).Cells(i, 1) = ComboBox2.Value Then
'do something
End If
Next i
I have debugged the code and I understood that if
statement
doesn't execute even after a match. 我调试了代码,我理解if
statement
即使在匹配后也不会执行。
How can I fix it ? 我该如何解决?
EDIT : 编辑:
Also I would like to know how you can add two cell values because directly adding it is showing incorrect output. 另外我想知道如何添加两个单元格值,因为直接添加它会显示不正确的输出。 For example 例如
wkbSource.Worksheets(sheet_no).Cells(i, 1) + wkbSource.Worksheets(sheet_no).Cells(i, 3)
This was due (once again) to the Variant Comparison Curse . 这是(再次)到变体比较诅咒 。 See in particular the "UPDATE 4" of that question. 特别参见该问题的“更新4” 。
If wkbSource.Worksheets(sheet_no).Cells(i, 1) = ComboBox2.Value Then
This compares two Variant
s. 这比较了两个Variant
。 But, when the cell contains a number, and is not explictly formatted as Text
, not preceded by '
when entered. 但是,当单元格包含一个数字,并且没有明确地格式化为Text
,前面没有'
输入时。 Excel will consider it as a number and so it's .Value
will be a number Variant
. Excel会将其视为一个数字,因此它的.Value
将是一个数字Variant
。 On the other hand, Combobox2.Value
retuned a text Variant
, so the comparison failed! 另一方面, Combobox2.Value
重新调整了文本Variant
,因此比较失败了!
When comparing two Variant
variables, these operations will fail: 比较两个Variant
变量时,这些操作将失败:
2 = "2" ' False
3 > "2" ' False
Therefore, the solution in your particular situation is to force comparing texts, using the .Text
properties of the control and the cell. 因此,在您的特定情况下,解决方案是使用控件和单元格的.Text
属性强制比较文本。 Here's how you would - for example - sum up cells that match your query: 以下是您将如何 - 例如 - 总结与您的查询匹配的单元格:
For i = 1 To LastRow
If Trim(wkbSource.Worksheets(sheet_no).Cells(i, 1).Text) = Trim(ComboBox2.Text) Then
'do something
if IsNumeric(wkbSource.Worksheets(sheet_no).Cells(i, 1).Value2) Then _
mySum = mySum + wkbSource.Worksheets(sheet_no).Cells(i, 1).Value2
End If
Next i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.