简体   繁体   English

为什么我收到以下 VBA 代码所需的对象错误?

[英]Why do I get object required error for the below VBA code?

I am new to VBA, I need help applying the below VBA code to two specific work sheets by Region and by Model.我是 VBA 新手,我需要帮助将以下 VBA 代码按区域和模型应用于两个特定的工作表。 The code simply finds the last column which has the name total for the year and copies the previous months values into a new column.该代码仅查找具有年份名称总计的最后一列,并将前几个月的值复制到新列中。 But I get an error object required at ws.但是我在 ws 处得到了一个错误对象。

   Sub Insert_New_Col()

Dim Found As Range, BeforeR As Long
Dim xSheets As Variant
Dim ws As Worksheet
Dim i As Long

xSheets = Array("By Region", "By Model") '

For i = LBound(xSheets) To UBound(xSheets)

    Set ws = xSheets(i)
    Set Found = ws.Rows(3).Find(What:="Total for the Year", Lookat:=xlWhole)
    BeforeR = R.Column - 1

    If Found Is Nothing Then
        MsgBox ("The word 'Totals' was not found in Row 5 on Sheet: " & ws.Name)
    Else
        Columns(BeforeR).Copy
        ws.Columns(R.Column).Insert Shift:=xlRight
    End If
Next i

End Sub

You want an actual member of the Worksheets collection:您需要Worksheets集合的实际成员:

Set ws = ThisWorkbook.Worksheets(xSheets(i))

BeforeR = R.Column - 1

What is R ?什么是R Add Option Explicit to the top of the module and declare all variables.在模块顶部添加Option Explicit并声明所有变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM