【发布时间】:2020-07-02 17:17:56
【问题描述】:
我从最初的帖子中编辑了这个问题,因为我意识到没有宏会激活 Worksheet_change 功能。
我正在使用用户窗体来创建宏来编辑单元格。然后我希望工作表从一个单元格中获取值并在其他单元格中创建值。这可以手动工作,但不能通过宏!
来自用户窗体:
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
【问题讨论】:
-
我不确定我是否理解您的解释。
Worksheet_Change代码在哪个工作表中? -
我还没有看到完整的代码,但我认为你需要
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)而不是Private Sub Worksheet_Change(ByVal Target As Range)来满足这两个工作表。此代码将位于ThisWorkbook -
“Worksheet_Change”代码在 .worksheets("OperationFund") 中的工作表,但我什至最近在该工作表上做了一个按钮,甚至该工作表中的宏都没有触发更改。
-
afaik,你的假设是错误的。如果您在工作表上有
worksheet_change()事件,并且该工作表中的范围发生任何更改,则worksheet_change()事件将触发。这就是我们有Application.EnableEvents的原因,因此我们可以关闭该功能并避免无休止的循环,您在此处的 worksheet_change 事件代码中使用了该功能。如果不担心 VBA 触发事件,那么这两行将是多余的。在您关闭enableEvents之后,可能发生了某些事情导致您的代码失败,这将一直关闭,直到您重新打开它。