我有2个私人潜艇,这些潜艇已经合并到下面的代码中。代码的第二部分需要定义范围的逻辑。我面临的问题是我的第二个代码未指定范围,因此我不确定如何定义范围?而且我的VBA知识不是那么好!有人可以帮助我输入此信息吗?
合并前的代码为:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range, cel As Range
Set rng = Intersect(Target, Range([H2], Cells(Rows.Count,
"H").End(xlUp)))
If rng Is Nothing Then Exit Sub
Application.EnableEvents = False
rng.Offset(, 1).FormulaR1C1 = "=IF(RC[-1]<>"""",R1C[6] & ""-"" &" &
"TEXT(COUNTA(R2C[-1]:RC[-1]),""0000"") & ""-"" & R1C[7],"""")"
Application.EnableEvents = True
End Sub
如果H代码2中提供了信息,则代码1使用P1和O1在I列中填充一个自动编号。
Private Sub Move_blanks_To_Bottom(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If Target.Column <> 9 Then Exit Sub
Range("A1", Range("A" & Rows.Count).End(xlUp)).Resize(, 11).Sort
key1:=Range("I1"), order1:=xlAscending, Header:=xlYes
End Sub
代码2正在使用I列并对值进行排序,因此,如果I中有一个值,它将把行移动到下一个可用行,如果I单元格为空白,则I列将有效地完成,该行将移到底部。 / p>
合并的代码为:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
'Do logic for this first range
Dim rng As Range, cel As Range
Set rng = Intersect(Target, Range([H2], Cells(Rows.Count,
"H").End(xlUp)))
If Not Intersect(rng, Target) Is Nothing Then
rng.Offset(, 1).FormulaR1C1 = "=IF(RC[-1]<>"""",R1C[6] & ""-"" &" &
"TEXT(COUNTA(R2C[-1]:RC[-1]),""0000"") & ""-"" & R1C[7],"""")"
End If
'now do logic for the second range (move_blanks_to_bottom)
'2nd LOGIC HERE
If Target.CountLarge = 1 And Target.Column = 9 Then
Range("A1", Range("A" & Rows.Count).End(xlUp)).Resize(, 11).Sort
key1:=Range("I1"), order1:=xlAscending, Header:=xlYes
End If
Application.EnableEvents = True
End Sub
谢谢!
答案 0 :(得分:0)
您的排序命令很好,尽管它相当复杂,因为它可以在一个命令中压缩一系列操作。使用此命令,您可以对从A列到K列(= 11)以及从第1行到最后使用的行(带有标题)的范围进行排序。您可以使用以下更简单的命令拆分该命令:
Dim lastrow As Long
Dim r As Range
lastrow = Range("A" & Rows.Count).End(xlUp).Row ' find row of last non-blank cell in column A
Set r = Range("A1").Resize(lastrow, 11) ' set the exact data range
r.Sort key1:=Range("I1"), order1:=xlAscending, Header:=xlYes
但这与您的代码2相同。
您可能需要知道,如果将命令分为两行,则需要使用_
终止行,如下所示:
Range("A1", Range("A" & Rows.Count).End(xlUp)).Resize(, 11).Sort _
key1:=Range("I1"), order1:=xlAscending, Header:=xlYes
否则,编译器会将它们视为单独的命令,并将删除语法错误消息。