【问题标题】:Copy and paste cells with random values复制和粘贴具有随机值的单元格
【发布时间】:2022-01-22 07:02:07
【问题描述】:

我的 VBA 代码是:

Sub hello()
Dim i As Long

Sheets("Sheet10").Select

For i = 3 To 101
Cells(i, 21).Value = Cells(2, 21).Value
Cells(i, 22).Value = Cells(2, 22).Value
Sheets("Sheet10").Calculate
Next i

End Sub

Cells(2,21)Cells(2,22) 包含一个随机公式,为简单起见,它可以是 =RAND()。我想:

  1. 复制Cells(2,21)Cells(2,22)
  2. Cells(2,21)Cells(2,22) 值粘贴到下一个i 行中;
  3. 刷新Cells(2,21)Cells(2,22)
  4. 重复直到i 等于101

我得到的是,当i=52 子错过第 3 点时,从i=52i=101 我得到相同的值。我该如何解决这个问题?

【问题讨论】:

  • 您是否有理由不在 VBA 中使用 RND
  • 是的,实际公式不是 rand,而且更复杂(就像其他随机单元格的加权平均值)
  • 当我设置一些单元格=RAND(),然后设置几百个其他单元格等于.Value,我的值都是不同的并且是随机的。即使没有调用Worksheet.Calculate,每个循环之后.Value 也会发生变化。我无法复制您的问题。
  • 这两个单元格是指其他工作表中其他随机单元格的加权平均值
  • "其他工作表中的其他随机单元格" - 但您只计算 Sheet10?也许您需要重新计算整个工作簿。

标签: excel vba excel-formula


【解决方案1】:

由于您似乎是从其他工作表中提取值,而不仅仅是 Sheet10,因此您可能需要执行更大的重新计算:

Sub hello()

    Dim i As Long
    
    With ThisWorkbook.Sheets("Sheet10")
        For i = 3 To 101
            .Cells(i, 21).Value = .Cells(2, 21).Value
            .Cells(i, 22).Value = .Cells(2, 22).Value
        Next i
        Application.Calculate 'note this affects all open workbooks
    End With 'fixed

End Sub

【讨论】:

  • 这对我不起作用,上面写着Compile error: Next without For
  • 抱歉 - 我用 Next i 代替了 End with - 在浏览器中编辑代码的危险...
【解决方案2】:

随机值列

  • 在每次迭代中,它将单列范围 (srrg (srrgAddress)) 的值写入二维基于一的数组 (dData) 的行,并重新计算包含 '随机公式”。
  • 它将数组中的值写入工作表,从范围第一列的一行 (dfRow) 中的单元格开始。
Option Explicit

Sub hello()
    
    Const srrgAddress As String = "U2:V2"
    Const dfRow As Long = 3
    Const dlRow As Long = 101
    
    Dim srrg As Range: Set srrg = Sheet10.Range(srrgAddress)
    Dim cCount As Long: cCount = srrg.Columns.Count
    
    Dim drCount As Long: drCount = dlRow - dfRow + 1
    Dim dData() As Variant: ReDim dData(dfRow To dlRow, 1 To cCount)
    
    Dim dr As Long
    Dim c As Long
    
    For dr = dfRow To dlRow
        For c = 1 To cCount
            dData(dr, c) = srrg.Cells(c).Value
        Next c
        srrg.Calculate
    Next dr
    
    Dim dfCell As Range: Set dfCell = srrg.Cells(1).EntireColumn.Rows(dfRow)
    Dim drg As Range: Set drg = dfCell.Resize(drCount, cCount)
    drg.Value = dData
        
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    相关资源
    最近更新 更多