找到一个值并使用VBA返回同一行中的NEXT值

时间:2015-08-20 08:04:59

标签: excel-vba vba excel

我有数据集,其中"材料"并且始终显示相应的编号(在同一行中)。但是,它们不会总是出现在同一个单元格中。

我正在寻找的是一个VBA脚本:

  1. 找到表达式" Material",然后
  2. 查找相应的数字(同一行中的下一个值,不一定是相邻的单元格),然后
  3. 复制+粘贴某个单元格中的数字。
  4. 提前多多感谢!

    Uni YaMo

1 个答案:

答案 0 :(得分:0)

我的时间不多了,但我希望以下代码片段能让你开始:

Private Sub CommandButton1_Click()

Dim myCol As Long
Dim Val As Variant
Dim FoundMatCodes() As Variant

For intRow = 1 To 100
    On Error Resume Next
    MatCol = Worksheets("Tabelle1").Rows(intRow).Find(What:="Material", LookIn:=xlValues, LookAt:=xlWhole, _
             SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column

    ' found 'Material'
    If MatCol > 0 Then

        Dim r As Range
        Dim c As Range

        Set r = Rows(intRow)

        ' you may want to look at more cells
        For intCells = 1 To 10

            Set c = r.Cells(intCells)
            If (Not IsEmpty(c)) Then
                Debug.Print c.Value

                ' found numeric value
                If IsNumeric(c) Then

                    ' check if the array is already initialised
                    ' if not initialise with space for one element
                    If (Not FoundMatCodes) = -1 Then
                        ReDim FoundMatCodes(0)
                    ' array already been initialised, so initialise it 
                    ' with one more element than before, but
                    ' keep all previously added values
                    Else
                        ReDim Preserve FoundMatCodes(UBound(FoundMatCodes) + 1)
                    End If
                    ' just add the found value
                    FoundMatCodes(UBound(FoundMatCodes)) = c.Value
                    Exit For
                End If

            End If

        Next intCells

    End If

    MatCol = -1
Next intRow

' output to sheet Tabelle2
Worksheets("Tabelle2").Range("A1:A" + CStr(UBound(FoundMatCodes) + 1)) = WorksheetFunction.Transpose(FoundMatCodes)
End Sub

它在a列中查找“材料”。如果找到它,则在行中搜索数值。找到的第一个值存储在一个数组中。在循环之后,数组的内容被粘贴到工作表'Tabelle2'中。希望有所帮助。

关于转置的问题,请看看: http://www.excelfunctions.net/Excel-Transpose-Function.html

干杯