如果value是数组,则Excel VBA交换单元格

时间:2013-04-28 16:34:03

标签: arrays excel-vba if-statement for-loop vba

南卡罗来纳州Abigaylebury

南卡罗来纳州Abigaylebury

南卡罗来纳州Abigaylebury

*想法是自动与家乡交换错误放置的州.i.e caroline& abigaylebury

我有5001行并尝试访问特别是两列(Home town,Home state)。 我正在尝试写一个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

1 个答案:

答案 0 :(得分: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