如何在不更改工作表名称的情况下将相同的代码复制到不同的工作表?

时间:2014-06-29 20:17:17

标签: vba excel-vba outlook-vba excel

如何编写代码以在复制到其他工作表时自动检测工作表名称

Sub SendEmail(address As String, subject As String, mail_body As String)

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

    Dim olMail As Outlook.MailStream
    Set olMail = olApp.CreateItem(olMailItem)

        olMail.To = address
        olMail.Subject = subject
        olMail.Body = mail_body
        olMail.Send


    Sub SendAllEmail()

    row_number = 2

    Do
    DoEvents

    row_number = row_number + 1
    //the sheet1 is hardcoded for the particular sheet which want to convert i to a variable
    Call SendEmail(Sheet1.Range("A" & row_number)Sheet2.Range("B3"),Sheet2.Range("B4"))

    Loop Until row_number = 6

End Sub

3 个答案:

答案 0 :(得分:0)

如果你想参考代码所在的表格(不知道它是哪个),只需使用Me - 例如

Me.Range("A" & row_number)

但正如Alex Bell建议的那样,更有效的方法可能是更改代码以处理任何工作表,并在ThisWorkbook中(或在其自己的模块中)编写一次。例如:

在ThisWorkbook中:

Sub example(objSheet as Worksheet)
  'I can refer to a cell on objSheet like so:
  SendEmail objSheet.Range("A1")
End Sub

可以从特定工作表上的代码调用,如下所示:

example(Me)

请注意,如果您的工作表中包含在该工作表中运行代码的按钮,而您只是复制工作表,则新按钮仍会调用旧工作表上的代码(即使新工作表中包含该工作表的副本)代码也是!)

答案 1 :(得分:0)

我认为您需要Application.ActiveSheet,这是当前有效的工作表。

答案 2 :(得分:0)

//当我在另一张表上运行此代码时,它表示找不到成员或数据方法

Sub SendEmail(address_mail As String, subject_mail As String, mail_body As String)


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

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

    olMail.To = address_mail
    olMail.Subject = subject_mail
    olMail.Body = mail_body

   On Error GoTo Cancel

    olMail.Send

Cancel:

End Sub
Sub SendMassEmail()

Dim addressString As String
addressString = ""
row_number = 2



Do
DoEvents

    row_number = row_number + 1
    addressString = addressString & Me.Range("C" & row_number) & ";"


    Loop Until row_number = 999
Call SendEmail(addressString, Me.Range("F9"), Me.Range("F10"))

End Sub

Sub repeatFunction(objSheet As Worksheet)
SendMassEmail objSheet.Range("C" & row_number)
End Sub