错误52 - 文件编号错误

时间:2013-11-26 05:21:17

标签: vba outlook runtime-error

以下VBA代码应该打开一个文本文件,将其中的数字读取到文本文件中,在文本文件中的数字中加1,然后将新数字保存在文本文件中。

我目前在指定的行(While Not EOF(filenum))上收到错误52。我该如何解决这个问题?

Public Sub Items_ItemAdd(Item As Outlook.MailItem)
Dim filenum As Integer
Dim current_number As String
Dim fileName As String
Dim objNS As Outlook.NameSpace
Set objNS = GetNamespace("MAPI")
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
filenum = FreeFile()
fileName = "G:\Infrastructure Services\Engineering Services\Hazard Report Number.txt"
Open fileName For Input As filenum
While Not EOF(filenum) '*error 52 - Bad file number
Line Input #filenum, current_number
Close filenum
Wend


If Item.Class = olMail Then
    If Left$(Item.Subject, 29) = "Hazard Identification Report" Then
        Dim Msg As Outlook.MailItem
        Dim NewForward As Outlook.MailItem
        Dim myFolder As Outlook.MAPIFolder
        Dim olApp As Outlook.Application
        Dim olNS As Outlook.NameSpace

        Set Msg = Item
        Set NewForward = Msg.Forward
        Set olApp = Outlook.Application
        Set olNS = olApp.GetNamespace("MAPI")

        strSender = ""
strsenderName = Msg.SenderEmailAddress





If strsenderName = "EX" Then
  Set objSender = itm.Sender
  If Not (objSender Is Nothing) Then
    Set objExchUser = Sender.GetExchangeUser()
    If Not (objExchUser Is Nothing) Then
      strSender = objExchUser.PrimarySmtpAddress
    End If
  End If
Else
  strSender = strsenderName
End If



        With NewForward
            .Subject = "Hazard report reciept number: & "
            .To = strSender
            .HTMLBody = "TYhank you for your email"
            .Send
        End With
        End If
    End If
    Close filenum

ExitProc:
    Set NewForward = Nothing
    Set Msg = Nothing
    Set olApp = Nothing
    Set olNS = Nothing


End Sub

1 个答案:

答案 0 :(得分:4)

您正在While ... Wend循环中关闭文件。所以它读取第一行,关闭文件,然后检查EOF(filenum)filenum不再是打开文件的有效句柄,因此错误。

只需将Close语句移出循环:

While Not EOF(filenum) '*error 52 - Bad file number
    Line Input #filenum, current_number
Wend
Close filenum

我猜你正确缩进你的代码会帮助你发现错误!