我是VBA的新手,请尝试处理包含2个表和特定宏的工作表。 我在一个模块中创建了宏,并将其放置在名为Positionen_Einfügen(插入整行)和Zeile_Löschen(删除整行)的按钮上。
代码运行得很完美,但是现在我想在Wokrsheet(Einzelkosten)中的特定区域中限制这些宏,但是该区域仍然很灵活,因为您可以插入多行或删除一行。
在这种情况下,我在桌子停靠的地方放了一个大红色“ Y”。我的“ Y”很灵活,如果使用宏,它们当然也会随宏一起移动。像是向下几行或向上几行。
我想将此“ Y”用作ActiveCell.EntireRow.Select的对象。因此,我可以在宏中编写一个.Find(“ Y”)函数,就像下面的代码一样:
Position_Einfügen()
'Disable Excel feautres to prevent Errors
ActiveSheet.Unprotect
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = False
'set specific range for area
Dim Target As Range
Set Target = Range("A9:R200").Find(Y, LookIn:=xlValues)
icountROws = Application.InputBox(Prompt:="How many rows do you want to insert after Line " _
& ActiveCell.Row & " ?", Type:=1)
' Dont allow negative numbers or empty field: Error Handling
If icountROws <= 0 Then End
ActiveCell.EntireRow.Select
'Can this work?
If ActiveCell.EntireRow.Select >= Y And ActiveCell.EntireRow.Select = Y Then
MsgBox ("Sie befinden sich außerhalb des erlaubten Bereichs")
End If
Exit Sub
Else If
Selection.Copy
' Selection.PasteSpecial xlPasteFormulas
Rows(ActiveCell.Row & ":" & ActiveCell.Row + icountROws - 1).Insert shift:=xlDown
End If
'Re-enable features after running macro, auto-debugging
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True
ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= _
True, AllowFormattingCells:=True, AllowFormattingColumns:=True
ActiveSheet.EnableSelection = xlNoRestrictions
End Sub
这是2.宏:删除功能
Sub Zeile_Löschen()
'select row to delete
Dim DeletePrompt As Integer
DeletePrompt = MsgBox("Are you sure you want to delete this row?", vbYesNo + vbQuestion, "Delete")
ActiveSheet.Unprotect
If DeletePrompt = vbYes Then
Rows(ActiveCell.Row).Delete
Else
'do nothing
End If
ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= _
True, AllowFormattingCells:=True, AllowFormattingColumns:=True
ActiveSheet.EnableSelection = xlNoRestrictions
End Sub
答案 0 :(得分:0)
您可以使用Target.Row
和Activecell.Row
进行操作,如下所示:
Set Target = Range("A9:R200").Find("Y", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=True)
' note the quotes around Y
If Target Is Nothing Then
iMaxRow = 200 ' need to set some maximum value even if Y is not found
Else
iMaxRow = Target.Row
Endif
If Activecell.Row >iMaxRow Then
Msgbox "out of range"
End
End
... and here you can continue inserting
类似地,您可以使用Target.Column
控制水平尺寸。
限制插入行的数量也很有意义,就像这样:
If ActiveCell.Row + icountROws > iMaxRow Then icountRows = iMAxRow - ActiveCell.Row
尝试避免使用select。在此处查看更多信息:How To Avoid Using Select。无论如何,您不能将整个(选定的)行与一个值进行比较。
代替
ActiveCell.EntireRow.Select 'Can this work?
If ActiveCell.EntireRow.Select >= Y And ActiveCell.EntireRow.Select = Y Then
使用
If Target.Value = "Y" Then
或
If Target.Value = "Y" Or Target.Value = "y" Then
代替
ActiveCell.EntireRow.Select
Selection.Copy
使用
ActiveCell.EntireRow.Copy