【发布时间】:2020-05-14 21:41:26
【问题描述】:
如果满足以下条件,我如何将行从一个工作簿复制/粘贴到另一个工作簿: 如果源工作簿(wb.Source,sheet1)中的所有行来自实际月份(包含真实日期的第 8 列),则复制它们并将它们粘贴到工作表 3 中的我的主工作簿(Wb)。仅复制具有第一个的行在第 8 列中作为日期的月份日期。
示例:
假设今天是 14.05.2020。
触发宏将从源工作簿中复制日期为 01.05.2020(第 8 列)的所有行,并将它们粘贴到工作表 3 中的 wb。
因此,宏需要参考 Today 函数才能说出现在实际上是哪个月份,然后在下一步中复制同一月份的行,但仅从该月份的第一天开始.
不胜感激!
Private Sub CommandButton3_Click()
Dim fname As String, wbSource As Workbook, wsSource As Worksheet
fname = Me.TextBox1.Text
If Len(fname) = 0 Then
MsgBox "No file selected", vbCritical, "Error"
Exit Sub
End If
Set wbSource = Workbooks.Open(fname, False, True) ' no link update, read only
Set wsSource = wbSource.Sheets("Sheet1") ' change to suit
Dim wb As Workbook, ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Sheets("Table 3")
' Set your source and destination worksheets as objects here
Set wsSource = wbSource.Sheets("Sheet1")
Dim i As Long, destination_row As Long
Dim source_rng As Range, destination_rng As Range
destination_row = 1
For i = 1 To 10 ' See note below regarding for vs while loop for this
' Check dates only against cells that contain date values (in case there is a non-date value in one of the cells)
If VarType(wsSource.Cells(i, 8)) = vbDate Then
' Condition checks that the date is today
If Format(Now, "yyyy/mm/dd") = Format(wsSource.Cells(i, 8).Value2, "yyyy/mm/dd") Then
' Set source and destination ranges
Set source_rng = wsSource.Range(wsSource.Cells(i, 1), wsSource.Cells(i, 10000))
Set destination_rng = ws.Range(ws.Cells(destination_row, 1), destination_sheet.Cells(destination_row, 10000))
source_rng.Copy destination_rng ' Alternatively use destination_rng.Value2 = source_rng.Value2
destination_row = destination_row + 1 ' Iterate the destination row so that the next copy outputs to the next row
End If
End If
Next i
' close source worbook no save
wbSource.Close False
End Sub
【问题讨论】:
-
总是有助于发布您当前的代码 - 这将使回答变得更加容易,否则我们可以将您推荐给您已经在这里得到的答案:stackoverflow.com/questions/61800272/…
-
Dateserial(year(date),month(date),1)为您提供当月的第一天