vba编程代码大全(全解vba初学者编程代码大全),小编带你了解更多信息 。
文章插图
1单元格合并:
Sub 宏1()
Dim i As Long
For i = 1 To 10
Cells(i, 3) = Cells(i, 1).Value & “-” & Cells(i, 2).Value
Next
End Sub
2. 单元格区域存入VBA数组
文章插图
Sub 宏1()
Dim arr ‘声明一个变量
Dim x As Integer
arr = Range(“a1:d10”) ‘确定arr的范围,也就是我们操作的区域
For x = 1 To 7
arr(x, 4) = arr(x, 3) * arr(x, 2) ‘数组的赋值方法
Next x
Range(“a1:d4”) = arr ‘数组最终的赋值区域,区域不同结果不同,但不能超出前面定义的范围
End Sub
3一维VBA数组放入单元格区域中
文章插图
Sub 宏1()
Dim arr(1 To 5) ‘声明一个变量,固定数组A1到E1
For x = 1 To 5
arr(x) = x * 3 ‘声明单个单元格的计算方法
Next x
Range(“a1:e1”) = arr ‘把单元格计算的结果赋值给我们选定的数组
Range(“a1:a5”) = Application.Transpose(arr) ‘把我们选定的数组做转置,出结果A1到A5
End Sub
4提取符合条件的单元格
文章插图
Sub ggsmart()
Dim i%, xrow%, j%, xcount% ‘定义变量xrow为A列单元格数目,xcount为包含张的个数
Dim arr() As String ‘定义arr为动态数组,由于不确定动态数组的边界
xrow = [a65536].End(3).Row ‘算出A列最后一个非空单元格行号然后赋值给Xrow
j = 1 ‘数组索引号
xcount =
Application.WorksheetFunction.CountIf([a1:a65536], “张*”) ‘统计有多少姓张的学生赋值给xcount
ReDim arr(1 To xcount) ‘重新定义数组大小,元素共有xcount个,此时xcount已经有值了
For i = 1 To xrow ‘定义i的取值范围
If Left(Cells(i, 1).Value, 1) = “张” Then
arr(j) = Cells(i, 1).Value ‘给数组中各个元素赋值
j = j + 1 ‘索引号加1
End If
Next i
[b1:b65536].Clear ‘清除原有数据
[b1].Resize(1, xcount) = arr ‘对B1往右的xcount个单元格输入数组的值
[b1].Resize(xcount, 1) =
Application.WorksheetFunction.Transpose(arr) ‘对B1往下的xcount个单元格输入数组的值
End Sub
5判断非空单元格,并提取(空格为一个)
文章插图
Sub test()
Dim arr, arr1(1 To 10000, 1 To 1)
Dim x, m, k
arr = Range(“a1:a21”)
For x = 1 To UBound(arr)
If arr(x, 1)“” Then
k = k + 1
arr1(k, 1) = arr(x, 1)
Else
m = m + 1
Range(“b1”).Offset(0, m).Resize(k) = arr1
Erase arr1
k = 0
End If
Next x
End Sub
6数组计算
文章插图
Sub test()
Dim arr, x
arr = Range(“a1:d6”)
For x = 1 To UBound(arr)
arr(x, 1) = arr(x, 1) * 3
arr(x, 2) = arr(x, 1) * 3
arr(x, 3) = arr(x, 1) * arr(x, 2)
arr(x, 4) = arr(x, 3) * arr(x, 2)
Next x
Range(“a8:d13”) = arr
End Sub
7字典
文章插图
Sub t() ’(字典装入数字)
Dim d
Dim arr
Dim x As Long
Set d = CreateObject(“scripting.dictionary”)
For x = 1 To 6
d.Add Cells(x, 1).Value, Cells(x, 2).Value’这种装入只能在KEYS列装入非重复的
Next x
Range(“d1”).Resize(d.Count) = Application.Transpose(d.keys)
Range(“e1”).Resize(d.Count) = Application.Transpose(d.items)
End Sub
文章插图
Sub rr()
Dim d
Dim arr
Dim x As Long
arr = Range(“a1:b16”)
Set d = CreateObject(“scripting.dictionary”)
For x = 1 To 16
d(arr(x, 1)) = d(arr(x, 1)) + arr(x, 2)’这种修改的方法最常用,可以删除重复值,单条件汇总
Next x
Range(“d1”).Resize(d.Count) = Application.Transpose(d.keys)
Range(“e1”).Resize(d.Count) = Application.Transpose(d.items)
End Sub
8提取所有工作表名称
Sub 提取所有工作表名称()
For x = 1 To Sheets.Count
Cells(x, 7) = Sheets(x).Name
Next x
【全解vba初学者编程代码大全 vba编程代码大全】
- 三万字实操手册:房地产投资基金运作最全解析
- 偷渡什么意思 偷渡什么意思全解
- 新手化学快速入门教程图解 滑雪技巧初学者单板简单步骤
- 小嘴女人面相性格好吗,女人嘴小面相全解!
- 滑板新手十个简单动作 滑板初学者开始怎么练
- 新手吉他入门零基础教学 初学者0基础学吉他先学什么
- 围棋的玩法说明和规则[初学者零基础学围棋入门知识]
- vba中主要提供了3种数据库访问接口 vba 连接数据库
- 星座运势全解析 5月7日是什么星座
- 下 初学者如何提高象棋水平(怎么能快速学会下象棋)