简体   繁体   中英

VBA - assigning the calculated value to a cell in different sheet

I have written a code to calculate a cost from one sheet of a workbook. after calculating I want that value to appear on another sheet of same workbook

Sub cost()

    Dim irow As Integer
    Dim pointer1 As Single
    Dim Kgl_PG_Campaign As Single
    Kgl_PG_Campaign = 0
    pointer1 = 0
    irow = 2
    Do Until Cells(irow, 3).Value = ""
        If Worksheets("ws2").Cells(irow, 11).Value = "Kagal" And Cells(irow, 12).Value = "PG" And Cells(irow, 24).Value = "Campaign" Then
            pointer1 = Cells(irow, 29).Value
            Kgl_PG_Campaign = Kgl_PG_Campaign + pointer1
        End If
    irow = irow + 1
    MsgBox Kgl_PG_Campaign
    Worksheets("COPQ_online").Range("C7").Value = Kgl_PG_Campaign
    Loop


End Sub

Error - run time error 9 - script out of range .

Please help

maybe you are after something like this:

Option Explicit

Sub cost()
    Dim irow As Long
    Dim Kgl_PG_Campaign As Single

    Kgl_PG_Campaign = 0
    irow = 2
    With Worksheets("ws2")
        Do Until Cells(irow, 3).Value = ""
            If .Cells(irow, 11).Value = "Kagal" And .Cells(irow, 12).Value = "PG" And .Cells(irow, 24).Value = "Campaign" Then
                Kgl_PG_Campaign = Kgl_PG_Campaign + .Cells(irow, 29).Value
            End If
            irow = irow + 1
            MsgBox Kgl_PG_Campaign
        Loop
    End With
    Worksheets("COPQ_online").Range("C7").Value = Kgl_PG_Campaign
End Sub

where I assumed that you want to write in Worksheets("COPQ_online") after you looped through "ws2" column "C" cells from row three down to the one preceeding the first empty cell

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