以文本方式查看主题

-  Foxtable(狐表)  (http://www.foxtable.com/bbs/index.asp)
--  专家坐堂  (http://www.foxtable.com/bbs/list.asp?boardid=2)
----  [求助]word文档重命名  (http://www.foxtable.com/bbs/dispbbs.asp?boardid=2&id=138017)

--  作者:天一生水
--  发布时间:2019/7/20 19:34:00
--  [求助]word文档重命名
如图,读取word文档中的红色框中的“案号”,为该文档重命名,报如下错误,请老师指教,如何处理?
谢谢!

图片点击可在新窗口打开查看此主题相关图片如下:截屏图片 (1).jpg
图片点击可在新窗口打开查看

Dim dlg As New OpenFileDialog
dlg.MultiSelect = True   ’多文件
If dlg.ShowDialog = DialogResult.OK Then
    For Each fl As String In dlg.FileNames
        Dim str As String = ""
        Dim app As New MSWord.Application
        try
            Dim doc = app.Documents.Open(fl)
            
            For Each k As object In doc.Paragraphs
                If k.Range.text.Contains("鲁") AndAlso k.Range.text.Contains("号") AndAlso k.Range.text.Length < 20 Then
                    str = k.Range.text
                    msgbox(fl)
                    msgbox(str)
                    Exit For
                End If
            Next
            app.quit
            
        catch ex As exception
            msgbox(ex.message)
            app.quit
        End try
        FileSys.RenameFile(fl, str & ".doc")
    Next
End If

--  作者:有点蓝
--  发布时间:2019/7/21 20:00:00
--  
str = str.trim().replace(vbcr,"").replace(vblf,"")
FileSys.RenameFile(fl, str & ".doc")
--  作者:天一生水
--  发布时间:2019/7/21 20:48:00
--  
谢谢蓝老师!
代码里有“app.quit”,为什么还提示文件占用?

图片点击可在新窗口打开查看此主题相关图片如下:截屏图片 (1).jpg
图片点击可在新窗口打开查看


--  作者:有点蓝
--  发布时间:2019/7/21 22:47:00
--  
word进程的退出有时需要一定的时间的,试试暂停1秒后再重命名:

System.Threading.Thread.Sleep(1000)
str = str.trim().replace(vbcr,"").replace(vblf,"")
FileSys.RenameFile(fl, str & ".doc")