2017-02-27 56 views
1

我已經放在一起了一個通過列I中所有已用單元循環的excel VBA宏,並檢查單元格的值是否與單詞匹配。對於列循環中的單元格 - 根據循環中的位置指定相鄰列單元格的值

如果字是一個比賽,我想在B列

這裏設置一個隨機數,1-5之間,在相鄰的單元格是我到目前爲止有:

Dim FLrange As Range 
Dim AllStockLastRow As String 
AllStockLastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1 
Set FLrange = Range("I2:I" & AllStockLastRow) 

For Each cell In FLrange 
    If cell.Value = "Shure" Then 
     Range("B2").Value = Int((5 - 1 + 1) * Rnd + 1) 
     Else 
    End If 
Next cell 

很明顯,這段代碼不起作用,因爲它只會繼續一遍又一遍地重置單元格B2的值。我不知道如何,但我希望代碼檢查I2的值,併爲B2設置隨機數值。然後檢查I3的值,並設置B3的隨機數....等等...

對不起,如果這裏的措辭令人困惑。如果我知道的術語,我大概可以找到通過谷歌的答案,而不是有由完全限定你的引用浪費你的時間:(

回答

4

避免ActiveSheet

Dim FLrange As Range 
Dim AllStockLastRow As String 

Dim ws As Worksheet 
Set ws = ThisWorkbook.Worksheets("Sheet1") 'your sheet name 

With ws 
    AllStockLastRow =.Cells(.Rows.Count, "A").End(xlUp).Row + 1 
    Set FLrange = .Range("I2:I" & AllStockLastRow) 
End With 

For Each cell In FLrange 
    If cell.Value = "Shure" Then 
     ws.Range("B" & Cell.Row).Value = WorksheetFunction.Randbetween(1,5) 
    End If 
Next cell 
+0

謝謝@CallumDA。只是好奇,是否有一個原因,爲什麼我應該避免在這種特定情況下引用ActiveSheet? –

+1

@AlexRitter - 'ActiveSheet'可以是一個'圖表' – Comintern

+1

如果你是工作的國王在另一張紙上,並從那裏運行宏(例如使用Alt + F8),那麼你會發現自己有些麻煩。 – CallumDA

1

你可以使用AutoFilter()

Sub main() 
    With ThisWorkbook.Worksheets("Sheet1") '<--| reference your sheet name 
     With .Range("I1:I" & .cells(.Rows.Count, "A").End(xlUp).Row) '<--| reference its column I range from row 1 (header) down to the last not empty row 
      .AutoFilter Field:=1, Criteria1:="Shure" '<--| filter column with "Shure" 
      If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then .Resize(.Rows.Count - 1).Offset(1, -7).SpecialCells(xlCellTypeVisible).Formula = "=Int((5 - 1 + 1) * Rand() + 1)" '<--| if any filtered cells other than headers then write the "random" formula in corresponding column B cells 
      .Parent.AutoFilterMode = False '<--| remove autofilter 
      .Offset(, -7).Value = .Offset(, -7).Value '<--| get rid of formulas and leave only values in column B 
     End With 
    End With 
End Sub 
相關問題