【问题标题】:Expand on recorded "Text To Column" macro展开录制的“文本到列”宏
【发布时间】:2026-01-03 01:20:11
【问题描述】:

我正在尝试(对于我的学习和功能宏一样多)将我录制的宏转换为以下函数。

我收到错误“没有选择要解析的数据”

我认为我的问题是第二个 Sub 中的 Selection.TextToColumns Destination:=Cells(1, (cNum + 1)).Select。我不知道"iDel" 是不是我写的方式有问题,因为我还没有知道如何更改Destination:=Range("I1")

地点:

cNum 是要解析的列
iCol 是要插入的列数
iDel 是解析分隔符
Sheet Number 中的iSn

任何见解都有帮助

这是固定版本2: (这是最后一个版本(我不知道我可以把 Array 放在“fTexeToColumn”中,试了一下,它成功了)

Sub TexeToColumn()
'1st is the column to be parsed
'2nd is the number of columns to insert
'3rd is the parsing delimiter
'4th is the Sheet Number
'Array Set New Col Header Names, add as many name as 2nd parameter is equal to

fTexeToColumn "8", "3", "[", "2", Array("New Col Name1", "New Col Name2", "New Col Name3")

End Sub

Sub fTexeToColumn(cNum As Long, iCol As Long, iDel As String, iSn As Long, Headers As Variant)
'cNum is the column to be parsed
'iCol is the number of columns to insert
'iDel is the parsing delimiter
'iSn is the Sheet Number

 Dim i As Long
 Dim BaseWks As Worksheet

 '~~> Set your sheet here
 Sheets(iSn).Select

 '~~>Adding Columns
 For colx = 1 To iCol Step 1
 Columns(cNum + colx).Insert Shift:=xlToRight
 Next

 '~~>Column to be parsed
 Columns(cNum).Select

'~Set destination range here
Selection.TextToColumns Destination:=Cells(1, (cNum + 1)), DataType:=xlDelimited, _
  TextQualifier:=xlNone, ConsecutiveDelimiter:=False, Tab:=False, _
  Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
  :=iDel, FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True

'~~>Delete original column
Columns(cNum).Delete

'Set Header Names
 Set BaseWks = ThisWorkbook.Worksheets(iSn)

  For i = LBound(Headers) To UBound(Headers)
  BaseWks.Cells(1, i + cNum) = Headers(i)
  Next i

End Sub

【问题讨论】:

  • 你想把它变成什么?您向我们展示了什么不起作用,您希望它做什么?
  • 感谢 pnuts 解决了所有问题

标签: excel vba


【解决方案1】:

OP 正确识别了两个问题:

i) Selection.TextToColumns 目标:=Cells(1, (cNum + 1)).Select and
ii) iDel

对于前者,.Select 是一个语法错误(在“设置目标范围”时,该列已被选中),对于后者,iDel 已被定义为 [ 字符串,而使用 @如果所需的分隔符是 i,则 987654324@ 将起作用(因为允许使用单个字符作为 Text To Columns 的分隔符)。

正如现在在 OP 中所反映的那样,修复方法是删除 .SelectiDel 周围的引号。

【讨论】:

  • 非常有帮助的评论。再次感谢
最近更新 更多