我导出的 CSV 报告通常包含大约 200-5000 行或 30-60 列。使用录制宏功能,我录制了一个经过“文本到列向导”的宏,生成的宏依赖于行大小,我该如何解决这个问题?
Sub Macro1()
Range("A1:A2313").Select
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1 _
), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array _
(20, 1), Array(21, 1), Array(22, 1), Array(23, 1), Array(24, 1), Array(25, 1), Array(26, 1), _
Array(27, 1), Array(28, 1), Array(29, 1), Array(30, 1), Array(31, 1), Array(32, 1), Array( _
33, 1), Array(34, 1), Array(35, 1), Array(36, 1), Array(37, 1), Array(38, 1), Array(39, 1), _
Array(40, 1), Array(41, 1), Array(42, 1), Array(43, 1), Array(44, 1), Array(45, 1), Array( _
46, 1), Array(47, 1), Array(48, 1)), TrailingMinusNumbers:=True
End Sub
答案1
您可以使用 For 循环找到行数,LastRow = ActiveSheet.Cells(ActiveSheet.rows.Count, "A").End(xlUp).row
然后循环遍历它。
FieldInfo 参数是一个可选参数,因此可以将其删除以类似于下面的代码。
Sub Text2Column()
'Delimited and Comma Separated
Application.ScreenUpdating = False
LastRow = ActiveSheet.Cells(ActiveSheet.rows.Count, "A").End(xlUp).row
For r = 1 To LastRow
ActiveSheet.Cells(r, 1).Select
Selection.TextToColumns Destination:=Range(ActiveSheet.Cells(r, 1), ActiveSheet.Cells(r, 1)), dataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, _
Comma:=True, Space:=False, Other:=False, TrailingMinusNumbers:=True
Next r
Application.ScreenUpdating = True
End Sub