我觉得羞怯地问这个 - 必须非常简单 - 但我花了好几个小时梳理书籍,网站和各种代码块试图解决它,但仍然无法使其发挥作用。我错过了什么?
我正在尝试将ActiveWorkbook和ActiveSheet分配给变量,以便可以直接指定它们而不是隐含。宏处理三种不同的工作簿。其中两个是静态名称,所以我可以通过名称引用它们,没问题。但是每次运行宏时,活动文件名都会不同。
隐含ActiveWorkbook和ActiveSheet时代码有效:
Dim callsWB As Workbook
Dim callsWS As Worksheet
Set callsWB = ActiveWorkbook
Set callsWS = ActiveSheet
Dim lastRow As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
Dim pType As Range
Set pType = Range("N3" & ":N" & lastRow).Find("P", LookIn:=xlValues)
但不是在我尝试使用变量时:
Dim callsWB As Workbook
Dim callsWS As Worksheet
Set callsWB = ActiveWorkbook
Set callsWS = ActiveSheet
Dim lastRow As Long
lastRow = callsWB.callsWS.Cells(Rows.Count, 1).End(xlUp).Row
Dim pType As Range
Set pType = callsWB.callsWS.Range("N3" & ":N" & lastRow).Find("P",LookIn:=xlValues)
我也尝试了各种语法,如
callsWB(callsWS).Range("N3")
和许多不同的With语句。如果有人能指出我正确的方向,我会非常感激。
答案 0 :(得分:2)
当您Set callsWS = ActiveSheet
时,它还将工作簿设置为变量的一部分。
所以callsWB.callsWS.
就像ActiveWorkbook.ActiveWorkbook.ActiveSheet
设置工作表时设置工作簿:
Set callsWS = callsVB.worksheets("Sheet1")
但是,由于您正在调用ActiveSheet,因此隐含了Active Workbook,因此Set callsWS = ActiveSheet
已足够
然后只使用工作表:
Dim callsWB As Workbook
Dim callsWS As Worksheet
Set callsWB = ActiveWorkbook
Set callsWS = ActiveSheet
Dim lastRow As Long
lastRow = callsWS.Cells(Rows.Count, 1).End(xlUp).Row
Dim pType As Range
Set pType = callsWS.Range("N3" & ":N" & lastRow).Find("P",LookIn:=xlValues)