选择“保存”后如何运行宏?

问题描述 投票:0回答:1

我正在设置一个文档,以便在特定单元格包含值的情况下删除行。我希望在选择“保存”按钮时运行此代码。我需要在vba脚本中添加些什么才能使这种情况发生?

我已经搜索了多个站点,并尝试了一些建议的解决方案,但没有找到一个可行的解决方案。

HideRows_BeforeSave()

Dim beginRow As Long
Dim endRow As Long
Dim chkCol As Long
Dim rowCnt As Long
Dim rngResult As Range
Dim ws As Worksheet

beginRow = 3
endRow = 38
chkCol = 14

Set ws = ThisWorkbook.Worksheets("Travel Expense Codes")

For rowCnt = beginRow To endRow
    If Cells(rowCnt, chkCol).Value = "X" Then
        Cells(rowCnt, chkCol).EntireRow.Hidden = True

    Else
        Cells(rowCnt, chkCol).EntireRow.Hidden = False

    End If
Next rowCnt

当将此代码插入'ThisWorkbook'对象时,运行宏时没有任何响应。当插入“模块”时,我可以使宏运行,但不能通过“保存”选项使其运行。

excel vba
1个回答
0
投票

您可以尝试这个吗?正如@braX所建议的那样,您需要从最后一行开始,一直到第一行。此代码位于“ ThisWorkbook”中,见红色圆圈。

enter image description here

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

  Dim beginRow As Long, endRow As Long, chkCol As Long, rowCnt As Long
  Dim rngResult As Range
  Dim ws As Worksheet

  beginRow = 3
  endRow = 38
  chkCol = 14

  Set ws = ThisWorkbook.Worksheets("Travel Expense Codes")

  For rowCnt = endRow To beginRow Step -1
    If Cells(rowCnt, chkCol).Value = "X" Then
      ws.Cells(rowCnt, chkCol).EntireRow.Delete
    End If
  Next rowCnt

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.