【发布时间】:2016-12-21 02:38:24
【问题描述】:
我想自动化我的 VBA,而不必每次有人更改单元格时都运行 VBA。我尝试使用 Worksheet_Change(ByRef Target As Range) 但出现编译器错误。下面是我没有使用 worksheet_change 事件的代码。这是一个共享的 Excel 工作簿,因此每次有人填写新单元格或进行更改时,我都需要将其自动化。
Option Explicit
Public Sub getEmails()
Dim names As Range, findRange As Range
Dim splitNames
Dim selectedEmails As String, i As Long, lRow As Long
Set names = Sheets("Email").Range("B1:C23") ' names range from lookup table from different worksheet
With Sheets("Sheet2")
' loop column K untill last row with data (staring from row 2 >> modify where you data starts)
For lRow = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row
' fill array directly from cell
splitNames = Split(.Range("B" & lRow), ",")
For i = 0 To UBound(splitNames)
' find the range matching the name
Set findRange = names.Find(What:=Trim(splitNames(i)), LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
' if match found, get the email and store to selected emails variable
If Not findRange Is Nothing Then
If selectedEmails = "" Then ' first email of this row
selectedEmails = findRange.Offset(0, 1).Value
Else ' add a ";" to separate email addresses
selectedEmails = selectedEmails & "; " & findRange.Offset(0, 1).Value
End If
End If
Next i
.Range("C" & lRow) = selectedEmails
' clrear all variables and arrays for next cycle
Erase splitNames
selectedEmails = ""
Next lRow
End With
End Sub
【问题讨论】:
-
你看到了什么错误?
-
我认为您正在使用 B 列中人员姓名的电子邮件地址更新 C 列(其中 B 列中的每个单元格都有多个人,以逗号分隔)。因此,您需要 (1) 当
Sheet2!B中的值发生变化时更新单行的Sheet2!C和 (2) 当Email!B:C中的任何单元格发生变化时更新Sheet2!C:C。那是对的吗?您的Worksheet_Change事件代码是什么不起作用,它在哪个工作表中? -
我收到此错误“编译错误:过程声明与具有相同名称的事件或过程的描述不匹配”@dgorti
-
这段代码工作正常,但我只想自动化它。我只是将 getEmails() 更改为 Private Sub Worksheet_Change(ByRef Target As Range)
-
您需要将
Worksheet_Change子代码放入Sheet2代码模块中,是吗?