【问题标题】:Excel VBA swapping cells if value is an array如果值是数组,则 Excel VBA 交换单元格
【发布时间】:2013-04-28 16:34:02
【问题描述】:

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

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

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

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

我有 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

【问题讨论】:

  • states() = Cells(y, n) 中,您的程序中没有定义n 变量。这可能是您错误的根源吗?
  • 您可以简单地使用 Vlookup 功能。你能把数据的截图粘贴到你的帖子中吗?
  • 另外,IIRC,您需要在分配一系列值之前正确地重新调整您的 states 数组。
  • 第一个错误是声明你的数组As String。要将范围值吸收到这样的数组中,它必须是:Dim states() As Variant

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


【解决方案1】:

这里有一些我认为可能对你有帮助的东西。假设我的工作表设置如下:

      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

【讨论】:

    猜你喜欢
    • 2018-08-25
    • 2021-12-06
    • 1970-01-01
    • 2018-05-03
    • 2014-03-20
    • 2015-11-02
    • 2014-09-06
    • 2017-06-20
    • 1970-01-01
    相关资源
    最近更新 更多