Version: Excel 2021.
Open the VBA interface: shortcut key Alt+F11
. (or 视图-宏
).
Record a macro, and then look at the code of the macro, you can basically understand the virtues of conventional Excel operations in VBA.
For example, if I need to modify a constituency, first
录制宏
, then modify the constituency casually, and then stop recording, and I will know the keyword corresponding to the constituencySelection
.
After knowing the routine Excel operations, the most important thing is to write logic.
I wrote a simple VBA logic:
Sub AddSpace()
' 将选中的单元格的第二个大写字符的前面加一个空格
' 例如"ZhangSanSan"改成"Zhang SanSan"
i = 1
For Each test In Selection '遍历选中的
ops = 2
If (Len(test) > 2) Then '只修改长度大于2的字符串
For ii = 2 To Len(test) '遍历单元格的字符串(从第二个开始)
a = Mid(test, ii, 1) '字符串取值
If (a >= "A" And a <= "Z") Then '判断是否是大写
ops = ii '确定位置
Exit For '跳出for循环
End If
Next ii
If Mid(test, ops - 1, 1) <> " " Then '如果已经有空格,则不加
test2 = Mid(test, 1, ops - 1) & " " & Mid(test, ops)
Selection(i) = test2
End If
End If
i = i + 1
If (i >= 10000) Then '不处理10000以上的数据量
Exit For
End If
Next
End Sub
If you can understand the above program, you can clearly understand the following common problems in programming:
- selection traversal;
- String traversal, modification, splicing of cell strings;
- Condition judgment;
- Exit the loop (VBA has no continue);
Effect:
Attach a Python version.
I thought it was a long time to write in python for 20 minutes, but I didn't expect that the VBA program took me an hour. Although to be honest, its running speed in this program is far better than python, because I have done redundant operations such as "opening excel, filling in line by line, saving excel" in python.
Python version:
# author: shandianchengzi
# description: 用大写字符分割字符串
# status: complete
from win32com import client
fp='E:/workspace/py/工作1.xlsx'
def myFunc():
ws = wb.Worksheets[0]
for i in range(1,1614):
oldStr=list(ws.Cells(i, 1).Value)
ops=0
for j in range(1,len(oldStr)):
if (oldStr[j].isupper()):
ops=j
break
oldStr.insert(ops, ' ')
ws.Cells(i, 2).Value = ''.join(oldStr)
excel = client.DispatchEx('Excel.Application')
excel.Visible = True #是否可视化
wb = excel.Workbooks.Open(fp)
myFunc()
wb.Save()
wb.Close(True)
excel.Quit()