如何在Excel中编写一个VBA多行相应的单元格If Statement

开始我是一个小白菜。 我简直就是昨天第一次看VBA。 所以,我很感激,如果你愚蠢的答复。 大声笑。

一周几次,我得到一张工作表的电子表格。 我必须拆分邮政编码并将它们移到那里透视商店。 大约有20个邮政编码,虽然我使用sorting选项,但它仍然需要我一段时间。 我想使用marco几乎给每个邮编一个商店。

这是我的问题。 我想看看“J1”,如果邮政编码匹配的许多我想要“牛头”写在“M1”

我能够做到这一点,花了我几个小时的试验和错误才得出最好的结果。 我尝试了很多不同的东西。 (最底层是我想出的)

这是问题。 我需要一直沿着电子表格进行此操作。 即。 如果m3 = 86409 J3 =金曼。 如果m4 = 86409 j4 =金曼。 如此等等一直到M5000,J5000。

任何帮助将不胜感激。 我想做的事很简单,但是我自己找不到答案,或者我无法理解。 我想我将不得不重新开始。 采取不同的方法。 不知道是什么。

Sub MoversBirthdays() Dim zipcode As Long, Store As String zipcode = Range("J2").Value If zipcode = "86426" Or "86427" Or "86429" Or "86430" Or "86435" Or "86436" Or "86437" Or "86438" Or "86439" Or "86440" Or "86442" Or "86446" Or "89028" Or "89029" Or "89046" Or "92304" Or "92332" Or "92363" Then Store = "Bullhead" Else: Store = "Kingman" If zipcode = "" Then Store = "" Range("M2").Value = Store End Sub 

 Sub MoversBirthdays() Dim varZip As Variant Dim arrStore() As String Dim StoreIndex As Long With Range("J2", Cells(Rows.Count, "J").End(xlUp)) If .Row < 2 Then Exit Sub 'No data ReDim arrStore(1 To .Rows.Count) For Each varZip In .Value StoreIndex = StoreIndex + 1 Select Case varZip Case 86426 To 86427, 86429 To 86430, 86435 To 86440, 86442, 86446, 89028 To 89029, 89046, 92304, 92332, 92363 arrStore(StoreIndex) = "Bullhead" Case "" arrStore(StoreIndex) = "" Case Else arrStore(StoreIndex) = "Kingman" End Select Next varZip End With If StoreIndex > 0 Then Range("M2").Resize(StoreIndex).Value = Application.Transpose(arrStore) End Sub 

你的代码有几个问题。

首先,您将zipcode定义为Long ,但将其与String进行比较。 它应该被定义为一个String(或者与Longs相比较)。

其次,你不能用值列表来做一个If。 它parsing,但它被解释为If zipcode is 86426; Or If 86427; Or If 86429... If zipcode is 86426; Or If 86427; Or If 86429... If zipcode is 86426; Or If 86427; Or If 86429... 你实际上需要说每个zip文件的If zipcode = "xxx"

但是,由于您使用的是Excel,因此您可以将工作表上的压缩文件列表放在工作表上,然后引用它进行比较。 假设列表在列A中,以下代码将执行您所需的操作:

 Sub MoversBirthdays2() Dim zipcode As String, Store As String Dim c As Range For Each c In Range("j2:j5000") zipcode = c.Value If zipcode = "" Then Store = "" Else If WorksheetFunction.CountIf(Range("a:a"), zipcode) > 0 Then Store = "Bullhead" Else Store = "Kingman" End If End If c.Offset(0, 2) = Store Next End Sub 

如果您实际上不需要用空格覆盖列M中的值(如果zip为空),则可能会更简单一些:

 Sub MoversBirthdays2() Dim zipcode As String, Store As String Dim c As Range For Each c In Range("j2:j5000") zipcode = c.Value If zipcode <> "" Then If WorksheetFunction.CountIf(Range("a:a"), zipcode) > 0 Then Store = "Bullhead" Else Store = "Kingman" End If c.Offset(0, 2) = Store End If Next End Sub