我正试图让一个宏在工作表上插入一列"运行";,然后粘贴来自纸张"的信息;模板";到特定行上新插入的列上。我已经将第四行的范围命名为";八";,但是,来自模板的信息被粘贴到A列的第4行,而不是新插入的列。
Set myWorksheet = Worksheets("Runs")
myFirstColumnT = myWorksheet.Cells.Find( _
What:="TS", _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
myLastColumnT = myWorksheet.Cells.Find( _
What:="TE", _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
For iCounter = myLastColumnT To (myFirstColumnT + 1) Step -100000000
myWorksheet.Columns(iCounter).Insert
Sheets("Templates").Select
Range("B2:B16").Copy
Sheets("Runs").Select
With Columns(iCounter).Select
Range("eight").PasteSpecial
End With
Next iCounter
问题是你的With
实际上没有做任何事情,如果它做了,你的Range
就不会引用它。
我已经删除了你的循环,它有一个巨大的步骤,实际上并没有循环任何东西。此外,你不需要一个循环。
我从您的.finds
中删除了.column
,因为如果它失败,会导致错误,我还添加了一些错误检查,以确定它是否(何时(找不到任何东西。
我删除了.Select
的所有实例,因为它们不是必需的。
Dim myworksheet As Worksheet
Dim myfirstcolumnt As Range
Dim mylastcolumnt As Range
Dim newcol As Long
Set myworksheet = Worksheets("Runs")
'I'm assuming you need this for a reason other than the loop, otherwise you can remove it
Set myfirstcolumnt = myworksheet.Cells.Find( _
What:="TS", _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious)
If myfirstcolumnt Is Nothing Then
MsgBox "TS not found"
Exit Sub
End If
Set mylastcolumnt = myworksheet.Cells.Find( _
What:="TE", _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious)
If mylastcolumnt Is Nothing Then 'Avoiding errors
MsgBox "TE not found"
Exit Sub
End If
newcol = mylastcolumnt.Column + 1 'No need to loop to find the column you're making
myworksheet.Columns(newcol).Insert 'use the new column index to add the column
Sheets("Templates").Range("b2:b16").Copy
myworksheet.Cells(4, newcol).PasteSpecial 'We know it's going in row 4 and we have the new column index now
如果你想使用你的命名范围,你可以做myworksheet.Cells(myworksheet.range("Eight").Row, newcol)...
尽管我建议更改名称,一个名为";八";指向第4行不是很清楚。