Excel如何把分散的数据单元格列条向左移到一起
1、首先打开Microsoft Office Excel 2007,新建文档并保存文件名《Excel如何把分散的数据单元格列条向左移到一起 .xlsm》(演示文件,下面代码复制到能运行宏的工作簿都可以)如图。

2、然后按下快捷键ALT+F11打开VBE(宏)编辑界面,然后点菜单栏【插入】下拉中列表中点【模块(M)】如图。

3、然后插入了一个模块1,在代码框中复制如下代码:
Option Base 1
Sub 数据向左移动()
'2020-9-26 21:43:18
Dim myr As Range, i As Long, j As Long, r As Long, c As Long
Dim k As Long, n As Long, x As Long, mb, m
Set myr = Selection
m = myr.Address
r = myr.Rows.Count
c = myr.Columns.Count
k = 0: n = 0: x = 0
ReDim mb(r, 2)
For i = 2 To c
For j = 1 To r
If j = 1 Then
If myr.Cells(j, i).Value <> "" Then
x = x + 1
mb(x, 1) = j
k = 1
Else
n = 1
End If
Else
If myr.Cells(j, i).Value <> "" Then
k = k + 1
If k = 1 Then
x = x + 1
mb(x, 1) = j
n = 0
End If
Else
n = n + 1
If n = 1 Then
If k >= 1 Then mb(x, 2) = j - 1
k = 0
End If
End If
End If
If j = r And myr.Cells(j, i).Value <> "" Then mb(x, 2) = j
Next j
For j = 1 To x
If mb(j, 1) = mb(j, 2) Then
If myr.Cells(mb(j, 1), i - 1).Value = "" Then
myr.Cells(mb(j, 1), i).Cut Destination:=myr.Cells(mb(j, 1), i - 1)
End If
Else
n = 0
For k = mb(j, 1) To mb(j, 2)
If myr.Cells(k, i - 1).Value <> "" Then
n = 1
Exit For
End If
Next k
If n = 0 Then
For k = mb(j, 1) To mb(j, 2)
myr.Cells(k, i).Cut Destination:=myr.Cells(k, i - 1)
Next k
End If
End If
Next j
Set myr = Range(m)
k = 0: n = 0: x = 0
Erase mb
ReDim mb(r, 2)
Next i
End Sub
4、以上操作动态过程如下:

5、回到工作表窗口,首先选原数据表,然后运行【数据向左移动】宏(菜单栏中点【视图】中下列表中【宏】列表【查看宏(V)】打开宏对方框,选该宏名,执行),输出结果右边数据单元格条向左移(有些数据需要运行多次才能得到最终结果),运行过程如下图。




6、如果觉得这篇经验帮到了您,请点击下方的 “投票点赞" 或者“收藏”支持我!还有疑问的话可以点击下方的 “我有疑问”,谢谢啦!