我有一个范围(比方说A1:A100)。我添加了7个集合,每个集合包含一组单独的单元格。
来自“A”列的偏移(0,1)行是预定的,并且可以是“y”和“n”的任何3个数字星座。我写了一个参数,其中y = 1,n = 0。
基于此,我写了几个IF语句(例如见下文)
If M(1) = 1 And M(2) = 1 And M(3) = 1 Then
Count = Count + 1 ' unique
Robust(Count) = SI_number 'unique
With Robust(Count)
.Offset(1, 0) = SI_name 'unique
.Font.ThemeColor = xlThemeColorDark1
.HorizontalAlignment = xlLeft
.Font.Size = 5
.Font.Name = "xxx"
.VerticalAlignment = xlCenter
.HorizontalAlignment = xlCenter
end with
' Robust and T is of type collection
有没有办法为多个范围/集合使用相同的“with ..”参数?
我将有7种不同的IF语句。每个都有一个特定的集合(自己的名称),如果满足条件,将使用单个单元格。为了避免我想做的很多重复行(在代码中):
With collection(1-7)
.action (same code as above)
.action
..
..
End with
我的一个想法是创建一个单独的宏,可以从我的主宏内部调用,以便:
With X
.action
.action
..
..
End with.
其中X可以是1到7.使用“with”或任何其他函数,是否可以将collection1,collection 2,...,collection 7存储在同一个变量(或等效类型)中,以便在最后每个If语句都有一个X = Collection()
Call format 'macro that formats the cell/text
另一个问题是如何将20个单独的单元添加到集合中?代码是重复的几个“collection.add范围(xx”..等。
这是一个Sub format()
应该做你期望的,与test_collection()
Sub一起测试它。
Option Explicit
Sub test_collection()
Dim c1 As Collection
Dim c2 As Collection
Dim i As Integer
Set c1 = New Collection
Set c2 = New Collection
c1.Add Sheet1.Range("A1")
c1.Add Sheet1.Range("A2")
c1.Add Sheet1.Range("A3")
c2.Add Sheet1.Range("B1")
c2.Add Sheet1.Range("B2")
c2.Add Sheet1.Range("B3")
''' adding bunch of cells using a loop
For i = 4 To 20
c1.Add Sheet1.Range("A" & i)
Next i
format c1
format c2
End Sub
Sub format(in_coll As Collection)
''' input is collection and we have to cycle through each individual cell in the collection
Dim i As Integer
For i = 1 To in_coll.Count
With in_coll(i)
'.Offset(1, 0) = SI_name
.Font.ThemeColor = xlThemeColorDark1
.HorizontalAlignment = xlLeft
.Font.Size = 5
.Font.Name = "xxx"
.VerticalAlignment = xlCenter
.HorizontalAlignment = xlCenter
End With
Next i
End Sub
但是,使用范围对象通常更适合使用单元格,因此这里是使用Range对象而不是集合执行相同操作的代码。
Sub test_range()
Dim c1 As Range
Dim c2 As Range
Dim i As Integer
Set c1 = Sheet1.Range("A1:A20")
Set c2 = Sheet1.Range("B1:B3")
format_range c1
format_range c2
End Sub
Sub format_range(in_rng As Range)
''' input is range and we can update the cells in a bulk
With in_rng
'.Offset(1, 0) = SI_name
.Font.ThemeColor = xlThemeColorDark1
.HorizontalAlignment = xlLeft
.Font.Size = 5
.Font.Name = "xxx"
.VerticalAlignment = xlCenter
.HorizontalAlignment = xlCenter
End With
End Sub