问题
I am very new to VBA and I am seeking help to solve the following problem. I need to multiply a range by a single number. All of the cells with in that range need to be multiplied by that one number.
Thank you!
回答1:
As what I comment just now.
1.Enter the formula at the cells (e.g. G1)
2.Press Enter key and drag the formula
回答2:
keong has already shown you one method but unfortunately that method requires one to do the calculation in another cell/range. If that is what you want then go with keong's answer but if you want to do the calculation in the same range then continue reading below.
Here is another method which doesn't use formulas or VBA.
Let's say the range is A1:A10
and you want to multiply the entire range by 5
- Simply type
5
in any blank cell. You can delete that later. - Copy that cell
- Select Range
A1:A10
- Right click on it
- Click on
Paste Special | Values - Multiply
as shown below and you are done.
Before
After
Followup from comments
In case you do not want to use a temp cell to write 5 then you can directly set 5
in the clipboard and use it like this.
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim MyData As New DataObject
Dim rng As Range
Set ws = Sheet1
Set rng = ws.Range("A1:A5")
'~~> Put the number 5 in clipboard
MyData.SetText 5
MyData.PutInClipboard
'~~> Get the data from clipboard
MyData.GetFromClipboard
rng.Formula = Application.Evaluate("=" & _
rng.Address & _
"*" & _
Val(MyData.GetText))
End Sub
Like I mentioned, you don't need VBA for this but if you still want to use VBA then you can use this instead of copying the data to the clipboard.
rng.Formula = Application.Evaluate("=" & rng.Address & "*" & MYNUMBER)
Where MYNUMBER
is the variable which has the number that you want to multiply the range with.
来源:https://stackoverflow.com/questions/31174875/excel-vba-how-to-multiply-range-by-one-number