我一直在尝试向跨部门电子表格编写一些宏,当我按下命令按钮时,该宏实际上将“存档”一行工作。我也有一个意思是当人们键入列时自动将其大写。见下文:
这是“存档”宏:
Sub Archive()
If MsgBox("Do you want to archive the selected row?" & vbNewLine & vbNewLine & "Row should only be archived after x has passed.", vbYesNo, "Archive") = vbNo Then Exit Sub
For Each WSheet In ActiveWorkbook.Worksheets
If WSheet.AutoFilterMode Then
If WSheet.FilterMode Then
WSheet.ShowAllData
End If
End If
For Each DTable In WSheet.ListObjects
If DTable.ShowAutoFilter Then
DTable.Range.AutoFilter
DTable.Range.AutoFilter
End If
Next DTable
Next WSheet
'Declare variables
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim lastRow As Long
'Set variables
Set sht1 = Sheets("xDepartment")
Set sht2 = Sheets("Archive")
'Select Entire Row
Selection.EntireRow.Select
'Move row to destination sheet & Delete source row
lastRow = sht2.Range("A" & sht2.Rows.Count).End(xlUp).Row
With Selection
.Copy Destination:=sht2.Range("A" & lastRow + 1)
.EntireRow.Delete
End With
End Sub
自动大写宏是否附加到特定工作表上? (即,在右键单击“ xDepartment”并选择“查看代码”时将其附加-不确定是否与此有关吗?)。此工作表上还有一个宏,用于计算特定单元格中数据的更改日期:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim A1 As Range
Set A1 = Range("O:O,Q:Q,T:T,W:W")
If Not Intersect(Target, A1) Is Nothing Then
Application.EnableEvents = False
Target.Value = UCase(Target.Value)
Application.EnableEvents = True
End If
Dim WorkRng As Range
Dim Rng As Range
Dim xOffsetColumn As Integer
Set WorkRng = Intersect(Application.ActiveSheet.Range("O:O, Q:Q"), Target)
xOffsetColumn = 1
If Not WorkRng Is Nothing Then
Application.EnableEvents = False
For Each Rng In WorkRng
If Not VBA.IsEmpty(Rng.Value) Then
Rng.Offset(0, xOffsetColumn).Value = Now
Rng.Offset(0, xOffsetColumn).NumberFormat = "dd/mm/yyyy"
Else
Rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
Application.EnableEvents = True
End If
End Sub
出现的错误是“运行时错误'13':类型不匹配”。你知道为什么会这样吗?
谢谢!
答案 0 :(得分:1)
在“存档”宏中的第一行之后放置
Application.EnableEvents = False
On error goto Whoops
然后在您的End Sub上方放置该宏
Whoops:
Application.EnableEvents = True
这会在存档运行时关闭另一个宏
答案 1 :(得分:1)
您将行从xDepartment工作表移动到Archive工作表的代码包括以下行
Selection.EntireRow.Select
这将使xDepartment工作表处于活动状态。实际移动该行并删除原始行的代码无法将xDepartment更改为ActiveSheet。
With Selection
.Copy Destination:=sht2.Range("A" & lastRow + 1)
.EntireRow.Delete
End With
在工作表更改中,您拥有
Set WorkRng = Intersect(Application.ActiveSheet.Range("O:O, Q:Q"), Target)
因此,存档工作表的Worksheet_Change将尝试在xDepartment工作表上工作。
但是您删除该行,使其不再存在;亨斯:
运行时错误'13':类型不匹配
设置您的WorkRng,
Set WorkRng = Intersect(Range("O:O, Q:Q"), Target)
它位于存档的私有代码表上的私有子过程中,因此除非您特别想处理另一个工作表,否则无需指定父级工作表。
避免在可能的情况下使用ActiveSheet,选择,选择和激活,并且从不在工作表的私有代码表中使用它们来引用该工作表。