我正在尝试在MS Access VBA中创建一个If-Then-Else语句。 此语句用于打开特定的word文档,但如果word文档不存在,则打开另一个word文档。
下面是我的代码,如果我摆脱了其他但它无法解决我的问题,它会起作用,因为我需要else语句。
Dim appword As Word.Application
Dim doc As Word.Document
Dim Path As String
Set appWord = GetObject(, "word.application")
If Err.Number <> 0 Then
Set appWord = New Word.Application
appWord.Visible = True
End If
If Value = "Excused" Then
Path = "C:\...existing docx"
Else
Path = "C:\...different docx"
End If
Set doc = appWord.Documents.Open(Path, , True)
答案 0 :(得分:1)
使用appword.Documents.Add
返回新文档。您还应该在使用GetObject
时添加错误处理程序。您也可以考虑使用Len(Dir(Path))
来测试文件是否存在。
Dim appword As Word.Application
Dim doc As Word.Document
Dim Path As String
On Error Resume Next
Set appword = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set appword = New Word.Application
appword.Visible = True
End If
On Error GoTo 0
If Value = "Excused" Then
Path = "C:\...existing docx"
Set doc = appword.Documents.Open(Path, , True)
Else
Set doc = appword.Documents.Add
End If
答案 1 :(得分:1)
验证文档是否存在,如果没有,则添加新文档。
Sub T()
Dim appword As Word.Application
Dim doc As Word.Document
Dim Path As String
Set appword = New Word.Application
appword.Visible = True
If Len(Dir("C:\...existing docx")) > 0 And Value = "Excused" Then
Path = "C:\...existing docx"
Set doc = appword.Documents.Open(Path, , True)
Else
Set doc = appword.Documents.Add
End If
End Sub