我有 3 列,标题为 A
B
和 C
,如图所示,我想检查中的值是否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
列设置值?
最佳答案
要使代码在 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/