代码 运行 在任何活动 sheet 而不是 sheet1

Code running on any active sheet instead of sheet1

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

好吧,我是 VBA 的新手,使用 Whosebug 参考问题中的 vba 代码,我试图将代码限制为 sheet1 但是每当我 运行 它时,它都会在 active sheet 而不是 sheet 上执行任务]1.

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

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, "")
    Next
Next lngRow
 'Dump the re-ordered range to columns C:D

[c1].Resize(lngCnt, 2).Value2 = Application.Transpose(Y)
End With
End Sub

这方面需要建议。

如评论中所述,如果您不利用它允许您将 ws.Range(等)快捷方式转换为 .Range,那么您的 With 将毫无意义。

尝试将您的代码更改为:

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, "")
            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 块,并在 sheet 上使用的每个 property/method 前面包含 ws,例如

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