Worksheet_Changemacros – 更改多个单元格

我写了一个macros,虽然它的function,它不是什么需要。 这是一个交互式的清单,打破了机器的多个领域,如果他们正在工作检查他们,然后这将更新一个主列表与多个部分。 但是,它一次只能处理一个单元格,并且需要能够一次处理多个单元格(包括行和列)。 这是我现在的代码:

'Updates needed: ' Make so more than one cell works at a time ' in both x and y directions Private Sub Worksheet_Change(ByVal Target As Excel.range) Dim wb As Workbook Dim mWS As Worksheet Dim conName As String Dim mCol As range Dim mCon As Integer Dim count As Long Dim cell As range Dim y As String count = 1 y = "" Set wb = ActiveWorkbook Set mWS = wb.Sheets("Master") Set mCol = mWS.range("B:B") mCon = 0 'Selects the name of the string value in which we need to search for in master list If Target.Column < 100 Then ThisRow = Target.Row conName = ActiveSheet.Cells(ThisRow, "B") y = Target.Value End If 'search for matching string value in master list For Each cell In mCol If cell.Value = conName Then mCon = count Exit For End If count = count + 1 Next 'mark as "x" in Master list Dim cVal As Variant Set cVal = mWS.Cells(count, Target.Column) cVal.Value = y End Sub 

发生了什么 – 如果我向下拖动多个行或列的“x”,我的代码会在y = Target.Value处中断,并且只会更新首先select的单元格和主列表中的对应单元。 它应该做的是,如果我拖放到多行的列“X”,它应该更新我正在工作的表和主列表中的所有人。 我一次只设置一个单元格的macros,我不知道如何设置它来拖放多行的“x”值

我认为你需要一个For ... Each迭代在Target ,以便与多个单元格一起工作。 正如Michael在评论中指出的那样, _Change事件只会触发一次,但Target反映所有已更改的单元,所以您应该能够遍历Target范围。 我testing了这个简单的事件处理程序:

 Private Sub Worksheet_Change(ByVal Target As Range) Dim myRange As Range Dim myCell As Range Set myRange = Target For Each myCell In myRange.Cells Debug.Print myCell.Address Next End Sub 

我不能在你的数据/工作表上明显地testing,但我认为它应该把你放在正确的轨道上。

 Private Sub Worksheet_Change(ByVal Target As Excel.range) Dim wb As Workbook Dim mWS As Worksheet Dim conName As String Dim mCol As range Dim mCon As Integer Dim count As Long Dim cell As range Dim y As String count = 1 y = "" Set wb = ActiveWorkbook Set mWS = wb.Sheets("Master") Set mCol = mWS.range("B:B") mCon = 0 'Add some new variables: Dim myRange as Range Dim myCell as Range Set myRange = Target Application.EnableEvents = False '## prevents infinite loop For each myCell in myRange.Cells If myCell.Column < 100 Then ThisRow = myCell.Row conName = ActiveSheet.Cells(ThisRow, "B") y = myCell.Value End If 'search for matching string value in master list For Each cell In mCol If cell.Value = conName Then mCon = count Exit For End If count = count + 1 Next 'mark as "x" in Master list Dim cVal As Variant Set cVal = mWS.Cells(count, Target.Column) cVal.Value = y Next Application.EnableEvents = True '## restores event handling to True End Sub 

您需要使用ForEach循环遍历单元格。

此外,你可能会更好地使用Selection对象而不是Target

 Private Sub Worksheet_Change(ByVal Target As Range) Application.EnableEvents = False Application.ScreenUpdating = False Application.Calculation = xlCalculationManual For Each cell In Selection Debug.Print cell.Address Next cell Application.EnableEvents = True Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic Exit Sub