使用循环内的变量设置范围

时间:2014-01-27 21:13:30

标签: excel vba

我在AA列中列出了不同的名称,AB列中的名称相同但顺序不同,并且在列AC和AD中附加了一些随机数。我正在尝试做的事情:如果AA中的名称等于垂直名称,请检查AB中的名称是否等于水平。如果是这样,使用范围的交集来找到单元格(例如)乘以AC和AD的随机数。对整个名单进行此操作。名单的长度可以有所不同。

尝试将垂直设置为特定范围时出现错误,但是当我想在内部范围内使用变量时,我不确定将范围设置为外部。 如果您有其他提示,请分享,这可能不是我的最后一个错误或此代码的问题。

Sub match()

Dim ws As Worksheet
Dim namelist As Long
Dim vertical As Range
Dim horisontal As Range
Dim x As Long
Dim y As Long
Dim z As Long

Set ws = ThisWorkbook.Sheets("Sheet1")
'Set vertical = ?
'Set horisontal = ?
nameList = ws.Cells(Rows.Count, 23).End(xlUp).Row
verticalLength = ws.Cells(Rows.Count, 1).End(xlUp).Row
horisontalLength = ws.Cells(1, Columns.Count).End(xlToLeft).Column

For x = 2 To namelist
    hname = Cells(x, 27)
    vname = Cells(x, 28)
    For y = 2 To verticalLength
        vertical = Range(Cells(y, 2), Cells(y, 21)) '<---- Error 'object variable   or with block variable not set'
        If vname = Cells(y, 1) Then
            For z = 2 To horisontalLength
                horisontal = Range(Cells(2, z), Cells(21, z))
                If hname = Cells(2, z) Then
                isect = Application.Intersect(Range("vname"), (Range("hname")))
                isect.Select
                'rest of code
                End If
            Next
        End If
    Next
Next

End Sub

期望的结果:

enter image description here

1 个答案:

答案 0 :(得分:0)

Sub match()

Dim ws As Worksheet
Dim namelist As Range, vert As Range, hor As Range
Dim rw As Range
Dim hCell As Range, vCell As Range, fCell As Range

    Set ws = ThisWorkbook.Sheets("Sheet1")
    With ws
        Set vert = .Range(.Range("A2"), .Cells(Rows.Count, 1).End(xlUp))
        Set hor = .Range(.Range("B1"), .Cells(1, Columns.Count).End(xlToLeft))
        Set namelist = .Range(.Cells(2, 27), _
                              .Cells(Rows.Count, 27).End(xlUp)).Resize(, 4)
    End With

    For Each rw In namelist.Rows

        Set hCell = hor.Find(rw.Cells(1).Value, , xlValues, xlWhole)
        Set vCell = vert.Find(rw.Cells(2).Value, , xlValues, xlWhole)

        If Not hCell Is Nothing And Not vCell Is Nothing Then

            Set fCell = ws.Cells(vCell.Row, hCell.Column)
            fCell.Value = rw.Cells(3) * rw.Cells(4)

        End If

    Next rw

End Sub