这里我试图随机冒号,然而,它告诉我不能自动填充,同样的事情适用于我的randomRow()
Sub randomCol()
Dim Line As Integer
Line = LastRow + 1
Range("N154").Select
ActiveCell.FormulaR1C1 = "=RAND()"
Dim randomRange As String
randomRange = "N" & Line & ":BF" & Line
MsgBox randomRange
Selection.AutoFill Destination:=Range(randomRange), Type:=xlFillDefault
Range("N2:BF" & Line).Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add key:=Range("N" & LastRow + 1), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("N1:BF" & Line)
.Header = xlGuess
.MatchCase = False
.Orientation = xlLeftToRight
.Apply
End With
End Sub
答案 0 :(得分:0)
自动填充方法要求目标必须包含源范围。自动填充的正确语法如下所示。
Set sourceRange = Worksheets("Sheet1").Range("A1:A2")
Set fillRange = Worksheets("Sheet1").Range("A1:A20")
sourceRange.AutoFill Destination:=fillRange
因此我修改了你的程序并希望它能正常工作。
Sub randomCol()
Dim Line As Integer
Line = LastRow + 1
Range("N154").Select
ActiveCell.FormulaR1C1 = "=RAND()"
Set SourceRange = Worksheets("Sheet1").Range("N154") 'Changed you can set the range required by you.
Dim randomRange As String
randomRange = "N" & Line & ":BF" & Line
Set fillRange = Worksheets("Sheet1").Range("n1:BF154") 'Set fill range appropriately but should include source range
MsgBox randomRange
'changed
'Selection.AutoFill Destination:=Range(randomRange), Type:=xlFillDefault
SourceRange.AutoFill Destination:=fillRange
Range("N2:BF" & Line).Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("N" & LastRow + 1), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("N1:BF" & Line)
.Header = xlGuess
.MatchCase = False
.Orientation = xlLeftToRight
.Apply
End With
End Sub
答案 1 :(得分:0)
编辑 LastRow
是一个返回ActiveSheet.Cells(Rows.Count, "L").End(xlUp).Row
的函数
目的地必须包含源范围,而后者是“N154”,前者是“N”和“BF”列之间的行Line
中的单元格,所以它只在{{1是154。
此外,最好从Line
类型定义Line
和LastRow()
,而不是Long
以便您的代码可以更改如下:
Integer
但您也可以考虑:
以避免选择和激活
实际上不需要Sub randomCol()
Dim Line As Long
Line = Lastrow + 1
Range("N" & Line).Select
ActiveCell.FormulaR1C1 = "=RAND()"
Dim randomRange As String
randomRange = "N" & Line & ":BF" & Line
MsgBox randomRange
Selection.AutoFill Destination:=Range(randomRange), Type:=xlFillDefault
Range("N2:BF" & Line).Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("N" & Line), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("N1:BF" & Line)
.Header = xlGuess
.MatchCase = False
.Orientation = xlLeftToRight
.Apply
End With
End Sub
Function LastRow() As Long
LastRow = ActiveSheet.Cells(Rows.count, "L").End(xlUp).Row
End Function
,因为你只是粘贴一个公式
所以你的代码可以变成:
Autofill