Excel VBA How to multiply range by one number [closed]

冷暖自知 提交于 2020-06-29 09:41:04

问题


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)
Formula
2.Press Enter key and drag the formula
enter image description here




回答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

  1. Simply type 5 in any blank cell. You can delete that later.
  2. Copy that cell
  3. Select Range A1:A10
  4. Right click on it
  5. Click on Paste Special | Values - Multiply as shown below and you are done.

Before

enter image description here

After

enter image description here

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!