1

我刚开始使用 Excel 的 VBA 代码,如果这看起来很基本,我深表歉意。我想做以下...

检查名为“索引”的工作表的 J 列(J5 到 J500)是否存在值“Y”。这是我的条件。然后我只想将符合条件的任何行的列 C 复制到 I到现有工作表和不同位置的单元格,即如果复制索引值 C3 到 I3 我想将它们粘贴到 A5 到 G5我所在的活动表,比如 Sheet2。

如果索引表有更改,我希望自动复制数据,如果可能的话。如果将新数据添加到索引中,它会如何工作?

经过大量搜索后,我发现了这个。从这个问题中,我稍微更改了代码以满足我的要求,这会将满足条件的整行复制到我从中运行宏的工作表中,但我对如何仅选择某些列感到困惑。

Sub CopyRowsAcross() 

Dim i As Integer 
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Index") 
Dim ws2 As Worksheet: Set ws2 = ActiveSheet 

For i = 2 To ws1.Range("B65536").End(xlUp).Row 
If ws1.Cells(i, 2) = "Y" Then ws1.Rows(i).Copy ws2.Rows(ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row + 1) 
Next i 

End Sub 

任何帮助表示赞赏

约翰

编辑:我创建了一个模型,它位于https://docs.google.com/file/d/0B0RttRif9NI0TGl0N1BZQWZfaFk/edit?usp=sharing

复制时不需要 A 和 B 列 - 要么是 J 列 - 这就是我用来检查条件的内容。

感谢您迄今为止的所有帮助。

4

2 回答 2

0

那是借用一些旧代码。在此您正在检查使用的最后一行,如果您知道您只想转到 500,您可以只使用整数:

Sub try2()

  Dim i, Y, x As Long 'you didn't mention what Y was, so it could also be a string.
  Dim ws1 As Worksheet: Set ws1 = ActiveWorkbook.Sheets("Index")
  Dim ws2 As Worksheet: Set ws2 = ActiveWorkbook.Sheets("Sheet2") 'active sheet can get  you into trouble
  Dim Ary1 As Range
  Dim ary2 As Range


   x = 5
   Y = "Y" 'for the sake of argument
         'For i = 2 To ws1.Range("B65536").End(xlUp).Row   This is if you are looking for the last row in MsOf2003 or earlier.  If you know that you are only looking to row 500, then hard code the intiger.
   For i = 2 To 500:
        'If ws1.Cells(i, 2) = "Y" You mentioned you were interested in column J, so we need to change the 2 to 10 (Column B to Column J)
         If ws1.Cells(i, 10) = Y Then
            ws1.Activate
            Set Ary1 = Range(Cells(i, 3), Cells(i, 9))
            ws2.Activate
            Set ary2 = Range(Cells(x, 1), Cells(x, 7)) 'avoid copying all together you don't need it
            ary2.Value = Ary1.Value
            x = x + 1
         End If
   Next i
  End Sub

我是在手机上而不是在编译器上写的,所以那里可能存在语法错误,这应该被视为伪 VBA 代码。我可以稍后检查您是否可以正常工作。如果您不希望它们被覆盖,则必须注意放置内容的位置。

于 2013-03-13T21:30:40.237 回答
0

这是更优雅的解决方案,与我的原始帖子更相似。唯一的区别是 Cells 引用符合正确的工作表。

Sub try3()
Dim i, x As Long
Dim Y as String
Dim ws1 As Worksheet: Set ws1 = ActiveWorkbook.Sheets("Index")
Dim ws2 As Worksheet: Set ws2 = ActiveWorkbook.Sheets("Sheet2") 'active sheet can get  you into trouble

 x = 5
 Y = "Y"
 For i = 2 To 500:
    If ws1.Cells(i, 10) = Y Then
       Range(ws2.Cells(x, 1), ws2.Cells(x, 7)).Value = Range(ws1.Cells(i, 3), ws1.Cells(i, 9)).Value
      x = x + 1
    End If
 Next i
End Sub

于 2013-03-14T02:06:43.223 回答