此代码在当前设置中将所有工作表中的第5行复制到主工作表。我需要它来拉出一个范围内的随机行。
Sub test()
Dim curRow As Integer
Dim activeWorksheet As Worksheet
Set activeWorksheet = ActiveSheet
curRow = 1
For Each ws In ActiveWorkbook.Worksheets
If Not ws.Name = activeWorksheet.Name Then
ws.Range("5:6").Copy Destination:=activeWorksheet.Range(CStr(curRow) & ":" & CStr(curRow) + 1)
curRow = curRow + 1
End If
Next ws
End Sub
我试过拧这样的随机代码,但是运行错误1004
失败了Sub test()
Dim curRow As Integer
Dim activeWorksheet As Worksheet
Set activeWorksheet = ActiveSheet
curRow = 1
rndnum = Int((50 - 30 + 1) * Rnd + 1)
For Each ws In ActiveWorkbook.Worksheets
If Not ws.Name = activeWorksheet.Name Then
ws.Range("(rndnum):(rndnum+1)").Copy Destination:=activeWorksheet.Range(CStr(curRow) & ":" & CStr(curRow) + 1)
curRow = curRow + 1
End If
Next ws
End Sub
答案 0 :(得分:0)
如果要在Range中使用变量,请执行以下操作:
'if you only want to use Rows
Range(var1 & ":" & var2)
'if you want to refer to a cell
Range(Cells(varRow,varColumn))
答案 1 :(得分:0)
你非常接近。其中一个行引用正在工作(尽管CStr转换是不必要的);另一个是畸形的。
Sub test()
Dim curRow As Long, rndNum As Long, ws As Worksheet
With ActiveSheet
curRow = 1
rndNum = Int((50 - 30 + 1) * Rnd + 1)
For Each ws In .Parent.Worksheets
If Not ws.Name = .Name Then
ws.Range(rndNum & ":" & rndNum + 1).Copy _
Destination:=.Range(curRow & ":" & curRow + 1)
curRow = curRow + 2
End If
Next ws
End With
End Sub
我还添加了With ... End With statement以减少对分配给ActiveSheet property的var的冗余调用。应该声明ws
var。