1

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

截至目前,我不断收到运行时错误号 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
4

3 回答 3

7

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

你不能使用这个。

phase.Text = getPhase(cycle)

.Text只读属性。即你不能写入它,而只能从中读取。你必须使用.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 中,文本的限制约为 8k 个字符。.Value另一方面,最多可以存储 32k 个字符。

于 2012-06-27T06:00:34.480 回答
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
于 2012-06-26T21:26:42.693 回答
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
于 2012-06-26T21:40:27.320 回答