-1

南卡罗来纳州阿比盖尔伯里

南卡罗来纳州阿比盖尔伯里

南卡罗来纳州阿比盖尔伯里

*想法是自动将错误放置的州与家乡交换。即南卡罗琳和阿比盖尔伯里

我有 5001 行并试图访问特别是两列(家乡,家乡)。我正在尝试编写一个交换家乡和家乡值的 vba 脚本,如果我的家乡值错误地放置在家乡列中。我试图通过在工作表中引用所有 50 个状态的范围的数组来做到这一点,并且应该在 if 语句中进行检查。

但是我不断得到不匹配,定义应用程序定义或对象定义错误。新手错误我确定。

这是我的尝试:

Dim states() As String 
states = Range("N1:N50").Value 
Dim x As Long 
Dim y As Long 

'go through rows in the d column
For x = 1 To 5001
    'Range("D" & x).Select

        'for loop for array and if statement
            For y = 1 To 50

            states() = Cells(y, n)

                    If y <= 1 Then

            'second for loop

                    Var = Cells(2, 4)
                    Cells(2, 4) = Cells(2, 5)
                    Cells(2, 5) = Var

                   End If

            Next y 'go to next 1..50            
Next x
4

1 回答 1

0

这是我认为可能对您有所帮助的东西。假设我的工作表设置如下:

      A     B     C     D            E           ...     N
1                       Home State   Home Town           States
2                       KS           Townsville          AL
3                       ME           Bar Harbor          AK
4                       CO           Boulder             AR
5     etc...

然后,我可以使用以下内容检查是否有任何条目Home Town实际上是状态名称,如果是,则将该值与Home State.

Dim states As Variant

Sub CheckHomeTown()
    Dim rw As Long, temp As Variant
    states = Range("N2:N52")               //Assign states to module level variable 'states'

    For rw = 2 To 5001                     //Loop through all 'Home Town` entries...
        If IsState(Cells(rw, 5)) Then      //If 'Home Town' is actually a state then swap...
            temp = Cells(rw, 4)
            Cells(rw, 4) = Cells(rw, 5)
            Cells(rw, 5) = temp
        End If
    Next rw
End Sub

Function IsState(val As Range) As Boolean
    Dim match As Boolean        
    match = False

    For Index = 1 To UBound(states)
        If val = states(Index, 1) Then
            match = True
        End If
    Next Index

    IsState = match
End Function
于 2013-04-28T17:07:01.537 回答