for循环不在工作表

时间:2015-04-29 07:41:11

标签: vba excel-vba excel

我尝试将常用列链接在一​​起,但是当我单击PolicyComponents Sheet中的单元格时,for循环不会运行 - 它只是退出sub。

代码段:

Sub LinkName()

Dim i As Long
Dim ShtUsedRange, ShtUsedRangeCol
Dim name As String
Dim name1 As String
Dim lookup_range As Range
Dim box


ShtUsedRange = ActiveSheet.UsedRange.Rows.Count
'Count the used rows in the Activesheet
ShtUsedRangeCol = ActiveSheet.UsedRange.Columns.Count
'Count the used Column in the Activesheet

name = ActiveCell.Row
'Row of the Selected Cell

name1 = ActiveSheet.Cells(name, 1).Value
'name of the row selected

'MsgBox name1

Set lookup_range = ThisWorkbook.Sheets("PolicyDetails").Range("a1:z5000")
'set the range of the Policy details to search from

box = Application.WorksheetFunction.VLookup(name1, lookup_range, 1, False)
'to match the name to the policy details

MsgBox box

For i = 1 To ThisWorkbook.Sheets("PolicyComponents").Rows.Count Step -1

If ThisWorkbook.Sheets("PolicyComponents").Cells(i, 1).Value = box Then
 ThisWorkbook.Sheets("Policy Viewer").Cells(16, 2).Value = ThisWorkbook.Sheets("PolicyComponents").Cells(i, 4).Value

End If    
Next i    
End Sub

2 个答案:

答案 0 :(得分:2)

  1. 您使用name作为字符串类型变量,但为其指定行号值。这意味着名称为"2"而不是2,并且在需要数字时无法使用。将变量称为与VBA .Name之类的保留字相同也绝不是一个好主意。
  2. 您正在使用 Step -1 ,但从 1 开始,这意味着它永远不会去任何地方。
  3. 这应该足以让循环继续。

    Sub LinkName()
    
        Dim i As Long
        Dim ShtUsedRange, ShtUsedRangeCol
        Dim rw As Long
        Dim lu As Variant
        Dim lookup_range As Range
        Dim box As Variant
    
    
        'Count the used rows in the Activesheet
        ShtUsedRange = ActiveSheet.UsedRange.Rows.Count
    
        'Count the used Column in the Activesheet
        ShtUsedRangeCol = ActiveSheet.UsedRange.Columns.Count
    
        'Row of the Selected Cell
        rw = ActiveCell.Row
    
        'name of the row selected
        lu = ActiveSheet.Cells(rw, 1).Value
    
        'MsgBox lu
    
        'set the range of the Policy details to search from
        Set lookup_range = ThisWorkbook.Sheets("PolicyDetails").Range("a1:z5000")
    
        'there is no error control here if there is no match
        'to match the name to the policy details
        box = Application.WorksheetFunction.VLookup(lu, lookup_range, 1, False)
    
        MsgBox box
    
        For i = 1 To ThisWorkbook.Sheets("PolicyComponents").Rows.Count Step 1
            If ThisWorkbook.Sheets("PolicyComponents").Cells(i, 1).Value = box Then
                ThisWorkbook.Sheets("Policy Viewer").Cells(16, 2) = _
                  ThisWorkbook.Sheets("PolicyComponents").Cells(i, 4).Value
                'probably best to exit hte loop here unless you want to try and catch other matches
                'Exit For
            End If
        Next i
    
    End Sub
    

    我重命名了两个变量。我不知道你实际上想要查找的值(数字/文本/日期)的性质,所以我把它留作变种。

答案 1 :(得分:1)

你的循环是从1到行数,但使用i,步长为-1,这意味着你向后计数,永远不会进入...Rows.Count

如果您想使用这样的步骤或使用Rows.Count计算一个(默认值),请更改循环的顺序,从1转到Step 1。< / p>