簡體   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