2015-04-29 15 views
2

我試圖將公共列鏈接在一​​起,但是當我單擊PolicyComponents Sheet中的一個單元格時,for循環不運行 - 它只是退出sub。For循環不運行在工作表中

代碼段:

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 
+1

您正在使用* name *作爲字符串類型變量,但將其分配給行號值。 Thi9s表示* name *是*「2」*而不是* 2 *,並且在需要數字時不能使用。 – Jeeped

+0

好吧我已經修復了,但是當我調試一行一行時,它只是完全跳過for循環。 @Jeeped –

+0

我不清楚下面的代碼修改是否解決了問題。如果你仍然需要一些調試幫助,你可以通過編輯添加對你的問題的任何修改嗎? – Jeeped

回答

2
  1. 您正在使用名稱作爲字符串類型變量,但將其分配給行號值。這意味着名稱是"2"而不是2,並且在需要數字時不能使用。將您的變量與保留字(如VBA的.Name)稱爲相同也不是一個好主意。
  2. 您正在使用步驟-1,但從開始,這意味着它永遠不會去任何地方。

這應該足以讓循環進行。

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去行計數,但使用i-1了一步,這意味着你指望向後,從未前往...Rows.Count

如果您想使用類似的步驟或使用Step 1向上計數(缺省值),則更改循環的順序,從Rows.Count變爲1