【问题标题】:copy/paste values with the if function使用 if 函数复制/粘贴值
【发布时间】:2015-02-14 04:18:37
【问题描述】:

我正在尝试在 VBA 中编写代码,只要主工作表是特定的一天,它就会将另一个工作表中的值复制到主工作表中。我的数据是这样设置的:

在主工作表的 A 列中,我有特定月份的日期 (mm/dd/yy)。 B 列和 C 列包含与计算无关但需要存在的数据。 D 到 G 列是我要粘贴源工作表中的值的位置。例如,如果 A19 是 2015 年 2 月 13 日,我希望宏将数据从源工作表中提取到单元格 D19:G19 中。

这是我目前使用的代码。我将不胜感激任何帮助。谢谢!

Sub newline()

strdate = InputBox("Date")
D = CStr(strdate)
's4 is the master worksheet
Set s4 = Sheets(4)
's5 is the source worksheet that updates every day with different data
Set s5 = Sheets(5)

n = s4.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count

i = 0

For j = 1 To n
    If s4.Cells(j, 1).Value = D Then
    i = i + 4
    'name of the cells in the source worksheet
    Set r = s5.Range("AccrualPayments")
    r.Copy
    s4.Cells(j, i).PasteSpecial (xlPasteValues)
    End If
Next j

End Sub

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    您是否在某处遇到错误?还是有什么特别没有做的?

    编辑:

    Sub newline()
    Dim strdate as String
    Dim s4, s5 as Worksheet
    Dim i, j, n as Integer
    
    strdate = InputBox("Date")
    
    's4 is the master worksheet
    Set s4 = Sheets(4)
    's5 is the source worksheet that updates every day with different data
    Set s5 = Sheets(5)
    
    n = s4.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
    
    i = 0
    
    For j = 1 To n
        If s4.Cells(j, 1) = strdate Then
        i = i + 4
        'name of the cells in the source worksheet
        s5.Range("AccrualPayments").copy
        s4.Cells(j, i).PasteSpecial Paste:=xlPasteValues
        End If
    Next j
    
    End Sub
    

    确保输入的日期与主工作表上的日期格式相同。例如,2015 年 2 月 2 日可以写成“2/2/2015”、“02/2/2015”或“02/02/2015”。否则,似乎这段代码应该可以工作。

    每个日期是否只会在您的工作表“s4”中出现一次?如果没有,第一个实例将在 D 列中粘贴范围“AccrualPayments”,在 H 列中粘贴第二个,在第三个 L 中粘贴,等等。如果它们只显示一次,这将不是问题。

    【讨论】:

    • 很抱歉。我的问题是我没有得到任何结果。
    • 啊!!谢谢,凯尔。在 vba 中格式化日期是个问题。我将 CStr 更改为 CDate ,一切都按预期工作。再次感谢!
    • 很高兴能帮上忙!
    猜你喜欢
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2020-06-24
    • 1970-01-01
    • 2018-04-08
    • 2014-07-19
    相关资源
    最近更新 更多