Excel VBA:是否有可能获得循环中的每个单元格的地址,并将其用于循环外

我想通过工作簿的一些工作表来写一个循环,以获得每个工作表中的一个特定单元格的地址。 我的目的是获取这些单元格的地址,并将它们用作循环引用。

我写了一个代码,但它不工作,我想要的:

Sub RegionalAverage() For i = 1 To 2 Sheets(i).Activate Range("A1").Select Selection.AutoFilter ActiveSheet.Range("A1:H23393").AutoFilter Field:=6, Criteria1:=1 Columns("A:H").Select Selection.SpecialCells(xlCellTypeVisible).Select Selection.Find(What:="1/1/2008", After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False).Select ActiveCell.Offset(0, 4).Select Name (i) = "'" & Selection.Parent.name & "'" & "!" & Selection.Address(External:=False) Next i MsgBox Name(1) MsgBox Name(2) End Sub 

我已经重写了你的程序,以避免使用。select1,并使用Option Explicit 2环境来强制声明所使用的variables。 我怀疑你的问题是由于使用了未声明的和无意义的Name数组而引起的。

 Option Explicit Sub RegionalAverage() 'declare the variables you plan to use!!!!! Dim i As Long, fnd As Range, aNames As Variant 'you were only looking for two addresses so dimension the array now ReDim aNames(1 To 2) 'loop through the first two worksheets For i = 1 To 2 'start isolating the workspace ujsing With ... End With With Worksheets(i) 'if AutoFilter is active, turn it off If .AutoFilterMode Then .AutoFilterMode = False ''work with the 'island' of data radiating out from A1 With .Cells(1, "A").CurrentRegion 'isolate to A:H With .Resize(.Rows.Count, 8) 'filter on column F = 1 .AutoFilter Field:=6, Criteria1:=1 'isolate to the visible cells With .SpecialCells(xlCellTypeVisible) 'set a range object to the first found cell Set fnd = .Cells.Find(What:="1/1/2008", After:=.Cells(.Cells.Count), _ LookIn:=xlFormulas, LookAt:=xlPart, _ SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) 'check if anything was found If Not fnd Is Nothing Then 'offset 4 columns to the right Set fnd = fnd.Offset(0, 4) 'store the parent worksheet name and cell address aNames(i) = Chr(39) & fnd.Parent.Name & "'!" & fnd.Address(External:=False) End If End With End With End With End With Next i MsgBox "First found at " & aNames(1) & vbLf & _ "Second found at " & aNames(2) End Sub 

请注意,我的数组被称为aNames 。 名称在VBA中被认为是一个“保留字”,并不认为是将保留字,方法或属性重新定义为variables的“最佳实践”。


¹ 请参阅如何避免使用在Excel VBAmacros中select更多的方法来摆脱依靠select和激活来实现您的目标。

² 在VBE工具中设置需要variables声明 ►选项►编辑器属性页面将把Option Explicit语句放在每个新创build的代码表的顶部。 这将避免像拼写错误这样的愚蠢的编码错误,也会影响你在variables声明中使用正确的variablestypes。 在没有声明的情况下即时创build的variables都是变体/对象types。 使用Option Explicit被广泛认为是“最佳实践”。