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

相关推荐
UR的出不克10 小时前
使用 Python 爬取 Bilibili 弹幕数据并导出 Excel
java·python·excel
wtsolutions10 小时前
Understanding Excel Data Formats - What Excel to JSON Supports
ui·json·excel
ぁず10 小时前
excel想生成一列随机数并删除公式保留值
excel
wtsolutions13 小时前
Real-World Use Cases - How Organizations Use Excel to JSON
json·github·excel
一只小H呀の13 小时前
pandas处理excel数据
excel·pandas
wregjru13 小时前
【操作系统】3.开发工具
excel
wtsolutions16 小时前
MCP Service Integration - Excel to JSON for AI and Automation
人工智能·json·excel
wtsolutions1 天前
JSON to Excel Add-in - Seamless Integration Within Excel
json·excel
wtsolutions1 天前
Getting Started with JSON to Excel Web App - Convert in Seconds
json·excel·web app
wtsolutions1 天前
Using the JSON to Excel API - Programmatic Access for Developers
json·excel