自动调用VBA代码后,它不会运行

时间:2019-01-23 05:47:25

标签: excel vba

我有一个名为Splittext的宏,该宏在工作表Macro Process的单元格“ B4”中发生更改时被调用,当我调用它时它不起作用,但在手动运行时它起作用。代码没有错误

Sub splitText()
    Dim wsS1 As Worksheet 'Sheet1
    Dim textstring As String, warray() As String, counter As Integer, strg As String

    Set wsS1 = Sheets("OUTPUT 1")
    wsS1.Activate

    textstring = Range("A2").Value
    warray() = Split(textstring, ">")

    For counter = LBound(warray) To UBound(warray)
        strg = warray(counter)
        Cells(counter + 3, 1).Value = Trim(strg)
    Next counter

    textstring = Range("B2").Value
    warray() = Split(textstring, ">")

    For counter = LBound(warray) To UBound(warray)
        strg = warray(counter)
        Cells(counter + 3, 2).Value = Trim(strg)  
    Next counter

    textstring = Range("C2").Value
    warray() = Split(textstring, ">")

    For counter = LBound(warray) To UBound(warray)
        strg = warray(counter)
        Cells(counter + 3, 3).Value = Trim(strg)
    Next counter
End Sub

该代码应分隔表“输出1”的单元格(“ A2”)(“ B2”)(“ C2”)中存在的文本

这就是我调用代码的方式

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Set Target = Range("B4")
    If Target.Value = "Completed" Then
        Call splitText
    End If
End Sub

1 个答案:

答案 0 :(得分:1)

目前尚不清楚您要监视哪些表的更改,但这对我有用:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Set Target = sh.Range("B4")
    If Target.Value = "Completed" Then
        Application.EnableEvents = False
        splitText
        Application.EnableEvents = True
    End If
End Sub


Sub splitText()
    Dim warray() As String, i As Long, c As Range
    For Each c In ThisWorkbook.Sheets("OUTPUT 1").Range("A2:C2").Cells
        warray = Split(c.Value, ">")
        For i = LBound(warray) To UBound(warray)
            c.Offset(i + 1, 0).Value = Trim(warray(i))
        Next i
    Next c
End Sub