Excel 宏录制与VBA编程 ——VBA编程技巧篇三 (未初始化Range判断、遍历工作表方法、工作表多行重复内容剔除)

未初始化Range的判断

有时候需要对已定义未初始化的range对象做判断

cpp 复制代码
dim curRange as range
If curRange Is Nothing Then
    debug.print("未初始化的..")
End If

遍历工作表方法

Chr(10):ASCII码中的换行键,相当于vbLF。

Chr(13):ASCII码中的回车键,相当于vbCR。

1、使用For...Next 语句遍历工作簿中所有的工作表

cpp 复制代码
Sub ShCount1()
    Dim c As Integer
    Dim i As Integer
    Dim s As String
    c = Worksheets.Count
    For i = 1 To c
        s = s & Worksheets(i).Name & Chr(13)
    Next
    MsgBox "工作簿中含有以下工作表:" & Chr(13) & s
End Sub

2、使用For Each...Next语句遍历工作簿中所有的工作表

cpp 复制代码
Sub ShCount2()
    Dim Sh As Worksheet
    Dim s As String
    For Each Sh In Worksheets
        s = s & Sh.Name & Chr(13)
    Next
    MsgBox "工作簿中含有以下工作表:" & Chr(13) & s
End Sub

工作表多行重复内容剔除

将a列内容拷贝到b列:将重复内容删除掉后拷贝

cpp 复制代码
Sub RunTest2()

    ' 将b列清理掉
    Range("b:b").Clear

    ' 将标题头拷贝到b列
    Range("a1").Copy Destination:=Range("b1")

    ' 计算末尾行号
    Dim EndRowNum As Integer
    EndRowNum = Range("a1").End(xlDown).Row
    
    ' 由后向前循环遍历
    Dim Num As Integer
    For Num = 2 To EndRowNum Step 1
        If WorksheetFunction.CountIf(Columns(2), Cells(Num, 1).Value) < 1 Then
            Cells(Num, 1).Copy Destination:=Cells(Range("b65535").End(xlUp).Row + 1, 2)
        End If
    Next

End Sub

关注

笔者 - jxd

相关推荐
wtsolutions2 小时前
JSON to Excel Add-in - Seamless Integration Within Excel
json·excel
wtsolutions2 小时前
Getting Started with JSON to Excel Web App - Convert in Seconds
json·excel·web app
wtsolutions6 小时前
Using the JSON to Excel API - Programmatic Access for Developers
json·excel
qq_435139576 小时前
EasyExcel(FastExcel)Excel导出功能 技术文档
excel
wtsolutions9 小时前
Understanding JSON Formats - What JSON to Excel Supports
json·excel
wtsolutions9 小时前
Advanced Features - Unlocking the Power of JSON to Excel Pro
linux·json·excel
fs哆哆11 小时前
VB.NET和VBA教程-如何查找Excel数据区域边界
excel
小矮强11 小时前
Excel中根据年月日提取月日,并按月日进行排序
excel
开开心心_Every11 小时前
图片批量压缩工具:支持有损无损两种模式
python·游戏·微信·django·pdf·excel·语音识别
wtsolutions12 小时前
Real-World Use Cases - How Organizations Use JSON to Excel
json·excel