VBA在文本中选择案例循环

时间:2012-06-26 20:56:18

标签: excel vba excel-vba

尝试循环遍历一系列单元格,并根据另一个单元格中的文本值为它们分配标签。因此,如果Cell J2 =“This Text”那么Cell A2 =“This Label”

截至目前,我一直收到运行时错误号424,说明所需的对象

Private Function getPhase(ByVal cell As Range) As String
Select Case cell.Text
    Case "Text1"
        getPhase = "Label1"
    Case "Text2"
        getPhase = "Label2"
End Select
End Function


Sub setPhase()
Dim cycle As Range
Dim phase As Range


Set cycle = Range("J2:J10")
Set phase = Range("A2:A10")

For Each cell In phase.Cells
    phase.Text = getPhase(cycle)
Next cell

End Sub

3 个答案:

答案 0 :(得分:7)

你已经得到了答案:)让我在我的帖子中做一些解释虽然:)

你无法使用它。

phase.Text = getPhase(cycle)

.Text Readonly 属性。即你不能写信,但只能从中读。您必须使用.Value

其次,如果要从同一行中选择值,则无需定义第二个范围。您可以随时使用.Offset财产。见这个

Option Explicit

Sub setPhase()
    Dim rng As Range, phase As Range

    Set phase = Sheets("Sheet1").Range("A2:A10")

    For Each rng In phase
        rng.Value = getPhase(rng.Offset(, 9))
    Next
End Sub

Function getPhase(ByVal cl As Range) As String
    Select Case cl.Value
        Case "Text1"
            getPhase = "Label1"
        Case "Text2"
            getPhase = "Label2"
    End Select
End Function

Select Case cell.Text也没有错,因为你只是从中读取。但是,使用.Value总是好的。原因是.Value属性返回单元格的实际值,其中.Text属性返回屏幕上显示的文本。在较高版本的Excel中,Text的大小约为8k字符。另一方面,.Value最多可存储32k个字符。

答案 1 :(得分:6)

我改变了循环。这假设两个范围是相同的长度

Function getPhase(ByVal cell As Range) As String

   Select Case cell.Value
    Case "Text1"
        getPhase = "Label1"
    Case "Text2"
        getPhase = "Label2"
  End Select


End Function


Sub setPhase()
Dim cycle As Range
Dim phase As Range


Set cycle = ThisWorkbook.Sheets("myexample").Range("J2:J10")
Set phase = ThisWorkbook.Sheets("myexample").Range("A2:A10")

Dim i As Integer
For i = 1 To phase.Cells.Count
    phase.Cells(i).Value = getPhase(cycle.Cells(i))
Next i

End Sub

......或者siddharth建议使用公式。

或者通过VBA执行公式:

Sub setPhase()

Dim phase As Range
Set phase = Excel.ThisWorkbook.Sheets("Sheet1").Range("A2:A10")
phase.Value = "=IF(J2=""Text1"",""Label1"",IF(J2=""Text2"",""Label2"",""""))"

End Sub

答案 2 :(得分:5)

这是我的版本:

Private Function getPhase(ByVal cell As Range) As String
    Select Case cell.Text
        Case "Text1"
            getPhase = "Label1"
        Case "Text2"
            getPhase = "Label2"
    End Select
End Function


Sub setPhase()
    Dim cycle As Range
    Dim phase As Range


    Set cycle = ActiveSheet.Range("b2:b10")
    Set phase = ActiveSheet.Range("A2:A10")

    For Each cell In phase.Cells
        cell.Value = getPhase(cycle.Cells(cell.Row, 1))
    Next cell

End Sub