Excelmacros帮助。 基于数组创build一个新的列。

我正在尝试在Excel中编写一个macros来创build一个新的列,并将这些状态分为这些区域。 我不断收到运行时错误13

这是我到目前为止的代码。

Sub Region () Dim Pacific As Variant Pacific = Array("WA", "OR", "ID", "CA", "NV", "AZ", "NM", "HI", "AK") Dim Continental As Variant Continental = Array("AR", "IA", "CO", "KS", "LA", "MS", "MT", "ND", "NE", "OK", "SD", "UT", "WY") Dim SouthEast As Variant SouthEast = Array("GA", "AL", "FL", "SC", "KY", "TN") Dim Midwest As Variant Midwest = Array("MN", "WI", "IL", "IN", "MI", "OH") Dim NorthAtlantic As Variant NorthAtlantic = Array("ME", "NH", "MA", "RI", "CT", "VT", "NY", "PA", "NJ", "DE", "MD", "WV", "VA", "NC") Dim Texas As Variant Texas = Array("TX”) Dim state As String , result As String score = Range("F1").Value If state = Pacific Then result = "PACIFIC" ElseIf state = Continental Then result = "Continental" ElseIf state = SouthEast Then result = "SouthEast" ElseIf state = Midwest Then result = "Midwest" ElseIf state = NorthAtlantic Then result = "North Atlantic" ElseIf state = Texas Then result = "Texas" Else result = "fail" End If Range("Z1").Value = result End Sub 

AFAIK,在数组中search一个string的出现在VBA中不是一件简单的事情。 您必须使用循环,或者可能使用WorksheetFunction.Match

一个简单的方法可能是完全避免数组 – 您的代码可以很容易地重构使用Select Case语句:

 Sub Region () Dim state As String , result As String state = Range("F1").Value Select Case state Case "WA", "OR", "ID", "CA", "NV", "AZ", "NM", "HI", "AK" result = "PACIFIC" Case "AR", "IA", "CO", "KS", "LA", "MS", "MT", "ND", "NE", "OK", "SD", "UT", "WY" result = "Continental" Case "GA", "AL", "FL", "SC", "KY", "TN" result = "SouthEast" Case "MN", "WI", "IL", "IN", "MI", "OH" result = "Midwest" Case "ME", "NH", "MA", "RI", "CT", "VT", "NY", "PA", "NJ", "DE", "MD", "WV", "VA", "NC" result = "North Atlantic" Case "TX" result = "Texas" Case Else result = "fail" End Select Range("Z1").Value = result End Sub 

注意:你也有两个代码问题。

  1. 你有过

     score = Range("F1").Value 

    当我认为你的意思

     state = Range("F1").Value 
  2. 你有"TX”而不是"TX" – 我不确定这个是否会导致你的Excel版本出现问题,但是在我的版本中。


要扩展这个函数,使它适用于列F中的所有单元格,您将需要遍历每一行:

 Sub Region () Dim state As String , result As String Dim lastRow As Long Dim r As Long With ActiveSheet lastRow = .Cells(.Rows.Count, "F").End(xlUp).Row For r = 1 to lastRow state = .Cells(r, "F").Value Select Case state Case "WA", "OR", "ID", "CA", "NV", "AZ", "NM", "HI", "AK" result = "PACIFIC" Case "AR", "IA", "CO", "KS", "LA", "MS", "MT", "ND", "NE", "OK", "SD", "UT", "WY" result = "Continental" Case "GA", "AL", "FL", "SC", "KY", "TN" result = "SouthEast" Case "MN", "WI", "IL", "IN", "MI", "OH" result = "Midwest" Case "ME", "NH", "MA", "RI", "CT", "VT", "NY", "PA", "NJ", "DE", "MD", "WV", "VA", "NC" result = "North Atlantic" Case "TX" result = "Texas" Case Else result = "fail" End Select .Cells(r, "Z").Value = result Next End With End Sub 

为什么不使用Access创build表格,然后链接到您要创build的更多逻辑表格(我假定您已经编写了一些代码的实际用法)这就是为什么首先创build访问权限的原因。 ..