vba - 使用vba的引用问题

标签 vba excel excel-formula

我有 3 列,标题为 A BC,如图所示,我想检查中的值是否A 列等于 B 列的 10%,如果是,我想将其设置为 C 列的值,如果不是,我想获取 B 列中 10% 的值。我在 sheet1 中,我想在 sheet2 中设置一个 VBA 按钮来运行代码。

这是代码:

Sub Macro1()
    Dim ws As Worksheet, lastrow As Long
    Set ws = Worksheets("sheet1")
    ws.Activate
    ActiveCell.Formula = "=IF(A2=B2*0.1, A2, B2*0.1)"
    lastrow = Range("A" & Rows.Count).End(xlUp).Row
    Range("C2").AutoFill Destination:=Range("C2:C" & lastrow), Type:=xlFillDefault
End Sub

我的问题是,如果我将鼠标指向 sheet1 中的 C2 并且只运行 vba 代码,它就会工作。如果我在 sheet2 并按下按钮,它将不起作用,它只是不显示任何数据。有没有办法根据我的条件为 C 列设置值?

worksheet

最佳答案

要使代码在 sheet1 上独立于事件工作表工作,您需要将 .Range 方法完全应用于 Worksheets("sheet1")对象。尝试下面的代码:

Sub Macro1()

    Dim lastrow As Long

    With Worksheets("sheet1")
        lastrow = .Range("A" & Rows.Count).End(xlUp).Row
        If lastrow = 1 Then
            MsgBox "No data"
            Exit Sub
        End If
        .Range("C2:C" & lastrow).Formula = "=IF(A2=B2*0.1, A2, B2*0.1)"
    End With

End Sub

为什么不更直接一些:始终将 C 列的值设置为等于 B 列的 10%?结果是一样的。

Sub Macro1()

    Dim lastrow As Long

    With Worksheets("sheet1")
        lastrow = .Range("A" & Rows.Count).End(xlUp).Row
        If lastrow = 1 Then
            MsgBox "No data"
            Exit Sub
        End If
        .Range("C2:C" & lastrow).Formula = "=B2*0.1"
    End With

End Sub

关于vba - 使用vba的引用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40411623/

相关文章:

arrays - 数组常量在 excel 中没有按预期工作

excel - 计算逗号分隔列表的第一个值和最后一个值之间的差异

vba - SAP的VBA声明结束

vb.net - 从VB.NET应用程序调用Excel时,如何使Excel显示在应用程序前面?

python - 尝试使用 Python 从 excel 电子表格中删除第一行

excel - InputBox 的工作表选择问题

excel - COUNTIFS 包括整列而不是单个项目

excel - 运行时错误 '1004' - 对象“_Global”的方法 'Range' 失败

arrays - 如何更改数组vba中的现有数据

vba - Word 2007 VBA - 使一些文本变为粗体和其他斜体