[英]How do I make my macro run when 'save' is selected?
I am setting up a document to remove rows if a specific cell contains a value.如果特定单元格包含值,我正在设置一个文档以删除行。 I want this code to run when the 'save' button is selected.
我希望在选择“保存”按钮时运行此代码。 What do I need to add to my vba script to make this happen?
我需要在我的 vba 脚本中添加什么来实现这一点?
I have searched several sites and tried several suggested solutions but am not finding one that is working.我搜索了几个站点并尝试了几个建议的解决方案,但没有找到一个有效的解决方案。
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
When this code is inserted into the 'ThisWorkbook' object I am getting no response when I run the macro.当将此代码插入“ThisWorkbook”object 时,我在运行宏时没有得到任何响应。 When inserted into a 'Module', I can make the macro run but am not able to make it run with the 'save' selection.
当插入“模块”时,我可以使宏运行,但无法通过“保存”选择使其运行。
can you try this?你能试试这个吗? as @braX suggested, you need to start from the last row and make your way up to the first row.
正如@braX 建议的那样,您需要从最后一行开始,一直到第一行。 This code lies in 'ThisWorkbook' see the red circles.
此代码位于“ThisWorkbook”中,见红色圆圈。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.