基本上我试图复制并在第二张纸上插入一定范围的单元格,因为程序循环遍历第一张纸上的一系列单元格,只要单元格不为空。我需要复制和插入范围来更改为每个循环的新副本和插入的单元格。任何帮助将不胜感激
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim rng As Range
Dim i As Integer
Dim j As Integer
For i = 12 To 24
Set ws = ThisWorkbook.Sheets("Input")
With ws
If Not IsEmpty(Cells(i, 2)) Then
For j = 10 To -2
Set ws = ThisWorkbook.Sheets("Budget Output #2")
With ws
Set rng = .Range("Cell(5,i-j):Cell(17,i-j+1)")
rng.Copy
rng.Offset(0, 2).Insert Shift:=xlToRight
rng.Offset(0, 2).ColumnWidth = 20
Application.CutCopyMode = False
Next j
Next i
End If
End With
End With
End Sub
答案 0 :(得分:2)
您不需要ONE行的With
语句。这会更清洁。还有两张纸,您应该使用两个工作表变量。最后,我清理了您的Range(Cells, Cells)
语法。虽然,由于你的For j = 10 to -2
,这仍然无效。要向后移动,您必须使用Step -#
。
Private Sub CommandButton1_Click()
Dim wsIn As Worksheet, wsOut As Worksheet
Dim rng As Range
Dim i As Integer
Dim j As Integer
Set wsIn = ThisWorkbook.Sheets("Input")
Set wsOut = ThisWorkbook.Sheets("Budget Output #2")
x = 2
For i = 12 To 24
If Not IsEmpty(wsIn.Cells(i, 2)) Then
Set rng = wsOut.Range("B:C")
rng.Copy
rng.Offset(0, x).Insert Shift:=xlToRight
rng.Offset(0, x).ColumnWidth = 20
Application.CutCopyMode = False
x = x + 2
End If
Next i
End Sub
答案 1 :(得分:1)
我会让你弄清楚答案。这是正确的结构:
For i ....
For j ...
with ws
end with
next j
next i
答案 2 :(得分:-1)
你有两个ws变量可能正确启动你的代码。
Dim ws As Worksheet, sh As Worksheet
Set ws = Sheets("Budget Output #2")
Set sh = Sheets("Input")