使用VBA如果然后语句复制和粘贴数据

我是一个全新的VBA用户,试图根据date范围复制和粘贴数据。 在第一列中,我有date,在第二列中有我想复制和粘贴的数据。 CurYear指的是我正在查找的范围内的结束date,而StatDate指的是我正在查找的范围中的开始date。 当我运行这个代码时,它崩溃了Excel。 请帮忙,我很迷路

Worksheets("Weekly").Select Dim nRows As Integer Dim CurYear As Date Dim StartDate As Date nRows=Range("A1").CurrentRegions.Count.Rows CurYear=Range("I265").Value StartDate=Range("M5").Value Do While Cells(nRows,1)<>"" if Cells(nRows,1).Value< CurYear & Cells(nRows,1)> StartDate Then Cells(nRows,1).Offset(0,1).Copy Worksheets("Weekly").Range("H41").Paste Loop End If 

而不是使用复制/粘贴,使用大量的内存,并使程序运行缓慢,您可能需要考虑下面的代码与您的代码或Rodger的目的相同,但比Select和复制/粘贴语法更快。

 Sub Test() Dim nRows As Long, LastRow As Long 'Declare as Long instead of Integer to avoid overflow Dim CurYear As Date, StartDate As Date LastRow = Cells(Rows.Count, 1).End(xlUp).Row 'Count the last used row in column 1 where you put the first data (dates) nRows = 2 'Set the starting point of row where you put the first data (dates). In this example I use 2 CurYear = Range("I265").Value StartDate = Range("M5").Value Do If Cells(nRows, 1).Value < CurYear And Cells(nRows, 1) > StartDate Then 'Use And not & Cells(nRows, 5).Value = Cells(nRows, 2).Value 'This is essentially a "copy/ paste" syntax. Change the value (5) to the column you want to paste the value in column 2 End If nRows = nRows + 1 'Set an increment value so each looping the nRows will increase by 1 Loop Until nRows = LastRow + 1 'Added by 1 so that the data in LastRow will keep being processed End Sub 

在你的代码的顶部(在sub之前)放上“option explicit”,它会告诉你一些事情要修复。 这样做将修复你的错误的一部分,如果你的结束,如果是在循环之外,而不是在它内部,但它不会捕捉到你不改变你的循环计数器。 试试这个代码。 这实际上和你做了一些小的改动几乎一样。

 Option Explicit Sub test() Dim sht As Worksheet, i As Long, l As Long, j Dim nRows As Integer Dim CurYear As Date Dim StartDate As Date Set sht = Worksheets("Test1") ' set the sheet as object isntead of selecting it for faster code and avoiding other issues nRows = Cells(sht.Rows.Count, "B").End(xlUp).Row 'Last used row in column B - current region lastrow gets twitchy in some circumstances and should be avoided unless there is a reason to use it l = 41 CurYear = range("I265").Value StartDate = range("M5").Value For i = 1 To nRows If Cells(i, 1).Value < CurYear And Cells(i, 1).Value > StartDate Then 'for If statements you use "and" not "&" Cells(l, 15) = Cells(i, 2) 'you will want something like this line and the next if you don't want to overwrite H41 if there is more than one match l = l + 1 End If Next i End Sub 

另外,为了帮助debugging,打开你的本地窗口(在VBE中查看)。 使用F8浏览代码,在本地窗口中查看variables,以确保它们是您期望的脚本中的那一步。

如果你用你的代码来做这件事,你会发现你的循环中的variables缺less一个计数器变化。 所以它一直在寻找nRow来最终成为“”,但它仍然停留在任何它所设定的范围内。 无限循环。 我将其更改为下一个格式,但其中6个是1,另外6个是您的代码。

欢迎来到VBA。 不要捅你的眼睛。 🙂