2012-04-27 32 views
1

我已經寫了一個宏來返回一個單元格中的特定值基於其他兩個單元格的連接值的查找。此宏可能需要在30列的每一列中運行。有沒有一種方法可以循環使用,以便我不必輸入30個變體?需要找到一種方法來循環這個宏通過其他列

這裏是我引用的代碼段:

Cells.Select 
ActiveWorkbook.Worksheets("Vendor Request").Sort.SortFields.Clear 
ActiveWorkbook.Worksheets("Vendor Request").Sort.SortFields.Add Key:=Range(_ 
    "F2:F" & LR2), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _ 
    xlSortNormal 
With ActiveWorkbook.Worksheets("Vendor Request").Sort 
    .SetRange Range("A1:BK" & LR2) 
    .Header = xlYes 
    .MatchCase = False 
    .Orientation = xlTopToBottom 
    .SortMethod = xlPinYin 
    .Apply 
End With 
If Cells(2, 6).Value <> "" Then 
Range("G2").Select 
ActiveCell.FormulaR1C1 = _ 
    "=CONCATENATE(""Example: "",IF(ISNA(VLOOKUP(CONCATENATE(RC[-4],""; "",RC[-1]),'Sample Data'!C[-6]:C[-2],5,FALSE)),"""",VLOOKUP(CONCATENATE(RC[-4],""; "",RC[-1]),'Sample Data'!C[-6]:C[-2],5,FALSE)))" 
If Cells(3, 6).Value <> "" Then 
Range("G2").Select 
Selection.AutoFill Destination:=Range("G2:G" & Range("F" & Rows.Count).End(xlUp).Row) 
Else 
End If 
Columns("G:G").Select 
Selection.Copy 
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ 
    :=False, Transpose:=False 
Else 
End If 

提前感謝!

編輯:終於得到它的工作。以下是我結束了:

Cells.Select 
    ActiveWorkbook.Worksheets("Vendor Request").Sort.SortFields.Clear 
    ActiveWorkbook.Worksheets("Vendor Request").Sort.SortFields.Add Key:=Columns(_ 
     j - 1), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _ 
     xlSortNormal 
    With ActiveWorkbook.Worksheets("Vendor Request").Sort 
     .SetRange Range("A1:BK" & LR2) 
     .Header = xlYes 
     .MatchCase = False 
     .Orientation = xlTopToBottom 
     .SortMethod = xlPinYin 
     .Apply 
    End With 
    Dim LRj As Long 
    With Sheets("Vendor Request") 
    LRj = .Cells(.Rows.Count, j - 1).End(xlUp).Row 
    End With 
    If Cells(2, j - 1).Value <> "" Then 
    Cells(2, j).Select 
    ActiveCell.FormulaR1C1 = _ 
    "=CONCATENATE(""Example: "",IF(ISNA(VLOOKUP(CONCATENATE(c3,""; "",C[-1]),'Sample Data'!c1:c6,5,FALSE)),"""",VLOOKUP(CONCATENATE(c3,""; "",C[-1]),'Sample Data'!c1:c6,5,FALSE)))" 
    If Cells(3, j - 1).Value <> "" Then 
    Cells(2, j).Select 
    Selection.AutoFill Destination:=Range(Cells(2, j), Cells(LRj, j)) 
    Else 
    End If 
    Columns(j).Select 
    Selection.Copy 
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ 
     :=False, Transpose:=False 
    Application.CutCopyMode = False 
    Else 
    End If 
    Next j 

回答

1

你可以改變... Range("G2:G ...到Range("G2:AKColumns("G:G"裏面一個Columns("G:AK"

Range(Cells(2,j),Cells(...,j)) for循環

+0

我只需要它來運行在其他列中。我希望有一種方式來循環。我試圖使用「For j = 6 To 62 Step 2」之類的東西,然後用j替換所有「G」的實例。這聽起來正確嗎? – user955289 2012-04-27 15:32:27

+0

@ user955289看到我的更新 – Aprillion 2012-04-27 15:37:43