简体   繁体   中英

reference issue using vba

I have 3 columns, with headers A B & C as shown at the picture, and I want to check if the value in column A is equal to 10% of column B , if yes, I want to set it to be the value for column C , if not, I want to get 10% of values in column B . I am in sheet1 and I want to set a VBA button in sheet2 to run the codes.

Here is the code:

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

My issues is if I point my mouse at C2 in sheet1 and I just run the vba codes, it will work. If I am at sheet2 and pressing the button, it won't work, it just doesn't show any data. Is there a way to set values to column C based on my criteria?

工作表

To make the code working on sheet1 independently of active sheet is, you need to apply .Range method exactly to Worksheets("sheet1") object. Try the below code:

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

Why not to be more straightforward: always set the value to column C equal to 10% of column B ? The result will be the same.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM