You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用VBA筛选数组中特定年月的行并复制至其他工作簿

提取指定年月的Excel行并复制到新工作簿(VBA实现)

需求与困惑

  • 需求:筛选Excel表格中第一列日期为指定年月的所有行,将这些行的A至I列内容复制到另一个工作簿。
  • 困惑:作为VBA新手,知道需要用For Each循环遍历行,但不清楚如何从dd/mm/yyyy格式的日期中提取出年月部分,因此暂时无法开展代码编写。

最终可用代码

Dim rngInput As Range, nTargetYear As Integer, nTargetMonth As Integer
Dim rngRow As Range, vntInput As Variant, nYear As Integer, nMonth As Integer
Dim rngTarget As Range

' 循环前先设置输入范围、目标工作簿和工作表
' 这部分需要你根据自己的实际情况调整,因为不清楚你的表格结构
Set rngInput = wsTEff.Range("A15:A500")

' 定义目标年月(示例:2023年1月)
nTargetYear = year0
nTargetMonth = mnthnum

' 遍历输入范围中的每一行
Dim i As Integer
i = 0
For Each rngRow In rngInput.Rows
    vntInput = rngRow.Cells(1, 1)  ' 取A列的日期值
    
    If IsDate(vntInput) = True Then  ' 先确认Excel识别该值为日期格式
        
        nYear = Year(vntInput)
        nMonth = Month(vntInput)
        
        ' 判断日期是否符合目标年月
        If nYear = nTargetYear And nMonth = nTargetMonth Then
            
            Set rngTarget = wsnew.Range("A5").Offset(i, 0)
                            
            ' 将源行的A-I列复制到目标位置(仅粘贴值)
            rngRow.Resize(1, 9).Copy
            rngTarget.PasteSpecial xlPasteValues
            i = i + 1
        End If
    End If
Next rngRow

内容的提问来源于stack exchange,提问作者Kim Woods

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 06:37:28