连接单元格,但之前检查值-Excel VBA

时间:2018-09-13 12:01:06

标签: excel vba excel-vba

因此,到目前为止,我想将D column中的值连接到J column中的值,但是我想检查column D中的值是否已经存在J column,我使用了InStr,直到它遇到一个已经具有不需要连接的值的单元格时,它才起作用

脚本:

    Sub Concatenate()
    Dim counter As Integer
    Dim myValue As Variant
    myValue = InputBox("For how many rows do you want to concatenate D w/ Js")
    d = 4 ' Concatenate from this column
    j = 10 'Concatenate to this column
    ' counter -> Counter to iterate through all the cells in both columns
    For counter = 2 To myValue
      If Cells(counter, d).Value <> "" Then
        If InStr(1, Cells(counter, j).Value, Cells(counter, d).Value) = 0 Then
          Cells(counter, j).Value = Cells(counter, j).Value & "," & Cells(counter, d).Value
        Else
          ' Had to leave it blank
        End If
      End If

    Next counter

End Sub

示例

How it looks                         How it should look
|    D    |   J     |                 |    D     |      J      |
|    a    |   1     |result of code =>|    a     |     1,a     |
|    b    |   2,b   |result of code =>|    b     |     2,b     | <= (nothing modified)
|    c    |   3     |result of code =>|    c     |     3,c     |
|   abc   |   42    |result of code =>|   abc    |     42,abc  |

当遇到值| b | 2,b |的行时,程序停止,其余的保持不变

3 个答案:

答案 0 :(得分:0)

打错字

中的,因为您有变量 contor

For contor = 2 To myValue

但随后您要递增变量计数器

Next counter

计数器更改为 con ,它应该可以工作

祝你好运

答案 1 :(得分:0)

好吧,查看您发布的输出后:

How it looks                         How it should look
|    D    |   J     |                 |    D     |      J      |
|    a    |   1     |result of code =>|    a     |     1,a     |
|    b    |   2,b   |result of code =>|    b     |     2,b     | <= (nothing modified)
|    c    |   3     |result of code =>|    c     |     3,c     |
|   abc   |   42    |result of code =>|   abc    |     42,abc  |

此代码应该起作用。 应用宏之前的数据图片:

enter image description here

应用宏后,我得到:

enter image description here

我的代码:

Sub Concatenate()

Dim Counter As Long
Dim myValue As Variant
myValue = InputBox("For how many rows do you want to concatenate D w/ Js")

For Counter = 2 To myValue Step 1
    If Right(Range("J" & Counter).Value, Len(Range("D" & Counter).Value)) <> Range("D" & Counter).Value Then Range("J" & Counter).Value = Range("J" & Counter).Value & "," & Range("D" & Counter).Value
Next Counter

End Sub

答案 2 :(得分:0)

有效的最终代码:

Sub Concatenate()
Dim counter As Integer
Dim myValue As Variant
myValue = InputBox("For how many rows do you want to concatenate D w/ Js")
d = 4 ' Concatenate from this column
j = 10 'Concatenate to this column
' counter -> Counter to iterate through all the cells in both columns
For counter = 2 To myValue
  If Cells(counter, d).Value <> "" Then
    If InStr(1, Cells(counter, j).Value, Cells(counter, d).Value) = 0 Then
      Cells(counter, j).Value = Cells(counter, j).Value & "," & Cells(counter, d).Value
    Else
      ' Blank
    End If
  End If
Next counter

End Sub