如何find给定行的不同列值?

我想在其他语言成为恐龙后学习VBA。 我正在从事的项目并不多,主要是一个概念validation或培训练习。

我有一个Excel表,列“部门”,“列表标记”,“标记”,“B标记”和“C标记”。 我有一个用户select部门的表格,然后input成本。 我想采取部门,find那一行,拉出标记的价值,并向用户显示列表,A,B和C定价。 大声呼喊回答这个问题的Chris Neilsen。 它帮助,不幸的是还不够。 我重写了他的代码,但通过debugging,我发现它不是真的拿起任何行。 我已经知道我需要什么列,而不是行。

基本上:

User selects department User enters item cost Search column 1 ("Department") for a match (Match should exist, because this column is used to populate the first ComboBox When the match is found, get the row. Once the row is found, get the markups from the corresponding columns Output cost times markup for all four prices 

我会告诉你我的代码,哪里是失败的,但是我所做的每一个变化都是一个不同的错误。 我想我坐在这里试图重新发明轮子。

如果您的部门条目是唯一的,您可以获得该行执行以下操作:

 deptRow = Application.WorksheetFunction.Match(departmentName, Range("A:A"), 0) 

假设列A包含部件名称,部门名称是您要search的部门的名称。 最后的0必须告诉Excel仅查找完全匹配。

实际上你可以调用任何标准的工作表函数。 只需调用Application.WorksheetFunction.functioname()

然后你可以得到单元格的值并添加它们:

 markup = Cells(deptRow,2)+Cells(deptRow,3)+Cells(deptRow,4)+Cells(deptRow,5) 

其中2,3,4,5对应于B,C,D,E列。

你也可以使用Application.WorksheetFunction.Sum函数。

一个简单的循环就足够了。

 Dim strTargetValue As String strTargetValue = "" 'Simulates a search for "Test 2" Dim strSearchValue As String strSearchValue = "Test 2" Dim intRowNumber As Integer intRowNumber = 0 Dim intRowCursor As Integer intRowCursor = 1 Dim bolStopLooking As Boolean bolStopLooking = False 'Loop until we find the row or find an empty cell. Do Until intRowNumber > 0 Or bolStopLooking = True 'Assumes first column is "Department" If Rows(intRowCursor).Cells(1).Value = strSearchValue Then intRowNumber = intRowCursor End If If Len(Rows(intRowCursor).Cells(1).Value) = 0 Then bolStopLooking = True End If intRowCursor = intRowCursor + 1 Loop 'Assumes Second Column is target value. Do same for other cells from row that you need. If intRowNumber > 0 Then strTargetValue = Rows(intRowNumber).Cells(2).Value End If