2013-09-27 143 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'不會創建一個新實例,因爲已經打開了一個實例。 –