|
-
Aug 26th, 2012, 03:31 AM
#1
Thread Starter
Hyperactive Member
Set range then add values to existing values
I have code the defines a dynamic range then for all cells in that range I want to add the same value but I do NOT want to overwrite the existing numbers. The following code is similar to what I currently have except the range is not dynamic as this is just an example:
Code:
Sub test()
Dim rng As Range
Dim mynumber As Integer
mynumber = 10
Set rng = Range(Cells(1, 1), Cells(10, 1))
rng.value = mynumber
End Sub
Obviously this just makes all cells in range rng equal to 10 (overwrites existing values). I also tried:
Code:
Sub test()
Dim rng As Range
Dim mynumber As Integer
mynumber = 10
Set rng = Range(Cells(1, 1), Cells(10, 1))
rng = rng + mynumber
End Sub
But just get a "type mismatch" error. I was playing around with some way of copying the existing numbers in the range, pastespecial values somewhere else, then do rng = mynumber then copy/pastespecial add values the original numbers back but this seems a very messy way of doing things. There must be a simple way of just adding to the existing values that I am missing!
Thanks
-Rob
http://www.sudsolutions.com
-
Aug 26th, 2012, 05:22 AM
#2
Re: Set range then add values to existing values
you can do a for each cell in the range
Code:
For Each c In rng
c.Value = c + mynumber
Next
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|