Consulting

Results 1 to 5 of 5

Thread: Adding two cells together

  1. #1
    VBAX Regular
    Joined
    Oct 2008
    Posts
    16
    Location

    Adding two cells together

    Hi,

    I am supposed to write a macro for work and until I get more familiar with VBA I decided to just write one that did something simple.

    By using the Record Macro and some example scripts I got some of it down. But for some reason my code doesn't work. Here's what I have:


    Option Explicit
    
    Sub Addition()
    Dim Add As Integer
    Dim var1 As Integer
    Dim var2 As Integer
    var1 = Range("A2").Select
    var2 = Range("B2").Select
    Add = var1 + var2
    Range("C2").Select
    ActiveCell.FormulaR1C1 = Add
    End Sub

    It displays -2 in cell 'C2' instead of the correct answer which would be 30
    (A2 = 20, B2 = 10)
    Last edited by Aussiebear; 04-14-2023 at 04:06 PM. Reason: Adjusted the code tags

  2. #2
    This will give you 30 as an answer.

    Sub Addition()
         
        Dim Add As Integer
        Dim var1 As Integer
        Dim var2 As Integer
        var1 = Range("A2").Value
        var2 = Range("B2").Value
        Add = var1 + var2
        Range("C2").Select
        ActiveCell.FormulaR1C1 = Add
         
    End Sub

  3. #3
    VBAX Regular
    Joined
    Oct 2008
    Posts
    16
    Location
    Thanks!

  4. #4
    Moderator VBAX Wizard lucas's Avatar
    Joined
    Jun 2004
    Location
    Tulsa, Oklahoma
    Posts
    7,323
    Location
    Alternative:

    Sub add()
    Range("C2").Value = Range("A2").Value + Range("B2").Value
    End Sub

    Be sure to mark your thread solved using the thread tools at the top of the page when you are sure you have an answer.
    Last edited by Aussiebear; 04-14-2023 at 04:07 PM. Reason: Adjusted the code tags
    Steve
    "Nearly all men can stand adversity, but if you want to test a man's character, give him power."
    -Abraham Lincoln

  5. #5
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Use Excel

    Sub add() 
        Range("C2").FormulaR1C1 = "=SUM(RC[-2]:RC[-1])" 
    End Sub
    Last edited by Aussiebear; 04-14-2023 at 04:07 PM. Reason: Adjusted the code tags
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •