2013-09-27 184 views
1

我想通过比较两列来在Excel中制作一个简单的宏。例如, 。比较列 - VBA

A  B    C 
--------------------------- 
john  1    5 
tom  2    2 
henry 3    7 
Mike  4    4 

所以在这种情况下,我比较1,5,2,2,3,7和4,4。 稍后我会通过电子邮件发送相同的行。 这是我发送电子邮件代码..

Sub sendEmail() 

Dim olApp As Outlook.Application 
Set olApp = CreateObject("Outlook.Application") 

    Dim olMail As Outllok.MailItem 
    Set olMail = olApp.CreateItem(olMailItem) 

    olMail.To = "[email protected]" 
    olMail.Subject = "Testing" 
    olMail.Body = "THis is the body" 
    olMail.Send 


End Sub 

现在我只是想比较一下两列存储“名称/秒”的地方,并在电子邮件的正文中发送他们..

回答

1

嗨,你可以做类似的事情:

Dim i As Integer 
Dim name As String 

'Loop over your rows 
For i = 0 to 100 

If Worksheets("YourSheet").Cells(i,2).Value = Worksheets("YourSheet").Cells(i,3).Value Then 

'Now get the name value 
name = Worksheets("YourSheet").Cells(i,1).Value 

'Now do what you want with your name 

End If 

Next i 
+0

+ 1不错的一个:) –

0

这是一个使用数组更快的方法。如果您有大量的行,则循环遍历行将非常缓慢。

Sub Sample() 
    Dim olApp As Object, olMail As Object 
    Dim MyData 
    Dim i As Long 

    Set olApp = GetObject(,"Outlook.Application") 

    '~~> Store the range in the array 
    '~~> I have taken 1000 rows. Change as applicable 
    MyData = ThisWorkbook.Sheets("Sheet1").Range("A1:C1000") 

    For i = LBound(MyData) To UBound(MyData) - 1 
     If MyData(i, 2) = MyData(i, 3) Then 
      Set olMail = olApp.CreateItem(0) 

      '~~> This will give you the names 
      Debug.Print MyData(i, 1) 

      With olMail 
       .To = "[email protected]" 
       .Subject = "Testing" 
       .Body = MyData(i, 1) 
       .Display '.Send 
      End With 
     End If 
    Next i 
End Sub 
+0

谢谢你的答案男人。我得到一个错误“运行时错误”-2147221020(800401e4)'自动化错误语法无效'.. 为什么我尝试调试,它移动到这一行.. “Set olApp = GetObject(”Outlook.Application“) “ – user2771150

+0

尝试使用'CreateObject'(在你自己的代码中的那个)而不是'GetObject' – sam092

+0

@ Sam092:这不是必须的。 :) Outlook是唯一的MS-Office应用程序,不管你使用GetObject还是CreateObject都不重要。原因很简单,'Createobject'不会创建一个新实例,因为已经打开了一个实例。 –