Arrays Excel VBA交换单元格(如果值为数组)
阿比盖尔伯里南卡罗来纳州 阿比盖尔伯里南卡罗来纳州 南卡罗来纳州阿比盖尔伯里 *这个想法是自动将错误的州与家乡进行交换,如南卡罗来纳州和阿比盖尔伯里州 我有5001行,试图访问特定的两列(家乡、家乡州)。 我正在尝试编写一个vba脚本,如果在home town列中错误地放置了home state值,则该脚本将交换home town和home state值。我试图通过在工作表中使用一个数组来实现这一点,该数组引用了所有50个状态的范围,并且应该在if语句中进行检查 然而,我不断得到不匹配,定义应用程序定义或对象定义错误。我敢肯定是新手犯的错误 这是我的尝试:Arrays Excel VBA交换单元格(如果值为数组),arrays,excel,if-statement,for-loop,vba,Arrays,Excel,If Statement,For Loop,Vba,阿比盖尔伯里南卡罗来纳州 阿比盖尔伯里南卡罗来纳州 南卡罗来纳州阿比盖尔伯里 *这个想法是自动将错误的州与家乡进行交换,如南卡罗来纳州和阿比盖尔伯里州 我有5001行,试图访问特定的两列(家乡、家乡州)。 我正在尝试编写一个vba脚本,如果在home town列中错误地放置了home state值,则该脚本将交换home town和home state值。我试图通过在工作表中使用一个数组来实现这一点,该数组引用了所有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
Dim states()作为字符串
状态=范围(“N1:N50”)。值
暗x等长
长得一样暗
'遍历d列中的行
对于x=1到5001
'范围(“D”和x)。选择
'for数组和if语句的循环
对于y=1到50
状态()=单元(y,n)
如果是的话,我想这里有些东西可能会对你有所帮助。假设我的工作表设置如下:
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...
然后,我可以使用以下内容检查家乡
中的任何条目是否实际上是州名,如果是,则将该值与家乡
交换
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
在states()=单元格(y,n)
中,程序中没有定义n
变量。这可能是您的错误的来源吗?您可以简单地使用Vlookup函数。你能在帖子中粘贴数据的屏幕截图吗?此外,IIRC,在为数组指定一系列值之前,你需要正确地重拨状态数组。第一个错误是将数组声明为字符串。要将范围值吸收到这样的数组中,它必须是:Dim states()作为变量