我已经整理了一个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 ......等的随机数....
对不起,如果这里的措辞令人困惑。如果我知道这个术语,我可以通过谷歌找到答案,而不必浪费你的时间:(
答案 0 :(得分:5)
通过完全限定您的参考资料来避免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
答案 1 :(得分: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