2013-09-27 190 views
0

我終於有一些工作代碼,但我得到一個「類型不匹配」的錯誤,一旦Module2函數完成,我不知道爲什麼。類型不匹配VBA不能找到

如果我經過它,它逐步通過module2上的「結束函數」,然後我得到類型不匹配,但它確實發送電子郵件。任何幫助將是偉大的

此VBA代碼分3部分。

1子

Sub Workbook_open() 

    Call Module1.GetData 

    End Sub 

2模塊1

Public EmailAddress As String 
    Public CompanyNumber As String 
    Public Name As String 
    Public GroupComp As String 

    Function GetData() 

    Dim LastRow As String 
    Dim rng As Range 


    LastRow = Cells(Rows.Count, "K").End(xlUp).Row 

    For Each rng In Range("K2:K" + LastRow) 

     If Not rng.Value = vbNullString Then 
      Select Case rng.Value 
       Case 1 
        Case Is = "True" 
        Let EmailAddress = ActiveCell.Offset(0, -5).Value 
        Let CompanyNumber = ActiveCell.Offset(0, -9).Value 
        Let Name = ActiveCell.Offset(0, -8).Value 
        Let GroupComp = ActiveCell.Offset(0, -7).Value 
        Call Module2.Email(EmailAddress, CompanyNumber, Name, GroupsComp) 
       Case 2 
        Case Is = "False" 
      End Select 

     End If 
    Next 
    End Function 

3模塊2

 Function Email() 
    'MsgBox (EmailAddress) 
    Set objMessage = CreateObject("CDO.Message") 
    objMessage.Subject = "Stuffl " & (GroupComp) 
    objMessage.From = "Department Name([email protected])" 
    objMessage.Cc = "Department Name([email protected])" 
    objMessage.To = (EmailAddress) 
    MsgBox (EmailAddress) 
    objMessage.TextBody = "TEST" 

     objMessage.Configuration.Fields.Item _ 
     ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 

     objMessage.Configuration.Fields.Item _ 
     ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "x.x.x.x" 

     objMessage.Configuration.Fields.Item _ 
     ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 

     objMessage.Configuration.Fields.Update 

     objMessage.Send 

    End Function 
+0

在'Module1.GetData'中,您使用4個參數調用'Module2.Email',但是在它的定義中沒有參數?另外,爲什麼使用'Function'而不是'Sub'呢?你定義的函數會返回'Variant'對象,這是必要的嗎? – Ioannis

+0

'函數電子郵件()'爲什麼它的函數,如果它不返回任何東西?看看這個[link](http://stackoverflow.com/questions/16964917/send-an-email-when-workbook-is-saved/16965103#16965103) – Santosh

回答

1

更改Function Email()

Function Email(emailaddress As String, companynumber As String, name As String, groupscomp As String) 

你是不是實際調用郵件功能,這就是問題所在,我認爲

+0

Sub調用Module1函數,Module1調用Module2函數。它發送郵件,以便它調用它。但生病嘗試上述沒有看起來有效的 – k3eper

+0

。你能向我解釋爲什麼它有效嗎?我從GetData函數將變量傳遞給Mail函數,我不明白爲什麼我必須在郵件函數中再次指定變量。 – k3eper

1

「我不明白,爲什麼我不得不在郵件中再次指定變量」

不管何時你傳遞值傳遞給子或函數,您必須定義該子或函數,以便期望將值傳遞給它。所以這是行不通的:

Sub Foo() 
    Dim i as Integer 
    i = 5 
    Call Bar(i) 
End Sub 

Sub Bar() 
    i = i + 2 
End Sub 

因爲Bar()不期望有任何東西傳遞給它。這將起作用:

Sub Foo() 
    Dim i as Integer 
    i = 5 
    Call Bar(i) 
End Sub 

Sub Bar(i as Integer) 
    i = i + 2 
End Sub 

因爲你現在告訴Bar期望一個整數被傳遞給它。

希望有幫助。

+0

感謝您的解釋讚賞 – k3eper