我将收到一个每周文件,其中一列必须使用“,”分隔符进行拆分,但其中目标列的位置和该列中值的长度未知,并且会有所不同
Split的目标列中的某些值具有前导0,如果将字符输入到格式为General的列,则当前正在删除这些值。在执行拆分之前,拆分的目标列始终格式化为文本。必须保留除目标列以外的列中的所有值。
在运行以下过程后,目标列似乎将转换为“常规”而不是预期的“文本”格式。我不确定如何确保列保持文本并保留前导0。
Current Sub:
Sub Test_Split_Column()
Dim LR As Long, i As Long, LC As Integer
Dim x As Variant
Dim r As Range, iCol As Integer
On Error Resume Next
Set r = Application.InputBox("Click in the column to split by", Type:=8)
On Error GoTo 0
If r Is Nothing Then Exit Sub
On Error Resume Next
ActiveSheet.UsedRange.SpecialCells(xlCellTypeBlanks).Value = " "
On Error GoTo 0
iCol = r.Column
Application.ScreenUpdating = False
LC = Cells(1, Columns.Count).End(xlToLeft).Column
LR = Cells(Rows.Count, iCol).End(xlUp).Row
Columns(iCol).Insert
For i = LR To 1 Step -1
With Cells(i, iCol + 1)
If InStr(.Value, ",") = 0 Then
.Offset(, -1).Value = .Value
Else
x = Split(.Value, ",")
.Offset(1).Resize(UBound(x)).EntireRow.Insert
.Offset(, -1).Resize(UBound(x) - LBound(x) + 1).Value = Application.Transpose(x)
End If
End With
Next i
Columns(iCol + 1).Delete
LR = Cells(Rows.Count, iCol).End(xlUp).Row
With Range(Cells(1, 1), Cells(LR, LC))
On Error Resume Next
.SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
On Error GoTo 0
.Value = .Value
End With
With ActiveSheet.UsedRange
.Replace What:=" ", Replacement:=vbNullString, LookAt:=xlWhole
End With
Application.ScreenUpdating = True
End Sub
下面链接的原始数据,当前输出和所需输出示例:
非常感谢您提供的任何帮助!谢谢!
答案 0 :(得分:0)
'
可用于强制excel将任何值视为文本。
x = Split(Replace("'" & .Value, ",", ",'"), ",")
答案 1 :(得分:0)
如果将一个String数组而不是Variant数组分配给一个范围,即使值是数字,这些值也将设置为字符串。
这样的事情应该有效。
Dim strValue As String
strValue = "000123,1234,0001"
Dim x As Variant
x = Split(strValue, ",")
ReDim result(0 To UBound(x), 0 To 0) As String
Dim i As Integer
For i = 0 To UBound(x)
result(i, 0) = x(i)
Next i
ActiveSheet.Range("A1:A3").Value = result