2014-10-31 38 views
3

因此,我编写了一个For循环代码,试图通过数据的特定列(列M)搜索包含以“GE90”开头的描述的单元格,并替换了一个双眼偏移单元格C栏)和“GE90 Hold”。如何使用For循环来替换偏移单元格

我以为我正确使用的代码,但由于某种原因,它似乎并没有工作。

Dim Cell 
For Each Cell In Range("M2:M" & LastRow) 
    If Cell.Value = "GE90*" Then 
     Cell.Offset(, -10).Value = "GE90 Hold" 
    End If 

Next Cell 
+2

如果我理解*与 “GE90” 开始*正确的,你应该是使用'如果左(Cell.Value,4)= “GE90” Then'?从列M到列C(例如-10)看起来偏移似乎是正确的。 – Jeeped 2014-10-31 13:03:14

+0

@Jeeped此代码完美工作谢谢! – ksmit144 2014-10-31 13:18:46

回答

4

Cell.Offset(, -10).Value如果你想写入Col C是正确的,但何尝不是一种简单的方法?

Range("C" & cell.row).Value = "GE90 Hold" 

Cells(cell.row, 3).value '<~~ As enderland suggested in the comment 

的问题是你如果条件。将其更改为

If Cell.Value Like "GE90*" Then 
+0

或'Cells(3,cell.row).value' – enderland 2014-10-31 13:04:55

+0

@enderland:也是这样:)更新了我的答案。 :) – 2014-10-31 13:06:15

+0

你可能喜欢这个聊天室顺便说一句 - http://chat.stackexchange.com/rooms/14929/vba – enderland 2014-10-31 13:06:48

5

你的问题其实是,你承担"GE90*"星号是一个通配符,但实际上,你的代码是寻找文字值"GE90*"。更改您的代码如下:

Dim Cell 
For Each Cell In Range("M2:M" & lastrow) 
    If Left(Cell.Value, 4) = "GE90" Then 
     Cell.Offset(, -10).Value = "GE90 Hold" 
    End If 

Next Cell 
+0

谢谢!改变=像Siddharth建议的那样解决了我所有的问题! – ksmit144 2014-10-31 13:16:32

+0

+ 1添加关于通配符的额外说明:) – 2014-10-31 13:23:08