使用vba中的if语句为excel连接或连接基于单元格值的文本数组

时间:2017-05-16 16:58:04

标签: excel-vba vba excel

我是VBA编程的新手,我正在尝试根据其在If语句中的值向单元格添加文本。我已经尝试过使用find语句,但它以null值结束,最终,我需要这个来处理3个不同的值。我不确定我需要将“MyCell”定义为变量。它没有任何方式。当我运行下面的代码时,它说MyCell是一个无效的限定符。

 Sub Macro2()
'
' Macro to insert Text into Cells

Dim i As Long
Dim MyCell As String

Worksheets("Tax").Active
For i = 2 To Range("H" & Rows.Count).End(xlUp).Row
    ActiveCell.Select
    MyCell = ActiveCell.Value

        If MyCell.Value = "State Tax" Then
            MyCell = Join("State Tax - ", Range(i, "D"))

        ElseIf MyCell.Value = "SUI" Then
            MyCell = Join("SUI - ", Range(i, "D"))

        ElseIf MyCell.Value = "Local Tax" Then
            MyCell = Join("Local Tax - ", Range(i, "D"))
        End If

    Next i
End Sub

1 个答案:

答案 0 :(得分:0)

你不需要myCell。如果你这样做,你会将它作为范围实例化,而不是字符串。试试这个,看看它是否完成了你需要的东西。

Sub Macro2()
'
' Macro to insert Text into Cells

Dim i As Long

With Worksheets("Tax")
For i = 2 To .Range("H" & Rows.Count).End(xlUp).Row
        If .Range("H" & i).Value = "State Tax" Then
             .Range("H" & i).Value = "State Tax - " & .Range("D" & i).Value

        ElseIf .Range("H" & i).Value = "SUI" Then
            .Range("H" & i).Value = "SUI - " & .Range("D" & i).Value

        ElseIf .Range("H" & i).Value = "Local Tax" Then
            .Range("H" & i).Value = "Local Tax - " & .Range("D" & i).Value
        End If

    Next i
End With
End Sub