使用索引号(从 1 开始)
Workbooks(1)使用工作簿名称
Workbooks("1.xlsx")Dim wd As Excel.Application
Dim wb As Workbook
Set wd = CreateObject("excel.application")
wd.Visible = True
Set wb = wd.Workbooks.Open(ThisWorkbook.Path & "/test.xls")
' ...
wb.Close
wd.QuitDim wb As Workbook
wb = Workbooks.Open(ThisWorkbook.Path & "/test.xls")
' ...
wb.Save
wb.Close关闭所有工作簿
Workbooks.close另存为(自动打开新文件关闭源文件)
ThisWorkbook.SaveAs FileName:="D:\1.xls"另存为(保留源文件不打开新文件)
ThisWorkbook.SaveCopyAs FileName:="D:\1.xls"oldfile = ThisWorkBook.Path & "/old.xlsx"
newfile = ThisWorkBook.Path & "/new.xlsx"
FileCopy oldfile, newfilebase = ThisWorkBook.Path & "/文件夹/"
pattern = base & "*.*"
file = Dir(pattern, vbReadOnly)
While file <> ""
Kill base & file
file = Dir
WendMkDir(directory)以下为不存在即创建
If Dir(outputDir, 16) = Empty Then
MkDir (outputDir)
End If方法 1:
Dim fileSystemObject As Object
Set fileSystemObject = CreateObject("Scripting.FileSystemObject")
If fileSystemObject.FileExists(<filepath>) = True Then
MsgBox "文件存在"
End If方法 2:
Dim file As String
file = Dir("E:\MyPictures\Pic\logo.gif")
If file <> "" Then
MsgBox "文件存在"
EndifSet Rng = MyWorkSheet.UsedRange
With Rng
.Borders.LineStyle = xlContinuous
.Borders.Weight = xlThin
.AutoFilter
End WithMyWorkSheet.Cells(i, j).Interior.ColorIndex在 thisworkbook 中添加如下代码段:
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
If ActiveSheet.Name = "yoursheet" Then
ActiveSheet.UsedRange.Interior.ColorIndex = 0
Target.Interior.ColorIndex = 6
End If
End Sub设置单元格 Value 里使用 Chr(10) 和 Chr(13),分别表示回车、换行。
MyWorkSheet.Rows(i).Hidden = Truesheet.Cells(m, n).NumberFormatLocal = "@"Range("A1") '表示 A1 单元格
Range("A2:D1") '表示 A2 到 D1 区域
Range("A2:D1")(3) '表示该区域里的第三个单元格
Range("D" & i) 'i 为变量
Range("D3:F4,G10") '引用多个区域
Range("2:2") '引用第二行
Range("2:12") '引用第二行到第十二行
Range("D:A") '引用第 A 到 D 列
Rows(2) '引用第二行
Rows("2:4") '引用第二到四行
Columns("B")
Columns("B:D")
Range(Clee1, Cell2) '左上与右下
Range(Range1, Range2) '取最大范围Range("1:1").Select '选中第一行MyWorkSheet.Application.SelectionDim dict
Set dict = CreateObject("Scripting.Dictionary")
' 新增,各种类型都可以,包括 Dictionary
dict.Add "hello", "world"
' 数量
dict.Count
' 删除
dict.Remove("hello")
' 判断是否存在
dict.exists("hello")
' 取值,需要先判断存在再取
dict.Item("hello")
' 修改、新增
dict.Item("hello") = "world"
' 循环
k = dict.Keys
v = dict.Items
For i = 0 to dict.count - 1
key = k(i)
value = v(i)
Next
' 清空
dict.RemoveAllCInt(MyWorkSheet.Cells(1,7))
CDbl(MyWorkSheet.Cells(1,7))Dim arr() As String
arr() = Split(ws.Cells(a, b).Value, "-")
alen = UBound(arr) - LBound(arr) + 1判断单元格的 value 是否为 “”。
主要使用 Exit 表达式。
Exit { Do | For | Function | Property | Select | Sub | Try | While }