1 问题:什么时候可以用 for each 进行循环?
不需要知道具体的循环变量,上下限。
答案 : 当for each xx in yyy ,只要 yyy 是 对象集合(s)
比如像 workbook 这样 的可数的对象的集合就可以
可以用for each 的地方都可以用 for i = 下限 to 上限 step 1
2 例子: excel 原生原装的对象集合 ,比如 workbooks, worksheets
Sub jackma1()
Dim sh1 As Object
For Each sh1 In Workbooks("test.xlsm").Worksheets
Debug.Print sh1.Name
Next
End Sub
3 例子,fso里的对象集合
- 正确
- Set fd1 = fso.getfolder(path1)
- Set ff1 = fso.getfile(path1)
- 错误,不能直接取fso的多个文件
- Set ff1 = fso.getfiles(path1)
- 其实可以间接用 fso.getfolder().files,效果一样的
- 但是有其他的 object.getfiles()
Sub jackma2()
Dim fso As Object
Dim path1
Dim fd1 As Object
Set fso = CreateObject("scripting.filesystemobject")
path1 = "C:\Users\Administrator\Desktop\test1"
Set fd1 = fso.getfolder(path1)
For Each f1 In fd1.Files
Debug.Print f1.Name
Next
End Sub
代码2.2 另外一种写法
其实可以间接用 fso.getfolder().files,效果一样的
Sub jackma2()
Dim fso As Object
Dim path1
Dim fd1 As Object
Set fso = CreateObject("scripting.filesystemobject")
path1 = "C:\Users\Administrator\Desktop\test1"
Set fd1 = fso.getfolder(path1).Files
For Each f1 In fd1
Debug.Print f1.Name
Next
End Sub
4 数组也可以
- 数组index 下限,lbound(arr)
- 数组index 上限,ubound(arr)
- 数组的长度: ubound(arr) - lbound(arr) +1
Sub jackma_array1()
arr1 = Array(1, 2, 3, 4, 5)
'循环index,展示array
For i = LBound(arr1) To UBound(arr1)
Debug.Print arr1(i)
Next
Debug.Print
'直接循环显示element
For Each i In arr1
Debug.Print i
Next
Debug.Print
'用join函数,感觉很巧妙
Debug.Print Join(arr1)
Debug.Print
Debug.Print Join(arr1, " ")
Debug.Print
End Sub
5 字典也可以
- VBA的字典,好像没有那种成对显示的那种 方法
- dict1.keys()
- dict1.items()
- 这是字典自身包含的2个数组
Sub test1_dict()
Dim dict1 As New Dictionary
dict1.Add 1, "a"
dict1.Add 2, "b"
dict1.Add 3, "c"
dict1.Add 4, "d"
dict1.Add 5, "e"
For Each i In dict1.Keys
Debug.Print i
Next
For Each j In dict1.Items
Debug.Print j
Next