比较列 – VBA

我想通过比较两列来在Excel中创build一个简单的macros。 例如。

ABC --------------------------- 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 = "myemail@example.com" olMail.Subject = "Testing" olMail.Body = "THis is the body" olMail.Send End Sub 

现在我只想比较两列,并将“姓名”存储在某个地方,并将其发送到电子邮件的正文中。

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

 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 

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

 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 = "myemail@example.com" .Subject = "Testing" .Body = MyData(i, 1) .Display '.Send End With End If Next i End Sub