vba - 如何循环宏?
问题描述
为什么这个 VBA 代码不起作用?这些文档使用了一种特殊的字体,称为rage, wait, arial。我想遍历文档的每个字母,并且每当.Font = "*rage*"
我想遍历十几个字母时。(我的中风 - 耐心。)
Sub grandma()
Dim doc As Document
Set doc = ActiveDocument
Dim Counter As Integer
For i = 1 To 6
doc.Range.Characters.Count
If doc.Range.Characters(i).Font.Name = "*rage*" Then
doc.Range.Characters(i).Font.Name = "Waiting for the Sunrise"
End If
If doc.Range.Characters(i).Font.Name = "*wait*" Then
doc.Range.Characters(i).Font.Name = "Rage Italic"
End If
If doc.Range.Characters(i).Font.Name = "*arial*" Then
doc.Range.Characters(i).Font.Name = "Arial Nova Cond Light"
End If
j = i
MsgBox "Hi! " & i
Next i
End Sub
解决方案
使用Like
运算符而不是=
使用通配符时。
Option Explicit
Sub grandma()
Dim doc As Document
Set doc = ActiveDocument
Dim i As Integer
For i = 1 To 6
With doc.Range.Characters(i).Font
Select Case True
Case .Name like "*rage*"
.Name = "Waiting for the Sunrise"
Case .Name Like "*wait*"
.Name = "Rage Italic"
Case .Name Like "*arial*"
.Name = "Arial Nova Cond Light"
End Select
End With
MsgBox "Hi! " & i
Next i
End Sub
旁注:我个人的偏好是避免使用数据类型
Integer
,而是使用Long
- 除非处理会溢出的遗留应用程序 aLong
或出于某种原因我不想放弃这两个额外的内存字节(讽刺)。尤其是在处理单个 word 文档字符时- 一个文档可能包含数千个字符,您可以快速溢出 Integer。看看为什么使用整数而不是长整数?了解更多信息。
推荐阅读
- django - Django Admin: Link to Admin-Interface of ForeignKey beneath add and modify
- jquery - 如何扩展引导导航元素的所有父项?
- angular - Angular Material Autocomplete 设置滚动顶部
- batch-file - How to get grep to run command after found first response in line-buffer?
- c# - LINQ - 将当前和以前的数据合并到一行
- python - 将多条正文线转换为列表理解
- node.js - Mongoose findById 查询不返回结果。对象始终为空。
- git - 无法连接到存储库:无法创建 http 代理 uri
- python - 如何在 Django 中呈现多个表单
- python - dataframe combine_first does not work as well as fillna