繁体   English   中英

使用if函数复制/粘贴值

[英]copy/paste values with the if function

我正在尝试在VBA中编写代码,以便在主工作表处于特定日期时将值从另一个工作表复制到主工作表中。 我的数据是这样设置的:

在主工作表的A列中,我有特定月份的日期(mm / dd / yy)。 B和C列中的数据与计算无关,但必须存在。 我要在D列到G列中粘贴源工作表中的值。 例如,如果A19是02/13/15,我希望宏将数据从源工作表中提取到单元格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

您在某处遇到错误吗? 还是有没有特别做的事情?

编辑:

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等,如果它们仅显示一次,则不会有问题。

暂无
暂无

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

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