运行在任何活动工作表而不是工作表1上的代码
此程序的function是将一个单元格的数据转换为将逗号分隔的条目拆分为新行的行。
那么我是新的VBA,使用从stackoverflow参考问题的VBA代码,我试图限制代码Sheet1,但每当我运行它,它执行活动工作表上的任务而不是Sheet1。
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, "$1") Next Next lngRow 'Dump the re-ordered range to columns C:D [c1].Resize(lngCnt, 2).Value2 = Application.Transpose(Y) End With End Sub
在这方面需要build议。
正如评论中提到的那样,如果你没有使用这个事实,那么你的With
就毫无意义,它允许你将ws.Range
(etc) .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