我试图通过比较两列来在excel中创建一个简单的宏。 例如。
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 = "myemail@example.com"
olMail.Subject = "Testing"
olMail.Body = "THis is the body"
olMail.Send
End Sub
现在我只想比较两列并在某处存储“name / s”并将其发送到电子邮件正文中。
答案 0 :(得分: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
答案 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 = "myemail@example.com"
.Subject = "Testing"
.Body = MyData(i, 1)
.Display '.Send
End With
End If
Next i
End Sub