我有以下代码:
Sub TestSaves()
Dim fName, fNameNoEx, SaveName As String
Dim fldr As FileDialog
CurrPath = ActiveDocument.Path
'CurrPath = "C:\temp"
If Left(CurrPath, 4) = "http" Then
PathSep = "/"
Else
PathSep = "\"
End If
FileNumber = FreeFile
OutputFile = CurrPath & PathSep & "fred.txt"
MsgBox OutputFile
Open OutputFile For Output As #FileNumber
Print #FileNumber, "Hello World"
Close #FileNumber
End Sub
当我的
CurrPath = ActiveDocument.Path
处于活动状态时,我得到
运行时错误 52(错误的文件名或编号)
在这种情况下,CurrPath 看起来像:
当我的
CurrPath = "C:\temp"
处于活动状态时,它就可以工作。
我想将另一个文件保存在与原始文档相同的位置,无论它是在本地还是在 OneDrive/Sharepoint 上。
我能弄清楚如何做到这一点的唯一方法是:
Environ("temp")
)Close #FileNumber
之后,我从临时文件夹中重新打开我的文件Documents.Open filename:=TmpFile
ActiveDocument.SaveAs2 filename:=OutputFile, FileFormat:=wdFormatText
,然后再次关闭文件。有点笨拙,当 .txt 打开、保存和关闭时,我最终在处理结束时屏幕闪烁(是的,我确实尝试在打开时设置
visible:=false
,但这也会影响 ActiveDocument
)。
但是...它有效。
如果您使用 OneDrive 应用程序将文件夹同步到本地计算机,则可以使用 此解决方案 将
ActiveDocument.Path
返回的 OneDrive Url 转换为本地路径,使用提供的函数,如下所示 GetLocalPath(ActiveDocument.Path)
。
顺便说一句,我建议使用
ThisDocument
而不是 ActiveDocument
。因此,包括该功能,那就是 GetLocalPath(ThisDocument.Path)
您生成的代码可能如下所示:
'Depends on function GetLocalPath, provided here:
'https://stackoverflow.com/a/73577057/12287457
Sub TestSaves()
Dim fName, fNameNoEx, SaveName As String
Dim fldr As FileDialog
CurrPath = GetLocalPath(ThisDocument.Path)
FileNumber = FreeFile()
OutputFile = CurrPath & Application.PathSeparator & "fred.txt"
MsgBox OutputFile
Open OutputFile For Output As #FileNumber
Print #FileNumber, "Hello World"
Close #FileNumber
End Sub
您可以使用 VBA 打开文件并将其直接保存到 SharePoint ...文件名和地址需要是 URL(例如 https://[domain].sharepoint.com/sites/[foldername]/Shared Documents/[子文件夹]/[文件名]) 并附加“?web=1”。