|
发表于 2024-7-23 13:40:35
|
显示全部楼层
感谢你的耐心,鱼油!错误 438 通常是因为我们尝试在对象上使用不支持的方法或属性。在这里,我们需要确保正则表达式正确设置,并且分割操作能够顺利进行。
为了简化并保证分割的功能,我们可以通过将“\”和“,”组合成一个分隔符来手动进行分割,而不使用正则表达式。这是一种更直接的方法。以下是改进后的完整代码:
- Sub ExpandSheetMacro()
- Dim wsExpand As Worksheet
- Dim wsSource As Worksheet
- Dim lastRow As Long
- Dim lastCol As Long
- Dim i As Long
- Dim j As Long
- Dim splitData As Variant
-
- ' 设置源工作表
- Set wsSource = ThisWorkbook.Sheets("Sheet1")
-
- ' 检查是否存在“展开表”
- On Error Resume Next
- Set wsExpand = ThisWorkbook.Sheets("展开表")
- On Error GoTo 0
-
- If Not wsExpand Is Nothing Then
- ' 如果存在,清空内容
- wsExpand.Cells.Clear
- Else
- ' 如果不存在,创建新工作表
- Set wsExpand = ThisWorkbook.Sheets.Add
- wsExpand.Name = "展开表"
- End If
-
- ' 复制A列和B列
- wsSource.Range("A:A").Copy wsExpand.Range("A1")
- wsSource.Range("B:B").Copy wsExpand.Range("B1")
-
- ' 按“\”和“,”分割C列内容
- lastRow = wsSource.Cells(wsSource.Rows.Count, "C").End(xlUp).Row
-
- For i = 1 To lastRow
- ' 将C列的内容按“\”和“,”分割
- splitData = Split(Replace(Replace(wsSource.Cells(i, 3).Value, "", ","), ",", ","), ",") '替换字符
-
- ' 将分割后的数据填入“展开表”的C列及以后各列
- For j = LBound(splitData) To UBound(splitData)
- wsExpand.Cells(i, j + 3).Value = Trim(splitData(j)) ' 从C列开始填充
- Next j
- Next i
-
- ' 找到“展开表”的最后一列非空列
- lastCol = wsExpand.Cells(1, wsExpand.Columns.Count).End(xlToLeft).Column
-
- ' 复制sheet1的D列到J列
- Dim col As Integer
- For col = 4 To 10 ' D到J列
- wsSource.Range(wsSource.Cells(1, col), wsSource.Cells(lastRow, col)).Copy wsExpand.Cells(1, lastCol + 1)
- lastCol = lastCol + 1
- Next col
-
- ' 调整列宽
- wsExpand.Columns.AutoFit
- End Sub
复制代码
### 更新要点:
1. **分割方法**:通过先替换反斜杠`“\”`为逗号`“,”`,然后将所有逗号分割,这样就能实现用两个分隔符的目的。
2. **安全性**:移除了正则表达式的部分,确保了代码的安全性和可读性。
这次应该能顺利运行了!再试试看这个更新版的代码,如果还有问题,请及时告诉我,我会继续帮助你的!希望这个代码能如鱼油般顺滑,轻松解决问题!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|