将值从一个工作表粘贴到另一个如果X = True

我正在试图创build一个macros,如果第五个工作表中的列F是= 3,则将值粘贴到3(列A到E)的左侧到另一个表(表1)中。 我似乎无法开始。 当我运行macros没有任何反应。 我确信我犯了一堆愚蠢的错误。

在此先感谢您的帮助!

插口

Sub Movevalues() Dim q As Integer, w As Integer w = 7 For q = 1 To 1000 If ActiveWorkbook.Worksheets("Taxable Accounts Import").Cells(q, 6).Value = 3 Then Range(Cells(q, 1), Cells(q, 5)).Select Selection.Copy Worksheets(1).Select Range(22, w).Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Worksheets(5).Select w = w + 1 End If Next q End Sub 

我认为这里的问题是,你从Worksheets(5)连续复制5个单元格,但是每个for循环只增加1。 如果目标实际上是添加到Worksheets(1)上的同一行,则需要将w增加5来代替…这是一个很好的,简单的修复哈哈:

 w = w + 5 

这就是说,你循环1000次,这意味着可能有1000个匹配,这将填充1000列(或5000列,如果我的5校正是准确的)。 好多啊! 如果你的意图是从第7行第22列开始,并从那里增加行,我可以使用下面的策略。 (沉重的评论来解释发生了什么…)

 Option Explicit Sub MoveValuesRev2() Dim q As Long, w As Long Dim TAI As Worksheet, SheetOne As Worksheet, _ SheetFive As Worksheet Dim Source As Range, Target As Range 'set references up-front w = 7 Set TAI = ThisWorkbook.Worksheets("Taxable Accounts Import") Set SheetOne = ThisWorkbook.Worksheets(1) Set SheetFive = ThisWorkbook.Worksheets(5) 'loop through the cells in question For q = 1 To 1000 If TAI.Cells(q, 6).Value = 3 Then 'store the left-of-the-found-value-3 cells in a range With SheetFive Set Source = .Range(.Cells(q, 1), .Cells(q, 5)) End With 'set the target range in row w, col 22 With SheetOne Set Target = .Cells(w, 22) End With 'the next two lines are the copy and paste step Source.Copy Target.PasteSpecial (xlPasteValues) 'increment w w = w + 1 End If Next q End Sub 

我认为使用一些variables而不是明确的引用会更容易。 有一件事情会变得更容易,就是你不需要前后“select”表单。

我会尽力评论我在做什么,这样对你来说是可以理解的。

未经testing,所以让我知道是否有任何麻烦。

 Sub Movevalues() Dim q As Integer, w As Integer Dim wsSource as Worksheet 'represents the SOURCE worksheet Dim wsDest as Worksheet 'represents the DESTINATION worksheet Dim copyRange as Range 'represents the range we want to COPY Dim destRange as Range 'represents the destination range 'Initialize some variables w = 7 Set wsSource = ActiveWorkbook.Worksheets("Taxable Accounts Import") Set wsDest = ActiveWorkbook.Worksheets(1) For q = 1 To 1000 With wsSource If .Cells(q, 6).Value = 3 Then 'Define the range to be "copied" Set copyRange = .Range(.Cells(q,1), .Cells(q, 5)) 'Define the destination range using the Resize method: Set destRange = wsDest.Range(22, w).Resize(1,copyRange.Columns.Count) 'Here, we don't need to select or even "copy" anything, we can write directly ' to one range, from another. destRange.Value = copyRange.Value 'ensure that w identifies the next column and does not overwrite the values ' that we just transferred, above. w = w + copyRange.Columns.Count End If Next q End Sub 

注意:这里假设您打算复制数据并将其全部放在目标工作表的单个行中,如您的示例所示(使用第22行,第w列作为粘贴目标)。