当单元格由宏更改时执行Worksheet_Change

时间:2016-09-22 15:21:32

标签: excel-vba excel-vba-mac vba excel

我已经从最初的帖子中编辑了这个问题,因为我意识到没有宏会激活Worksheet_change函数。

我正在使用UserForm来创建一个宏来编辑单元格。然后我希望工作表从一个单元格中获取值并在其他单元格中创建值。这是手动工作,但不是通过宏!

来自UserForm:

Sub WriteOperatingFunds(dates, description, money)
  Dim ws2 As Worksheet
  Set ws2 = ThisWorkbook.Worksheets("OperatingFunds")

  'find first empty row in database
  irow = ws2.Cells.Find(What:="*", SearchOrder:=xlRows, _
    SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

  ws2.Cells(irow, 1).value = dates
  ws2.Cells(irow, 2).value = description
  ws2.Cells(irow, 3).value = money
End Sub

从工作表中:

Private Sub Worksheet_Change(ByVal Target As Range)
  Dim change As String
  Dim chngRow As Long
  Dim IncRow As Long
  Dim ExpRow As Long
  Dim TotRow As Long
  Dim Income As Long
  Dim Expense As Long
  Dim Total As Long

  Set ws = ThisWorkbook.Worksheets("OperatingFunds")

  TotRow = ws.Cells(ws.Rows.Count, 5).End(xlUp).Row 'finds bottom of 'Total' Column
  'looks for target in range
  If Not Application.Intersect(Target, ws.Range("C3", ws.Cells(TotRow + 1,        4))) Is Nothing Then
    change = Target.Address(False, False)
    chngRow = ws.Range(change).Row

    'Get the last rows of range columns
    IncRow = ws.Range("C" & ws.Rows.Count).End(xlUp).Row
    ExpRow = ws.Range("D" & ws.Rows.Count).End(xlUp).Row

    Application.EnableEvents = False 'to prevent endless loop & does not record changes by macro
    'if Total column is empty
    If ws.Cells(chngRow, 5) = "" Then
        Income = Application.WorksheetFunction.Sum(ws.Range("C3", ws.Cells(TotRow + 1, 3)))
        Expense = Application.WorksheetFunction.Sum(ws.Range("D3", ws.Cells(TotRow + 1, 4)))
        Total = Income + Expense
        ws.Cells(chngRow, 5) = Total
    'if total column is not empty (i.e. needs to be rewritten)
    ElseIf ws.Cells(chngRow, 5) <> "" Then
        Income = Application.WorksheetFunction.Sum(ws.Range("C3", ws.Cells(chngRow, 3)))
        Expense = Application.WorksheetFunction.Sum(ws.Range("D3", ws.Cells(chngRow, 4)))
        Total = Income + Expense
        ws.Cells(chngRow, 5) = Total
    End If
  Else
    MsgBox "Else is thrown."
    Exit Sub
  End If

  Application.EnableEvents = True 'so that future changes can be read
End Sub

1 个答案:

答案 0 :(得分:0)

我不想自命不凡地回答我自己的问题,但我的朋友帮助我找到了解决方案,也许这会帮助其他人遇到类似的问题。

关键因素是我使用UserForm上的按钮将数据写入单元格。实际上并没有&#34;改变&#34;我写的单元格#34;单元格(#,#)=值&#34;。在我的代码中,我需要将Sub公开,然后

Call ThisWorkbook.Worksheets("worksheetname").Worksheet_Change(Target.address)

这使一切顺利! 他帮助我的例子:https://bytes.com/topic/access/answers/767919-trigger-click-event-button-another-form