【发布时间】:2016-12-12 15:47:51
【问题描述】:
此程序的功能是将一个单元格的数据转换为行,即将逗号分隔的条目拆分为新行。
我是 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
在这方面需要建议。
【问题讨论】:
-
改用 x= .Range
-
出现对象定义错误。
-
除非您在工作表对象的任何子对象之前使用点(例如 Range),否则您的 with 命令不会执行任何操作。因此,您还需要 .cells 以及我可能没有发现的任何其他文件
-
我使用过 .Range 和 Sheet1.Range 但每次都会出错。
-
ws.Range,无处不在,别再用没有任何意义的变量名了,你自己搞糊涂了