对于项目,我正在尝试创建一个在C#中创建并在Access中使用的自定义库。为此,我做了以下事情:
using System.Runtime.InteropServices;
。DLL的目的是通过SMTP处理/发送邮件,包含多个地址,附件等。为此,我创建了以下内容:
[Serializable(), ClassInterface(ClassInterfaceType.AutoDual), ComVisible(true)]
public class SendOPSMail
{
public void SendMail(string ToAddress, string Subject, string Body, string FromAddress, ref string[] attachments, string CCAddress = "", string BCCAddress = "")
{
//Check if attachment is null or not else assign empty value
attachments = attachments ?? new string[0]; //after research it seems that I cant assign a NULL array in VBA/DLL and need to be passed by ref - so this can be deleted
using (var msg = new MailMessage())
using (var client = new SmtpClient("spamfilter.mySpamFilter.com", 587))
{
msg.IsBodyHtml = true;
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.SubjectEncoding = System.Text.Encoding.UTF8;
if (!string.IsNullOrEmpty(FromAddress))
{
msg.From = new MailAddress(FromAddress);
}
string[] splitTO = ToAddress.Split(delimiterChars);
foreach (var TO in splitTO)
{
msg.To.Add(new MailAddress(TO));
}
//handle attachments
foreach (string value in bijlagen)
{
msg.Attachments.Add(new Attachment(value));
}
//set the remaining required fields
msg.Body = Body;
msg.Subject = Subject;
//Send mail
client.Send(msg);
}
}
}
我在我的Access引用中包含了DLL,这一切都很好。虽然我试着打电话给我的班级如下:
Dim test As OPS2Mail.SendOPSMail
Set test = New OPS2Mail.SendOPSMail
test.SendMail "some@email.com", "Test", "<b>Test</b>", "some@email.com", AttachmentArray
我收到(访问/ VBA)错误438, the property or method is not supported for this object.
所以在研究之后我发现了一个帖子,他们说我必须在DLL中创建一个主类,用函数调用类(SendOPSMail),然后在VBA中我首先初始化Main类以调用另一个类。所以在DLL代码中我添加了:
public class MainOPSMail
{
public SendOPSMail GetSendOPSMail()
{
return new SendOPSMail();
}
}
并在VBA / Access中将其更改为:
Dim testMain As OPS2Mail.MainOPSMail
Set testMain = New OPS2Mail.MainOPSMail
Dim test as OPS2Mail.SendOPSMail
set test = testMain.GetSendOPSMail
test.SendMail "some@email.com", "Test", "<b>Test</b>", "some@email.com", AttachmentArray
这似乎有效,但为什么呼叫会如此麻烦?有没有办法让它更简单?就像我创建一个类一样,将其设为com-visible
并使用一个简单Dim
和set
(或者甚至没有设置?)来调用它。
很抱歉,如果该帖子包含大量愚蠢的问题,但我对此有点新见,特别是DLL。
答案 0 :(得分:0)
在这里做了一些阅读:http://jumbloid.blogspot.nl/2009/12/making-net-dll-com-visible.html我发现我可以使用public interface
轻松调用我的DLL类。
所以我添加的是:
public interface ISendMail
{
void SendMail(string ToAddress, string Subject, string Body, string FromAddress, ref string[] attachments, string CCAddress = "", string BCCAddress = "");
}
我在班上添加了一个默认构造函数:public SendOPSMail() { }
我的类继承自创建的接口:public class SendOPSMail : ISendMail
现在我可以像这样轻松调用VBA中的方法/类:
Dim test As OPS2Mail.SendOPSMail
Set test = New OPS2Mail.SendOPSMail