代码1 - 单元格引用祥光,及效果

Option Explicit
' 与Excel交互 - 单元格
Sub Table_Sub()
' 详细写法,对象层次访问
'Application.Workbooks("工作簿2.xls").Worksheets("Sheet2").Range("A1").Value = 555
' 选择当前工作簿的A1单元格
Range("A1").Select
' 设置当前工作簿的A1单元格内容
Range("A1").Value = 9527
' 获取当前工作簿A1单元格内容
MsgBox Range("A1").Value
' 清理当前工作簿A1单元格内容
Range("A1").Clear
' 单元格具体操作
Call Table_Range_Sub
End Sub
Sub Table_Range_Sub()
' 引用单个单元格
Range("A1").Value = 100
' 引用多个单元格
Range("A2,B2,C2").Value = 200
' 引用单个单元格区域
Range("A4:C6").Value = 300
' 引用单个单元格及区域
Range("A8,E5:F6").Value = 400
' 引用自定义的区域名称
Range("ThisE8F9").Value = 500
' 引用整行或整列
'Range("11:11,H:H").Value = "cc"
Range("11:11").Value = 11
Range("H:H").Value = "H"
' 引用相连整行或整列
Range("I:K,13:14").Value = 1314
End Sub
代码2 - 单元格选择、偏移,及效果

下列代码先执行Table_Cells_Sub,之后执行Table_Offset_Sub
' 与Excel交互 - 单元格 - Cells、Offset属性.
' Cells 选择单元格(行、列)
Sub Table_Cells_Sub()
' 引用工作表中的单元格
Worksheets("Sheet2").Cells(5, 2) = 100
' 引用单元格区域
Range(Cells(8, 2), Cells(13, 5)).Value = 200
' 引用单元格区域内的单元格
Range("B8:E13").Cells(3, 2).Value = "TEST"
End Sub
' Offset 单元格偏移
Sub Table_Offset_Sub()
' 在单元格B5为准偏移2行1列并赋值
Range("B5").Offset(2, 1).Value = "21"
' 在单元格C7为准偏移-2行-2列并赋值
Range("C7").Offset(-2, -2).Value = "-22"
End Sub
代码3 - 单元格内容拷贝剪切、引用公式、格式操作,及效果

Option Explicit
Sub CellRefTest()
' 区域拷贝到D2
Range("A1:B10").Copy Range("D2")
' 区域剪切到D2
Range("A1:B10").Cut Range("G3")
' 引用公式
Range("J3").Formula = "=sum(G3,H3)"
' 更改文字操作 - 1
' Range("G3:H12").Font.Name = "Courier New"
' Range("G3:H12").Font.Size = 15
' Range("G3:H12").Font.Bold = True
' Range("G3:H12").Font.Italic = True
' Range("G3:H12").Font.Color = RGB(125, 125, 125)
' 更改文字操作 - 2
With Range("G3:H12").Font
.Name = "微软雅黑"
.Size = 16
.Bold = True
.Italic = True
.Color = vbBlue
End With
' 更改边框线
With Range("G3:H12").Borders
.LineStyle = xlDouble
.Color = vbRed
.Weight = xlThick
End With
' 区域填充颜色
Range("G3:H12").Interior.Color = RGB(134, 223, 25)
' 设置区域对齐方式
With Range("G3:H12")
.HorizontalAlignment = xlRight
.VerticalAlignment = xlBottom
End With
' 设置区域内容缩进大小
With Range("G3:H12")
.HorizontalAlignment = xlLeft
.InsertIndent 3
End With
' 设置自动换行
Range("A12").Value = "这个单元格是测试自动换行的。"
Range("A12").WrapText = True
End Sub
代码4 - 用"For"遍历单元格,完成偏移拷贝区域功能

' 用"For"遍历单元格,完成拷贝区域功能
Sub Test1()
' 设置B2:E5区域内容
Range("B2:E5").Value = 100
' 设置区域对象
Dim Rng As Range
Set Rng = Range("B2:E5")
' 完成偏移拷贝区域功能
Dim RNum As Integer, CNum As Integer
For RNum = 1 To Rng.Rows.Count
For CNum = 1 To Rng.Columns.Count
Range("D8").Offset(RNum, CNum) = Rng.Cells(RNum, CNum)
Next CNum
Next RNum
End Sub
代码5 - ’ 用"For Each"遍历工作表,并打印名称

' 用"For Each"遍历工作表,并打印名称
Sub Test()
Dim sheet As Worksheet
For Each sheet In Worksheets
Debug.Print sheet.Name
MsgBox sheet.Name
Next sheet
End Sub
代码6 - Range对象使用
Sub WorkbooksTest()
' 定义Range对象
Dim obj As Range
' 对Range对象赋值
Set obj = Range("B4:C5")
' 将Range列数打印
MsgBox obj.Column
End Sub
关注
笔者 - jxd
文章展示了使用VBA进行Excel单元格的引用、赋值、偏移、拷贝、剪切、格式设置以及工作表遍历的方法,包括通过Range和Cells属性选择、偏移单元格,应用公式,以及调整字体、边框和对齐方式等格式操作。
6438

被折叠的 条评论
为什么被折叠?



