如何找到给定行的不同列值?

时间:2013-06-07 16:16:46

标签: excel vba excel-vba

我在尝试学习其他语言的恐龙后学习VBA。我正在进行的项目并不多,主要是概念验证或培训练习。

我有一个Excel表,其中包含“Department”,“List Markup”,“A Markup”,“B Markup”和“C Markup”列。我有一个表单,用户选择部门,然后输入成本。我想拿部门,找到那一行,拉出标记的值,并向用户显示列表,A,B和C定价。向回答this问题的Chris Neilsen大声疾呼。遗憾的是,它帮助不够。我重写了他的代码,但通过调试我发现它并没有真正占用任何行。我已经知道我需要哪些列,而不是行。

基本上:

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

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

2 个答案:

答案 0 :(得分:1)

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

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

假设列A包含deparment名称,departmentName是您要搜索的部门的名称。最后的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功能。

答案 1 :(得分:0)

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

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
相关问题