如何将对象赋值给变量
Sub test() Dim sht As Worksheet sht = Sheets.Add ‘这里会报错的 Set sht = Sheets.Add ‘将对象赋值给变量 需要加上set sht.Name = "4月" End Sub
例子:创建表 以sheet1的单元格内容为名字
Sub test() Dim sht As Worksheet Dim i As Integer For i = 2 To 5 Set sht = Sheets.Add sht.Name = Sheet1.Range("a" & i) Next End Sub
dir函数
1)判断有无此文件 dir里支持通配符
Sub test() Dim i As Integer For i = 1 To 5 If Dir("a:\data\" & Sheet1.Range("a" & i) & ".xls*") = "" Then #支持通配符 Sheet1.Range("b" & i) = "无此文件" Else Sheet1.Range("b" & i) = "有文件" End If Next End Sub
2)dir的使用说明,在文件data里有多个苏州文档 如 苏州.xlsx 、苏州.xls
Sub ss() Range("a1") = Dir("d:\data\苏州.xls*") #返回苏州 Dir("d:\data\*.*")遍历所有文件 Range("a1") = Dir #返回苏州 Range("a1") = Dir #返回空 Range("a1") = Dir #报错 End Sub
3)遍历所有文件名
Sub test1() Dim str As String str = Dir("d:\data\*.xls*") For i = 1 To 100 Range("a" & i) = str str = Dir If str = "" Then Exit For End If Next End Sub
4)壳子,对固定的文件夹内的数据打开 再关闭
Sub test1() Dim str As String Dim wb As Workbook str = Dir("d:\data\*.xls*") For i = 1 To 100 Set wb = Workbooks.Open("d:\data\" & str) wb.Close str = Dir If str = "" Then Exit For End If Next End Sub
原文:https://www.cnblogs.com/xiao-xuan-feng/p/12662631.html