代码在任何活动工作表而不是sheet1上运行

时间:2016-12-11 19:30:46

标签: excel vba excel-vba slice

该程序的功能是将一个单元格的数据转换为将逗号分隔条目拆分为新行的行。

我是VBA的新用户,使用 stackoverflow 参考问题中的vba代码,我试图将代码限制为 sheet1 ,但每当我运行它时,它都会执行活动工作表上的任务,而不是sheet1。

pip install boto==2.44

在这方面需要提供建议。

1 个答案:

答案 0 :(得分:4)

正如评论中所提到的,如果您没有利用它允许您将With(等)简化为ws.Range的事实,则.Range毫无意义。

尝试将代码更改为:

Sub SliceNDice()
    Dim objRegex As Object
    Dim X
    Dim Y
    Dim lngRow As Long
    Dim lngCnt As Long
    Dim tempArr() As String
    Dim strArr

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        Set objRegex = CreateObject("vbscript.regexp")
        objRegex.Pattern = "^\s+(.+?)$"
        'Define the range to be analysed

        '"." is needed to qualify which sheet Range, Cells, and Rows applies to.
        'Without a "." (or a "ws."), each property would refer to the active sheet.
        X = .Range("A1", .Cells(.Rows.Count, "b").End(xlUp)).Value2
        ReDim Y(1 To 2, 1 To 1000)
        For lngRow = 1 To UBound(X, 1)
            'Split each string by ","
            tempArr = Split(X(lngRow, 2), ",")
            For Each strArr In tempArr
                lngCnt = lngCnt + 1
                'Add another 1000 records to resorted array every 1000 records
                If lngCnt Mod 1000 = 0 Then ReDim Preserve Y(1 To 2, 1 To lngCnt + 1000)
                Y(1, lngCnt) = X(lngRow, 1)
                Y(2, lngCnt) = objRegex.Replace(strArr, "$1")
            Next
        Next lngRow
        'Dump the re-ordered range to columns C:D

        'Only write output if there is something to write
        If lngCnt > 0 Then
            'Need to also specify that the following line applies to ws, rather
            'than to the active sheet
            .Range("C1").Resize(lngCnt, 2).Value2 = Application.Transpose(Y)
        End If
    End With
End Sub

或者,你可以摆脱With ws块并在你在该表上使用的每个属性/方法前面加ws,例如。

X = ws.Range("A1", ws.Cells(ws.Rows.Count, "b").End(xlUp)).Value2