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

时间:2016-07-18 18:59:58

标签: excel vba excel-vba

我是一位全新的VBA用户,他尝试根据日期范围复制和粘贴数据。在第一列中我有日期,在第二列中我有我想要复制和粘贴的数据。 CurYear是指我正在寻找的范围内的结束日期,StatDate指的是我正在寻找的范围中的开始日期。当我运行此代码时,它崩溃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

2 个答案:

答案 0 :(得分:1)

明确&#34;选项&#34;在代码的顶部(在子代码之前),它会告诉你需要修复的东西。这样做可以解决你的错误部分,如果你的结束是在循环之外而不是在它内部,但它不会发现你没有改变你的循环计数器。请尝试使用此代码。它实际上几乎与你的几个小改动相同。

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

另外,为了帮助调试,请打开本地窗口(在VBE中查看)。使用F8逐步执行代码,在本地窗口中查看变量,以确保它们符合您希望它们在脚本中的那一步。

如果您对代码执行此操作,您将看到您错过了针对循环的变量的计数器更改。所以它一直在寻找nRow最终成为&#34;&#34;但它保持在它设定的任何地方。无限循环。我将它更改为下一个格式,但是代码中的6个和另外6个代码。

欢迎来到VBA。不要瞧不起眼睛。 : - )

答案 1 :(得分:0)

您可能希望考虑以下代码与代码或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