我一直在编写一个代码,可以逐行从excel中导出一些数据。它似乎工作,但它给了我一个“没有If的Else”错误。我不能为我的生活找到原因,即使我采取了必要的预防措施(我认为),它仍然在做着。
Sub test()
Dim objword As Object
Dim fNameAndPath As Variant
Dim fNameAndPath2 As Variant
fNameAndPath = "C:\test"
fNameAndPath2 = "C:\test"
i = 2
While Not IsEmpty(Cells(i, 3))
If Cells(i, 9) = "End of Probation Per" Then _
Set objword = CreateObject("Word.Application")
objword.Visible = True
objword.Documents.Open (fNameAndPath)
objword.Activate
With objword.ActiveDocument
.Bookmarks("EmpName").Range.Text = Cells(i, 2).Value
.Bookmarks("EndDate").Range.Text = Cells(i, 11).Value
filename = Application.GetSaveAsFilename("MyFileName.xls", _
"Excel files,*.xlsx", 1, "Select your folder and filename")
If TypeName(filename) = "Boolean" Then Exit Sub
ActiveWorkbook.SaveAs filename
ActiveWorkbook.Close False
Else: Cells(i, 9).Font.Italic = True
End If
i = i + 1
Wend
End Sub
欢迎修复此基本编码错误的建议!
答案 0 :(得分:1)
你没有End With
。让我们用一些格式编辑它以揭示错误
Sub test
Dim objword As Object
Dim fNameAndPath As Variant
Dim fNameAndPath2 As Variant
fNameAndPath = "C:\test"
fNameAndPath2 = "C:\test"
i = 2
While Not IsEmpty(Cells(i, 3))
If Cells(i, 9) = "End of Probation Per" Then
Set objword = CreateObject("Word.Application")
objword.Visible = True
objword.Documents.Open (fNameAndPath)
objword.Activate
With objword.ActiveDocument
.Bookmarks("EmpName").Range.Text = Cells(i, 2).Value
.Bookmarks("EndDate").Range.Text = Cells(i, 11).Value
filename = Application.GetSaveAsFilename("MyFileName.xls", _
"Excel files,*.xlsx", 1, "Select your folder and filename")
End With '### THIS WAS MISSING
If TypeName(filename) = "Boolean" Then Exit Sub 'single line If so no end if necessary
ActiveWorkbook.SaveAs filename
ActiveWorkbook.Close False
Else
Cells(i, 9).Font.Italic = True
End If
i = i + 1
Wend
End Sub
答案 1 :(得分:-1)
在&#34之后添加换行符然后"并更改下面的代码,因为它不会在退出子
之后执行If TypeName(filename) = "Boolean" Then
Exit Sub
ActiveWorkbook.SaveAs filename
ActiveWorkbook.Close False
Else: Cells(i, 9).Font.Italic = True
End If