比较一列中的文本以确定另一列的输出

好的。 这是我在A1栏中的内容:A100:

12V Automotive Products 12V Automotive Products 12V Automotive Products 12V Automotive Products 12V Automotive Products 12V Automotive Products 12V Automotive Products 12V Automotive Products 12V Automotive Products 12V Automotive Products 12V Automotive Products 12V Automotive Products A/V Cables Accessories Accessories Accessories Accessories Accessories Accessories Accessories Accessories Accessories Accessories Accessories Action Action Action Action Action Action Action Action Action Action Action Action Action Action Action Action Action Action Action Action & Adventure Action & Adventure Adapters Adapters Adapters Adapters Adapters & Splitters Adapters & Splitters Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure Adventure 

这是代码:

 Sub FillColumnB() Dim rng As Range, cl As Range Set rng = Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row) For Each cl In rng If cl = "12V Automotive Products" Then cl.Offset(0, 1) = "tdexjxr" ElseIf cl = "Accessories" Then cl.Offset(0, 1) = "s6ii" ElseIf cl = "Action" Then cl.Offset(0, 1) = "7ks57k5k" ElseIf cl = "Action & Adventure" Then cl.Offset(0, 1) = "kxee5xskex" ElseIf cl = "Adapters" Then cl.Offset(0, 1) = "kxykk5ezw" ElseIf cl = "Adobe Titles" Then cl.Offset(0, 1) = "kz46yk78" ElseIf cl = "Adventure" Then cl.Offset(0, 1) = "l8rrzlez" ElseIf cl = "All Toys" Then cl.Offset(0, 1) = "ezlllels6" ElseIf cl = "Animation" Then cl.Offset(0, 1) = "988l7889l" ElseIf cl = "Anti-Virus/Anti-Spyware" Then cl.Offset(0, 1) = "wq3w" ElseIf cl = "Applications" Then cl.Offset(0, 1) = "jrd5j" ElseIf cl = "Arcade" Then cl.Offset(0, 1) = "drj76j" ElseIf cl = "Arts & Humanities" Then cl.Offset(0, 1) = "8l" End If Next End Sub 

我的问题是为什么上面的代码不工作?

首先一个Select Case块比一系列ElseIf语句更有意义。 至于为什么“没有工作”,没有错误,有两个可能的问题:

1)您不访问单元格对象的值。 它应该是隐含的,但指定它应该有所帮助。

2)你没有处理单元格的值不符合任何列出的文本的情况。 添加一个最后的Else案件应该处理这种可能性。 如果rng所有单元都是这样,那么就更多地查看它们的内容。 也许有需要删除的前导或尾随空白。

 For Each cl In rng.cells Dim outCell as Range Set outCell = cl.offset(0,1) Select Case cl.value Case "12V Automotive Products" outCell.value = "s6ii" Case "Action" outCell.value = "7ks57k5k" 'Case ... ' outCell.value = ... Case Else outCell.value = "Not Recognized Value" End Select Next cl 

你需要确保你的范围是抓住一切,因为如你所说,你的代码适用于less量的数据(10行)。 使用以下内容显示一个消息框,通知您在范围select中的总行数。 确保它正在检查正确数量的行:

  Dim rng As Range, cl As Range Dim rngCheck As Integer Set rng = Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row) rngCheck = Range("A" & Rows.Count).End(xlUp).Row MsgBox rngCheck 

从上一张纸复制到新纸张:

 Sheets("Name of Sheet").Range(Range of Cells).Copy Sheets("Destination Sheet").Range(Where you want it).PasteSpecial Paste:=xlPasteValues