如何批量替换Excel宏中的SharePoint外部链接?
可以通过VBA代码一键批量替换所有宏中的SharePoint外部链接前缀,具体操作如下:
- 打开合并后的目标工作簿,按下
Alt+F11打开VBA编辑器 - 点击菜单栏的插入 -> 模块,新建一个代码模块
- 将以下代码粘贴到模块中:
Sub RemoveExternalMacroLinks() Dim vbComp As VBComponent Dim regex As Object Set regex = CreateObject("VBScript.RegExp") ' 匹配所有SharePoint格式的工作簿链接前缀 regex.Pattern = "'https?://[^']+\.xlsm'!" regex.Global = True ' 遍历工作簿内所有代码模块 For Each vbComp In ThisWorkbook.VBProject.VBComponents ' 处理标准模块和工作表/工作簿代码模块 If vbComp.Type = vbext_ct_StdModule Or vbComp.Type = vbext_ct_Document Then Dim allLines As String allLines = vbComp.CodeModule.Lines(1, vbComp.CodeModule.CountOfLines) allLines = regex.Replace(allLines, "") vbComp.CodeModule.DeleteLines 1, vbComp.CodeModule.CountOfLines vbComp.CodeModule.AddFromString allLines End If Next vbComp Set regex = Nothing MsgBox "外部链接前缀已全部移除", vbInformation End Sub
- 按下
F5运行这个宏,或者在编辑器中右键点击宏名选择运行
注意事项
- 运行前需在Excel信任中心开启信任对VBA项目对象模型的访问:依次点击「文件」->「选项」->「信任中心」->「信任中心设置」->「宏设置」,勾选对应选项
- 操作前请务必备份目标工作簿,防止代码执行异常导致数据丢失
内容的提问来源于stack exchange,提问作者David Færgeman
相关产品推荐
相关产品推荐

