VBA按钮计算

时间:2018-02-12 08:24:11

标签: excel-vba vba excel

我在单元格d4:p5中有一系列数字,并希望能够将所有数字乘以1.36(并再次返回),并使用按钮单击显示在相同单元格中的结果。

这可能吗?

2 个答案:

答案 0 :(得分:0)

使用以下代码:

Option Explicit

Public Sub MultiplyCells()

 Dim ws As Worksheet
 Dim x As Integer, y As Integer, rowLength As Integer, columnLength As 
 Integer, rowStart As Integer, columnStart As Integer
 Dim multiplier As Double

 Set ws = ThisWorkbook.Worksheets("yourSheet")

 rowLength = 5 'in your example. To make it dynamically use rows.count
 rowStart = 4

 columnLength = 16 'in your example. To make it dynamically use column.count
 columnStart = 4

 multiplier = 1.36

 For x = rowStart To rowLength Step 1
     For y = columnStart To columnLength Step 1
         ws.Cells(x, y).Value = ws.Cells(x, y).Value * multiplier
     Next y
 Next x
End Sub

然后使用开发者工具创建一个按钮 - >插入 - >按钮。 右键单击刚刚创建的按钮,并将Sub MultiplyCells分配给它。

现在您应该能够创建第二个按钮并“向后”应用上述逻辑。

答案 1 :(得分:0)

启动项目:

StartingProject 添加艺术字对象,图片,图形或按钮(基本上你可以附加宏的任何东西) AddingButton 转到Visual Basic编辑器(热键是 Alt + F11 ) 并在您的vba项目中插入一个新模块。 enter image description here
在新模块中输入以下代码:

Option Explicit
Sub Multiply()
    Dim MySheet As Worksheet
    Dim MyRange As Range
    '   This is your working sheet, modify "Sheet1" to the actual name
    Set MySheet = ThisWorkbook.Worksheets("Sheet1")
    '   This is your range, modify "D4:P5" to your actual range address
    Set MyRange = MySheet.Range("D4:P5")
    '   Condition on "A1" value, if it is true, multiply, otherwise divide by 1.36
    '   You can change "A1" to any unnecessary cell address
    If MySheet.Range("A1") Then
        '   Evaluate "evaluates" formulas you input in them
        '   This formula looks like "=$D$4:$P$5 * 1.36"
        MyRange.Value = Evaluate("=" & MyRange.Address & "*1.36")
    Else
        MyRange.Value = Evaluate("=" & MyRange.Address & "/1.36")
    End If
    '   Change "A1" value to an opposite
    MySheet.Range("A1").Value = Not MySheet.Range("A1").Value
End Sub

附加"乘以"宏到你的按钮