我有一组名称相似的工作表,并希望对所有这些工作表执行操作(例如工作表名称为1C
,2C
,3C
等。我已经尝试了以下代码但是我得到运行时错误424 :
Sub InsertURLType()
Dim ws As Worksheet
Dim LastCol As Integer
For Each ws In Activebook.Sheets
If ws.Name Like "?1" Then
With ActiveSheet
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
LastRow = Range("A1").End(xlDown).Row
Columns(LastCol).Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
ActiveCell.Select
ActiveCell.FormulaR1C1 = "URL Type"
ActiveCell.Offset(1).Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],URLs!C1:C2,2,FALSE)"
ActiveCell.AutoFill Range(ActiveCell.Address, Cells(LastRow, ActiveCell.Column))
End If
Next ws
End Sub
答案 0 :(得分:1)
我不知道Activebook
。请尝试ActiveWorkbook property中的ActiveWorkbook
。
此外,您应该处理为ws
循环设置的For Each ... Next
工作表类型变量。 With ... End With statement将允许所有进一步的操作将其作为工作表引用,以便执行工作。
Sub InsertURLType()
Dim ws As Worksheet
Dim LastRow As Long, LastCol As Long
For Each ws In ActiveWorkbook.Sheets
With ws
If .Name Like "?1" Then '<~~ this doesn't appear to pattern match the WS names you described in your narrative
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
LastRow = .Range("A" & Rows.Count).End(xlUp).Row '<~~ look from the bottom up
.Columns(LastCol).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
.Cells(1, LastCol) = "URL Type"
.Cells(2, LastCol).Resize(LastRow - 1, 1).FormulaR1C1 = _
"=VLOOKUP(RC[-1], URLs!C1:C2, 2, FALSE)"
End If
End With
Next ws
End Sub
您用于If .Name Like "?1" Then
的面具似乎与您在叙述中提供的工作表名称不匹配。如果不能解决问题,请提供所有工作表名称的列表以及您要处理的工作表名称的子集。
此简短子将检查您的工作表名称。
Sub Check_WS_Names()
Dim ws As Worksheet, strWSs As String
strWSs = " 1C 2C 3C 4C 5C 6C 7C 8C 9C 10C 11C 12C 13C" & _
" 1O 2O 3O 4O 5O 6O 7O 8O 9O 10O 11O 12O 13O" & _
" 1S 2S 3S 4S 5S 6S 7S 8S 9S 10S 11S 12S 13S "
For Each ws In ActiveWorkbook.Sheets
With ws
If CBool(InStr(1, strWSs, Chr(32) & .Name & Chr(32), vbTextCompare)) Then
Debug.Print "found: " & .Name
End If
End With
Next ws
End Sub
运行后,检查VBE的立即窗口(Ctrl + G)以获得结果。