【问题标题】:For Cell in Column Loop - Specify value for adjacent column cell based on location in loop对于列循环中的单元格 - 根据循环中的位置指定相邻列单元格的值
【发布时间】:2017-02-28 02:05:50
【问题描述】:

我整理了一个 excel VBA 宏,它循环遍历 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设置随机数......等......

对不起,如果这里的措辞令人困惑。如果我知道术语,我可能可以通过谷歌找到答案,而不必浪费你的时间:(

【问题讨论】:

    标签: vba excel


    【解决方案1】:

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

    【讨论】:

    • 很好的解决方案。谢谢@CallumDA。只是好奇,在这种特殊情况下我是否有理由避免引用 ActiveSheet?
    • @AlexRitter - ActiveSheet 可能是一个Chart
    • 如果您正在处理不同的工作表并从那里运行宏(例如,使用 Alt+F8),那么您会遇到一些麻烦。
    • 有道理。谢谢。
    • @CallumDA 嘿,伙计,我的脚本刚刚完成运行,我在“If cell.Value="Shure" 行上收到“运行时错误:13 类型不匹配”。知道为什么会这样是?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      相关资源
      最近更新 更多