对于列循环中的单元格 – 根据循环中的位置指定相邻列单元格的值

我把放在一起的一个excel VBAmacros循环遍历所有在列I中使用的单元格,并检查单元格的值是否与一个单词相匹配。

如果这个词是匹配的,我想在列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的随机数….等等…

对不起,如果这里的措辞是混乱。 如果我知道术语,我可以通过谷歌find答案,而不必浪费你的时间:(

通过完全限定您的参考来避免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 

你可以使用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