问题
This image shows the initial state of the columns, in UK format. #value if I try to add 1 to it, False if I run ISNUMBER() on it, and True if I use text to column on entry to swap period & comma. Once in true state, I can use the numbers, but for some this true state isn't reached. Instead, they result in the error handling convert to number diamond that pops up.
I used the recorder to record the text to columns procedure on a single column. It produces the following:
Range(Range("J2"), Range("J2").End(xlDown)).Select
Selection.TextToColumns Destination:=Range("J2"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
I have roughly 60 columns this must be applied to and my current solution is to have 60 entries of this block of code with different cell references, which ends up running very slowly.
- Is there a way to apply this to multiple columns?
- Is there some code I can delete out of this block to make it run faster?
I could not find answers while searching.
回答1:
Though using selection is not ideal, there are ways to utilize Selection to support more efficient looping of columns to .texttocolumns.
Note that I do not have any additional arguments in texttocolumns, which may or may not be a problem for you depending on your use.
Private Sub TTC()
If Selection.Count = 1 Then
Selection.TextToColumns
Else
Dim sr As Long, sc As Long, er As Long, ec As Long, col As Long
sr = Selection.Row 'start row
sc = Selection.Column 'start column
er = Selection.Rows.Count + sr - 1 'end row
ec = Selection.Columns.Count + sc - 1 'end column
For col = sc To ec
Range(Cells(sr, col), Cells(er, col)).TextToColumns
Next col
End If
End Sub
In the above, the selection is used to define variables, which are then specific ranges to loop through and apply the texttocolumns.
Additional note, I have not set this up to skip columns, e.g., would not work for non-contiguous ranges; this will work for contiguous ranges, across multiple rows/columns.
In terms of speeding up the process, you can use turn off screenupdating, calculation, and displayalerts, prior to executing.
来源:https://stackoverflow.com/questions/58396409/using-text-to-columns-macro-on-multiple-columns