【发布时间】:2017-06-02 21:54:59
【问题描述】:
我对 VBA 还很陌生,我已经与这段小代码斗争了一天多,所以我求助于你,我的知识上司。
我有以下情况:
最终目标是得到 4 个变量:ADR1、ADR2、ADR3 和 ADR4。这些变量应该由 IF 函数创建,该函数将 4 组单元格与一个目标单元格(在 IF 和 ELSIF 部分中找到)进行比较。
当找到这些单元格之间的匹配项时,我想将某个单元格值分配给变量 ADR1。将值添加到变量 ADR1 后,循环将再次开始以将值分配给 ADR2,依此类推,直到 ADR4。
为了创建四个变量 ADR1-4,我使用了“for I = 1 to 4”语句。
当我执行此代码时,我在'ADR(I) = Cells(1, "B").Value' 行得到一个'类型不匹配错误',所以第一个 ELSIF 部分。
谁能向我解释为什么我会出现这种不匹配以及应该如何解决它?
Sub variable_incrementation()
'resetting variables
ADR1 = 0
ADR2 = 0
ADR3 = 0
ADR4 = 0
Dim N As Integer
N = 4
Dim ADR(1 To 4) As Long
Dim I As Long
For I = 1 To 4
Do
'N is supposed to increase by steps of four due to the target cells that contain the matching information
N = N + 4
If Activesheet.Cells.(2, "A") = Activesheet.Cells.(N, "D") Or _
Activesheet.Cells.(3, "A") = Activesheet.Cells.(N, "D") Then
ADR(I) = Activesheet.Cells.(1, "A").Value
ElseIf Activesheet.Cells.(2, "B") = Activesheet.Cells.(N, "D") Or _
Activesheet.Cells.(3, "B") = Activesheet.Cells.(N, "D") Or _
Activesheet.Cells.(4, "B") = Activesheet.Cells.(N, "D") Then
ADR(I) = Activesheet.Cells.(1, "B").Value
ElseIf Activesheet.Cells.(2, "C") = Activesheet.Cells.(N, "D") Or _
Activesheet.Cells.(3, "C") = Activesheet.Cells.(N, "D") Or _
Activesheet.Cells.(4, "C") = Activesheet.Cells.(N, "D") Or _
Activesheet.Cells.(5, "C") = Activesheet.Cells.(N, "D") Then
ADR(I) = Activesheet.Cells.(1, "C").Value
ElseIf Activesheet.Cells.(2, "D") = Activesheet.Cells.(N, "D") Or _
Activesheet.Cells.(3, "D") = Activesheet.Cells.(N, "D") Or _
Activesheet.Cells.(4, "D") = Activesheet.Cells.(N, "D") Then
ADR(I) = Activesheet.Cells.(1, "D").Value
Else
End If
Loop Until (IsEmpty(ADR) = False) Or (N <= 43)
Next I
For J = 1 To 4
MsgBox (ADRJ)
Next
End Sub
【问题讨论】:
-
确保 ActiveSheet 上的值,因为这是您在没有说明该单元格中范围对象的父项的情况下搜索的内容,而不是数字而不是文本或错误。
-
Cells() 方法需要两个整数值(rowindex 和 columnindex),为什么要提供字符串?
-
@avb 列可以是字符串,VBA会解析为列号。
-
@ScottCraner,真的很有效,Excel 永远不会停止让我吃惊:)