根据日期将数据复制到单元格

时间:2017-09-19 08:39:37

标签: excel vba excel-vba

所以我有2个工作簿,helper.xlsm和每周data.xlsx 我想做的是从helper.xlsm表11中复制来自D3 G3 P3 R3和T3单元格的数据 每周data.xlsx工作表1上的相同列,但两个工作簿中基于日期的不同单元格

所以这本书的数据 helper book

基于B列中的日期到本书 weekly data book

我需要匹配日期然后复制和粘贴 例如,如果date = 19-september,则需要将数据粘贴到行309中 20号将是310等,任何帮助都会很棒,如果你能花时间解释代码,那将是非常棒的,因为我试图学习vba

1 个答案:

答案 0 :(得分:1)

如果您正在寻找将某些数据从当前文件复制到目标电子表格的宏,您可以尝试以下代码。

它打开目标文件的浏览窗口,如下所示:

文件打开对话框 - 目标文件:

enter image description here

以下是代码:

Sub exportday()
    Dim fileStr As String, srcBk As Workbook, destBk As Workbook, rng1 As Range, rng2 As Range, tmpDt As Date
    Set srcBk = ThisWorkbook
    ChDrive srcBk.Path
    ChDir srcBk.Path

'    get destination file
    fileStr = Application.GetOpenFilename("Destination file (*.xls*),*.xls*")
    If fileStr = "False" Then Exit Sub
    Set destBk = Workbooks.Open(fileStr)
    Sheets("day sales").Select

'    get source row
    For Each rng1 In srcBk.Sheets(1).Columns("B").Cells
        If rng1 > 0 Then
            tmpDt = rng1
            Exit For
        End If
    Next

'    get destination row and update values
    For Each rng2 In destBk.Sheets("day sales").Columns("B").Cells
        If rng2 = tmpDt Then
            rng2.Offset(0, 2) = rng1.Offset(0, 2)   'col D
            rng2.Offset(0, 5) = rng1.Offset(0, 5)   'col G
            rng2.Offset(0, 14) = rng1.Offset(0, 14) 'col P
            rng2.Offset(0, 16) = rng1.Offset(0, 16) 'col R
            rng2.Offset(0, 18) = rng1.Offset(0, 18) 'col T
            Exit For
        End If
    Next

    destBk.Close savechanges:=True
    MsgBox "Spreadsheet " & fileStr & " updated.", vbInformation, "Success"
End Sub

假设:

  • 源电子表格(宏所在的位置)只有1张