【问题标题】:VBA code for applying different percentage for last column of table用于为表的最后一列应用不同百分比的 VBA 代码
【发布时间】:2015-07-12 16:02:39
【问题描述】:

这是我目前所拥有的:

Sub test()
    Dim r As Range, n As Integer, i As Integer
    On Error Resume Next
    Set r = Application.InputBox("Select the range", Type:=8)
    On Error GoTo 0
    If r Is Nothing Then Exit Sub
    n = Application.InputBox("How many departments?")
    c = ActiveCell.Column
    r.Copy
    For i = 1 To n
        Cells(ActiveCell.Row, c + (i - 1) * (r.Columns.Count + 1)).Activate
        ActiveCell.PasteSpecial Paste:=xlPasteValues
    Next i
    Application.CutCopyMode = False
End Sub

到目前为止这个宏,

  1. 提示用户选择一个范围。该范围将是另一个工作表中的表格。
  2. 然后它会再次提示用户询问有多少部门,并根据该数字,它将所选范围复制到新工作表中特定次数。
  3. 下一步是 - 根据部门类型 - 用户需要输入一个百分比并将该百分比应用于所选范围的最后一列,即销售收入。

例如,如果用户输入有 5 个部门,它将在新工作表中复制表格 5 次。然后它应该再次提示用户询问 5 个部门中每个部门的百分比份额是多少,并将最后一列(销售收入)乘以它们各自的百分比。为了更好地说明我的观点,这里有一个示例工作簿:

Dummy Data on GoogleDrive

关于如何做到这一点的任何建议?

【问题讨论】:

  • c 未声明。这是疏忽还是全局变量?

标签: vba excel


【解决方案1】:

这种方法怎么样 - 当您复制值时,将最后一列替换为链接到原始范围的公式,并在复制列下方的百分比值。允许用户直接在电子表格中修改这些百分比。比如:

Sub test()
    Dim r As Range, n As Integer, i As Integer, c As Integer
    Dim vals As Variant
    Dim cRange As Range
    Dim pCell As Range 'to hold percentage
    Dim numRows As Integer, numCols As Integer
    Dim fcol As String
    On Error Resume Next
    Set r = Application.InputBox("Select the range", Type:=8)
    On Error GoTo 0
    If r Is Nothing Then Exit Sub

    numCols = r.Columns.Count
    numRows = r.Rows.Count
    vals = r.Value

    fcol = r.Columns(numCols).Address
    fcol = "'" & r.Parent.Name & "'!" & fcol

    n = Application.InputBox("How many departments?")
    c = ActiveCell.Column
    Set cRange = Range(ActiveCell, ActiveCell.Offset(numRows - 1, numCols - 1))
    For i = 1 To n
        cRange.Value = vals
        Set pCell = cRange.Cells(1, 1).Offset(numRows, numCols - 1)
        pCell.Value = 100 '=100%
        cRange.Columns(numCols).FormulaArray = "=" & fcol & " * " & "0.01 * " & pCell.Address
        pCell.Offset(1).Value = "Department " & i & "'s %"
        Set cRange = cRange.Offset(0, numCols + 1)
    Next i

End Sub

在这段代码中,我展示了一种使用范围对象值属性和变量数组传输数据的标准方法。在VBA中很少需要选择、复制和粘贴

【讨论】:

  • 谢谢,约翰。是否可以让宏从 B2、K2、S2 等中检索百分比?这取决于有多少部门,但总有一个地方我必须放百分比,所以不妨从那里检索它。查看示例工作表“Dept_Spread”以更好地了解我的意思。 docs.google.com/spreadsheets/d/…
  • 一个问题是保存百分比的实际单元格取决于调用宏时活动单元格的位置(根据您的代码)。一种可能性是,在设置 pCell 的循环中,为工作簿的名称集合中的单元格创建一个名称(但您可能希望确保在重新运行子程序时清除名称)。然后,例如,“Dept1Percent”可以始终引用保存部门 1 百分比的单元格,无论调用子时哪个单元格处于活动状态。
猜你喜欢
  • 2019-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
相关资源
最近更新 更多