繁体   English   中英

基于数据验证列表的动态列复制/粘贴

[英]Dynamic Column Copy/Paste based off of Data Validation List

在每个月末,我们将预测销售额(公式所在的位置)作为硬编码复制/粘贴到其他列中,以供参考和对帐。
例如,将列 D(一月)到列 F(三月)复制到列 Q(一月硬编码)到 S(三月硬编码)

我正在尝试修改我的代码,以便用户可以从每个预测选项卡上的两个数据验证下拉列表中选择要复制/粘贴为值的月份范围(例如 1 月 - 3 月)。
例如,下面是我根据公式的 # 行添加到复制/粘贴的内容。

Dim LastRow As Long
With ActiveSheet
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
Range("T1") = "PPU"
Range("T2") = "=S2/R2"
Range("T2").Copy
Range("T2:T" & LastRow).Select `dynamic row
Selection.PasteSpecial xlFormulas
Range("T:T").Copy
Range("T:T").PasteSpecial xlPasteValues

使用上面的代码,是否可以更改此设置,而不是“&Lastrow”,我将行保持为静态,但使列复制变量,因此缺少更好的术语 firstMonth 和 secondMonth。
要选择的列将基于两个命名范围,其中用户从两个数据验证列表(firstMonth 和 secondMonth)中进行选择,每列都分配了一个列“字母”(例如,Jan 是列 D、二月列 E 等)

没有动态,它会是这样的:

Range("D12:F19").Copy
Range("Q12").PasteSpecial xlValues

但我想让用户通过数据验证列表选择月份,通过选择开始月份 (firstMonth) 和结束月份 (secondMonth) 进行硬编码

类似的东西:

Range(firstMonth &"12": secondMonth & "19").Copy `firstMonth in theory is the column letter so, "D12" and secondMonth is the second column letter (F12)

Range("pasteFirstMonth &"12").PasteSpecial xlValues `the firstMonth will be paired with the column letter, say "Q" where it will paste those values.  A second column range isn't needed here since only the copied range will paste, not overlapping anything else.  This is the "hardcoded" area.

更新:稍微重新配置了下面蒂姆的回答。

Sub copyColumns()

Dim months, m1, m2, sht

    months = Split("Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec", ",")
    Set sht = ActiveSheet
    
    m1 = Application.Match(sht.Range("Month1").Value, months, 0)
    m2 = Application.Match(sht.Range("Month2").Value, months, 0)
    
    sht.Range(sht.Cells(8, 3 + m1), sht.Cells(16, 3 + m2)).Copy
    sht.Range(sht.Cells(8, 16 + m1), sht.Cells(16, 16 + m2)).PasteSpecial xlValues
    
End Sub

这样的事情应该工作:

Sub DoCopy()

    Dim months, m1, m2, sht

    months = Split("Jan,Feb,Mar,Apr,May,June,July,Aug,Sept,Oct,Nov,Dec", ",")
    Set sht = ActiveSheet

    m1 = Application.Match(sht.Range("Month1").Value, months, 0)
    m2 = Application.Match(sht.Range("Month2").Value, months, 0)

    If Not IsError(m1) And Not IsError(m2) Then
        'copy range - use offset (3 here) depending on where months begin
        sht.Range(sht.Cells(12, 3 + m1), sht.Cells(19, 3 + m2)).Copy
        'etc
    End If

End Sub

您可以提示用户选择所需的月份,并且可以使用 Selection 对象,例如

Set rng=Selection
Cells(rng.row, rng.column) gives you the top left cell of the selection, 
rng.Columns.Count gives you the number of columns, etc.

从用户的角度来看,在屏幕上选择一个区域并按下按钮比输入值或从列表中选择要容易得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM