自己写的实用VBA代码合集√

Excel中✓符号的四种技术路径与兼容性实战指南 在Excel中,对勾(✓)不仅是视觉标记,更是承载业务状态的关键数据元素。其底层本质是Unicode字符(U+2713),但实际应用中常因字体依赖(如Wingdings)、编码混淆或输入不规范,导致条件格式失效、COUNTIF统计为0、PDF导出错位及邮件乱码等问题。真正稳定的解决方案需区分‘显示’与‘数据’:优先采用Unicode字符输入保障跨平台兼容性,结合数据验证实现防错输入,再通过条件格式建立状态反馈,最终以VBA宏驱动自动化流程。本文聚焦Check Mark与Excel符号两大核心热词,系统梳理从 阅读详情

1.遍历所有已打开的word文档

For Each docOpened In Documents
   ……
Next docOpened

2.Word 将目录下所有文档转换为txt,并删除原文档

Sub 目录下doc转txt()
'目录下所有word文档转为txt,并删除word文档
'保存在原目录
    '遍历所有文件夹,把带路径的文件名存入字典
    On Error Resume Next
    Dim Path As String, t 'Path为路径,t用于计算程序执行花费的时间
    Set objshell = CreateObject("Shell.Application")
    Set objfolder = objshell.BrowseForFolder(0, "选择文件夹", 0, 0)
    If Not objfolder Is Nothing Then Path = objfolder.self.Path & "\"
    Set objfolder = Nothing
    Set objshell = Nothing    
    '创建字典用于存储路径和文件名
    Dim DicPath, DicFile, i As Integer, Ke, ContentName As String, FileName As String, MsgTxt
    Set DicPath = CreateObject("Scripting.Dictionary")
    Set DicFile = CreateObject("Scripting.Dictionary")
    DicPath.Add Path, ""
    i = 0
    '存所有路径
    Do While i < DicPath.count
        Ke = DicPath.keys
        ContentName = Dir(Ke(i), vbDirectory)
        Do While ContentName <> ""
            '若有子文件夹,则添加
            '跳过当前的目录及上层目录
            If ContentName <> "." And ContentName <> ".." Then
                If GetAttr(Ke(i) & ContentName) = vbDirectory Then
                    DicPath.Add (Ke(i) & ContentName & "\"), ""
                End If
            End If
                ContentName = Dir
        Loop
        i = i + 1
    Loop
    '存所有doc文件名
    For Each Ke In DicPath.keys
        FileName = Dir(Ke & "*.doc")
        Do While FileName <> ""
            DicFile.Add (Ke & FileName), ""
            FileName = Dir
        Loop
    Next Ke    
    '打开文件
    Application.DisplayAlerts = wdAlertsNone
    Dim myDoc
    For Each Ke In DicFile.keys
        Set myDoc = Documents.Open(Ke)
        '原路径另存为TXT
        ActiveDocument.SaveAs2 FileName:=myDoc.Path & "\" & Left(myDoc.Name, InStrRev(myDoc.Name, ".") - 1) & ".txt", FileFormat:=wdFormatText
        '处理完成后关闭并删除原word文档
        ActiveDocument.Close
        Kill Ke
    Next Ke
    MsgBox "Done!"
End Sub

3.获取网页源代码

有时源代码里的中文会变成乱码,此时用StrConv函数转换成unicode,问题即可解决
Dim httpRequest As Object
    Set httpRequest = CreateObject("MSXML2.XMLHTTP.3.0")
    httpRequest.Open "GET", "http://develop.100ppi.com/tmp/autoproduct/ccq2/ci/cha_num.php?pid=" & ItemID & "&sdate=" & sDate & "&edate=" & eDate, False
    httpRequest.Send
    txtTemp = httpRequest.responseText
    或txtTemp = StrConv(httpRequest.responsebody, vbUnicode)

4.Excel合并相同文件名的单元格,不同文件名的行填充不同的背景色

A列填了文件名,已排序。
Dim i As Integer, j As Integer, k As Integer 'i用于遍历,j用于计数须合并的行数,k用于填充颜色
i = 1
k = 0
With wbTmp
    Do While .Cells(i + 1, 1) <> ""
        j = 1
        Do While .Cells(i, 1) = .Cells(i + j, 1)
           j = j + 1
        Loop
        If j > 1 Then
            .Range(.Cells(i, 1), .Cells(i + j - 1, 1)).Merge
        End If
        If (k Mod 2 = 1) Then
            .Cells(i, 1).Resize(j, 5).Interior.Color = 5296274
        Else: .Cells(i, 1).Resize(j, 5).Interior.Color = 49407
        End If
        k = k + 1
        i = i + j
    Loop
End With

5.若同目录下不存在某文件夹,则创建

Dim sr
sr = Dir(ThisWorkbook.Path & "\上海办待导入txt", vbDirectory)
If sr = "" Then
    MkDir ThisWorkbook.Path & "\上海办待导入txt"
End If

6.Word替换昨日今日去年之类的字眼

Sub 替换昨今去()
Dim Yesterday_Day As Integer, Yesterday As String, Yesterday_Month As Integer, Yesterday_Year As Integer
Dim Today_Day As Integer, Today_Month As Integer, Today_Year As Integer
Yesterday = DateAdd("d", -1, Date)
Yesterday_Day = Day(Yesterday)
Yesterday_Month = Month(Yesterday)
Yesterday_Year = Year(Yesterday)
Today_Day = Day(Date)
Today_Month = Month(Date)
Today_Year = Year(Date)




    '选择性粘贴
    Selection.PasteAndFormat (wdPasteDefault)
    
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting


    '取消所有超链接
    Dim cc As Field
    For Each cc In ActiveDocument.Fields
    If cc.Type = wdFieldHyperlink Then
    cc.Unlink
    End If
    Next
    Set cc = Nothing


    '替换昨天、昨日
    With Selection.Find
        .Text = "昨[天日]{1}"
        .Replacement.Text = Yesterday_Month & "月" & Yesterday_Day & "日"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '替换今天、今日
    With Selection.Find
        .Text = "今[天日]{1}"
        .Replacement.Text = Today_Month & "月" & Today_Day & "日"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '替换今年
    With Selection.Find
        .Text = "今年"
        .Replacement.Text = Today_Year & "年"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '替换去年
    With Selection.Find
        .Text = "去年"
        .Replacement.Text = Today_Year - 1 & "年"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '删象屿期货的段前符号
    With Selection.Find
        .Text = ChrW(61548)
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = True
        .MatchWildcards = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '手动换行符替换成回车符
    With Selection.Find
        .Text = "^l"
        .Replacement.Text = "^p"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = True
        .MatchWildcards = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '段与段顶多只隔一行,将任意个回车符号替换成二个
    With Selection.Find
        .Text = "(^13)@"
        .Replacement.Text = "^p^p"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '全选+剪切
    Selection.WholeStory
    Selection.Cut
End Sub

7.提取word文档里的图片

Sub 存成html()
Application.ScreenUpdating = False


    Dim FileName As String
    FileName = InputBox("请输入文件名")
    Selection.Copy
    Documents.Add DocumentType:=wdNewBlankDocument
    Selection.PasteAndFormat (wdPasteDefault)
    '若无目录则创建
    If Dir("D:\backup\140591\桌面\报告temp\", vbDirectory) = "" Then MkDir "D:\backup\140591\桌面\报告temp\"
    ActiveDocument.SaveAs FileName:="D:\backup\140591\桌面\报告temp\" & FileName, FileFormat:=wdFormatHTML, _
        LockComments:=False, Password:="", AddToRecentFiles:=True, WritePassword _
        :="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
        SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
        False
    ActiveWindow.View.Type = wdWebView
    '段与段顶多只隔一行,将任意个回车符号替换成二个
    With Selection.Find
        .Text = "(^13)@"
        .Replacement.Text = "^p^p"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '全选+剪切
    Selection.WholeStory
    Selection.Cut
    
    ActiveDocument.Close False
Application.ScreenUpdating = True
MsgBox "已完成!"
End Sub

8.Word 删除新闻中的多余代码和文字

Sub 新闻排版()
'
'
    '选择性粘贴
    Selection.PasteAndFormat (wdPasteDefault)
    
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    
    '删图片
    Dim oInlineShape As InlineShape
    For Each oInlineShape In ActiveDocument.InlineShapes
        oInlineShape.Delete
    Next


    '取消所有超链接
    Dim cc As Field
    For Each cc In ActiveDocument.Fields
    If cc.Type = wdFieldHyperlink Then
    cc.Unlink
    End If
    Next
    Set cc = Nothing


    '删(微博)[微博]
    With Selection.Find
        .Text = "[\[\(\(]微博[\)\]\)]"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '删(博客,微博)
    With Selection.Find
        .Text = "(博客,微博)"
        .Replacement.Text = "^p^p"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = True
        .MatchWildcards = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '删象屿期货的段前符号
    With Selection.Find
        .Text = ChrW(61548)
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = True
        .MatchWildcards = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '删小标题后的/
    With Selection.Find
        .Text = "/^p"
        .Replacement.Text = "^p"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = True
        .MatchWildcards = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '删股票代码
    With Selection.Find
        .Text = "\([\-0-9.]{1,}[,^s]{1,}[\-0-9.]{1,}[,^s]{1,}[\-0-9.%]{1,}\)"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '删股票涨跌值
    With Selection.Find
        .Text = "\[[\-0-9.%]{1,}\]"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '删[2.98% 资金 研报]
    With Selection.Find
        .Text = "\[[\-0-9.%]{1,}^s资金^s研报\]"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '删(600648,股吧)
    With Selection.Find
        .Text = "\([0-9]{6},[股吧基金]{2,3}\)"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
        
    '手动换行符替换成回车符
    With Selection.Find
        .Text = "^l"
        .Replacement.Text = "^p"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = True
        .MatchWildcards = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '段与段顶多只隔一行,将任意个回车符号替换成二个
    With Selection.Find
        .Text = "(^13)@"
        .Replacement.Text = "^p^p"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchByte = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    
    '全选+剪切
    Selection.WholeStory
    Selection.Cut
End Sub
 

9.Excel双击则复制单元格内容到剪切板

放到Worksheet对应的代码中
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    With CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
        .SetText Target
        .PutInClipboard
    End With
End Sub

10.用对话框打开Excel文件

iFileName = Application.GetOpenFilename("Excel文件 (*.xlsx;*.xls), *.xlsx;*.xls")

11.Excel按指定列升序排列

With wbf.Sort
    .SortFields.Clear
    .SortFields.Add Key:=Range("B1"), SortOn:=xlSortOnValues, Order:=xlAscending 'descending,递减。Ascending,递增
    .SetRange Range("A1").CurrentRegion '排序区域
    .Header = xlGuess '第一行包含标题
    .MatchCase = False '不区分大小写
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

12.汉字编码成URL用的字符串

Public Function Escape(ByVal strText As String) As String
    Set JS = CreateObject("msscriptcontrol.scriptcontrol")
    JS.Language = "JavaScript"
    Escape = JS.eval_r("encodeURI('" & Replace(strText, "'", "\'") & "');")
End Function

13.Excel汇总同目录文件

Sub HzWb()
    Dim bt As Range, r As Long, c As Long
    r = 1    '1 是表头的行数
    c = 8    '8 是表头的列数
    Range(Cells(r + 1, "A"), Cells(65536, c)).ClearContents    ' 清除汇总表中原表数据
    Application.ScreenUpdating = False
    Dim FileName As String, wb As Workbook, Erow As Long, fn As String, arr As Variant
    FileName = Dir(ThisWorkbook.Path & "\*.xls") '返回一个Excel文件,可匹配到.xlsx
    Do While FileName <> ""
        If FileName <> ThisWorkbook.Name Then    ' 判断文件是否是本工作簿
            Erow = Range("A1").CurrentRegion.Rows.Count + 1    ' 取得汇总表中第一条空行行号
            fn = ThisWorkbook.Path & "\" & FileName
            Set wb = GetObject(fn)    ' 将fn 代表的工作簿对象赋给变量
            Set sht = wb.Worksheets(1)    ' 汇总的是第1 张工作表
            ' 将数据表中的记录保存在arr 数组里
            arr = sht.Range(sht.Cells(r + 1, "A"), sht.Cells(65536, "B").End(xlUp).Offset(0, 8))
            ' 将数组arr 中的数据写入工作表
            Cells(Erow, "A").Resize(UBound(arr, 1), UBound(arr, 2)) = arr
            wb.Close False
        End If
        FileName = Dir    ' 用Dir 函数取得其他文件名,并赋给变量
    Loop
    Application.ScreenUpdating = True
End Sub

14.Excel 将指定 数据另存为txt文件

'新建一张表用于存放待保存的数据
Set wbTmp = ThisWorkbook.Worksheets.Add(after:=wb)

'复制待保存的数据
wb.Cells(2 + iJx, "C").Resize(iSc, 1).Copy wbTmp.Cells(1, 1)
wb.Cells(2 + iJx, "R").Resize(iSc, 1).Copy wbTmp.Cells(1, 2)

'将新表复制出来成为一个单独的文件并另存为txt
wbTmp.Copy
ActiveWorkbook.SaveAs FileName:=ThisWorkbook.Path & "\自定义文件名.txt", FileFormat:=xlText, CreateBackup:=False

'关闭上一步出现的新Workbook
ActiveWorkbook.Close False

'删除原文件中的临时表
wbTmp.Delete



(转)Excel VBA 操作 Word(入门篇) 原文地址 本文的对象是:有一定Excel VBA基础,对Word VBA还没有什么认识,想在Excel中通过VBA操作Word还有困难的人。 一、新建Word引用 需要首先创建一个对 Word Application 对象的引用。在VBA中,工具-引用,选取“MicroSoft Word 11.0 Object Library”。 方法一、New Word.App... 阅读详情

相关推荐

多种办公功能的WORD VBA程序

word的VBA办公助手 源代码。

VB973490770的专栏 1511

自己写的实用VBA代码合集

1.遍历所有已打开的word文档 For Each docOpened In Documents …… Next docOpened 2.Word 将目录下所有文档转换为txt,并删除原文档 Sub 目录下doc转txt() '目录下所有word文档转为txt,并删除word文档 '保存在原目录 '遍历所有文件夹,把带路径的文件名存入字典 On E...

dlxqlig0806的博客 7181

【SAP GUI 脚本 VBA】

在Excel中用VBA编写SAP GUI脚本,实现办公自动化

qq_43156252的博客 1万+

VBA常用语句116句,让你操作无限

(1) Option Explicit '强制对模块内所有变量进行声明 (2) Option Base 1 '指定数组的第一个下标为1 (3) On Error Resume Next '忽略错误继续执行VBA代码,避免出现错误消息 (4) On Error GoTo 100 '当错误发生时跳转到过程中的某个位置 (5) On Error GoTo 0 '恢复正常的错误提示 (6) Application.DisplayAlerts=False '在程序执行过程中使出现的警告框不显示 (7) Applica

qq_40621901的博客 4594

使用libx265对YUV进行h265编码

使用libx265对YUV进行h265编码

Embedded engineer 3079

从零到一:STM32 CubeMX与WS2812B的DMA驱动艺术

本文详细介绍了如何使用STM32 CubeMX和DMA技术驱动WS2812B RGB LED灯条,从硬件设计到软件实现的全过程。通过CubeMX配置定时器和DMA,实现高效的PWM波形生成与数据传输,解决传统GPIO控制资源占用高的问题。文章还提供了颜色编码、动画效果实现及常见问题解决方案,助力开发者快速掌握智能LED控制技术。

weixin_28278377的博客 978

WORD-VBA自用程序代码记录-20240701

word用VBA提高办公效率

VB973490770的专栏 757

1 FFmpeg从入门到精通-FFmpeg简介

1.FFmpeg简介 1.1 FFmpeg的定义 1.2 FFmpeg的历史 1.3 FFmpeg的基本组成 1.4 FFmpeg的编解码工具ffmpeg 1.5 FFmpeg的播放器ffplay 1.6 FFmpeg的多媒体分析器ffprobe 1.7 FFmpeg编译(1)FFmpeg之Windows平台编译(2)FFmpeg之Linux平台编译(3)FFmpeg之OS X平台编译 1.8 FFmpeg编码支持与定制(1)FFmpeg的编码器支持(2)FFmpe

migu123的专栏 3691

VBA常用代码总结

VBA代码总结

Eternal_Whispers的博客 1万+

基于Python的闲鱼商品价格评估模型:爬虫+价格预测全实现

本文介绍了一个完整的全球气候数据抓取与分析流程,采用轻量化的技术栈(requests+pandas+matplotlib+folium),实现以下核心功能: 全球城市定向抓取:支持自定义城市列表,自动获取经纬度并抓取多源气候数据 双数据源互补:结合OpenWeatherMap API(实时数据)和Climate-Data.org(历史数据) 全维度覆盖:采集气温、降水、湿度等核心指标,并进行自动化清洗转换 丰富可视化:生成热力图、趋势图和统计图表,支持地理定位展示 灵活扩展:模块化设计便于新增城市或扩展数据

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 3047

WhatsApp网页版扫码分析

扫码登录本质上是WhatsApp的多设备登录,设备之间可以独立运行,那么当我们首次通过WhatsApp扫码登录二维码时,到底发生了那些事情?交换了那些数据?

SocialMarketing的博客 5230

QTP的那些事---webtable的一些重要使用集合精解

' ******************************** Function Library ********************************* ' Registering both functions RegisterUserFunc "WebTable", "ObjectsByMicClass", "ObjectsBy...

weixin_34290390的博客 185

Ubuntu 22.04/24.04 安装 ROS2 完整教程(Humble / Jazzy)

最后更新:2026年2月适用系统:Ubuntu 22.04 LTS(Jammy) / Ubuntu 24.04 LTS(Noble)适用架构:x86_64 / arm64(包括树莓派)

2401_84116277的博客 6011

技巧篇:常用的vba代码汇总

一些常用的vba代码集合

郑小柒是西索的博客 6493

使用 MATLAB/Simulink + Simscape Electrical,构建一个含光伏并网系统与SVG的联合仿真模型,实现动态无功补偿与电压支撑

摘要:本文详细介绍了基于Simulink的SVG与光伏并网逆变器联合系统建模方法。通过构建包含光伏单元、SVG主电路和控制模块的仿真模型,实现动态无功补偿与电压稳定。重点阐述了ip-iq无功检测算法、双闭环控制和SVPWM调制等关键技术。仿真结果表明,该系统能快速响应无功需求,在10ms内将功率因数提升至0.98以上,有效抑制电压波动。文章为新能源并网系统中的电能质量治理提供了实用解决方案,并提出了进一步优化方向。

xiaoheshang_123的博客 322

(九)DFI接口时序

文章目录一、DFI Interface 一、DFI Interface   DFI接口是连接DDR Controller与DDR_PHY之间的通用接口,其信号组如下表:       

Mr.翟的博客 1万+

VBA宏实现Word论文自动排版

VBA宏实现Word论文自动排版

qq_49750651的博客 9047

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

图片木马(海阳木马)的代码及防止上传的方法

一、海阳图片木马代码:其实不一定是这样,只要是HTML代码或ASP任何代码均可。%@ LANGUAGE="VBSCRIPT" codepage ="936" %>title>111title>style>body{font-family: 宋体 ; font-size: 10pt}table{ font-family: 宋体; font-size: 9pt }a{ font-famil

思科网络 4256

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

(原创)同Scripting.Dictionary等价的字典类

写此类的原因是因为个人所写的"模版类".,因为很多免费的个人主页空间(因为阿拉穷啊,没钱买空间啊=.=)都不提供FSO.所以导致Scripting.Dictionary也不能使用,所以那"模版类"就不能运行了.于是就有了自己写一个"字典类"的念头.此类同Scripting.Dictionary对象的使用没有任何的区别,所以以前是根据Scripting.Dictionary来写的程序,不用怎样的

鱼的天堂与地狱 1356

VBA Word

VBA不仅可以操作Excel也可以操作Word,Word也有开发工具也有宏录制。

人不风流枉少年 573

asp中Scripting.Dictionary字典对象使用示例

vbscript的Scripting.Dictionary创建了类似于Key索引对应Value值的字典对象,通过Key直接索引到指定的Value。 VBScript中Scripting.Dictionary使用示例如下: Dim objDict Set objDict = WSH.CreateObject("Scripting.Dictionary") ' .Add(k

夜鹏少的博客 2799

VBA常用代码

VBA常用代码

ribut9225的专栏 8966

VBA代码合集(更新2023.10.26)

【代码】VBA代码合集(更新2022.12.21)

m0_63356449的博客 5648

VBA代码自学收集(150例)

VBA代码自学收集(150例)

qq_38220914的博客 4万+

VBA:VBA常用小代码合集

说起排序这个词,想必大家都不陌生,这是数据处理过程中最常见的操作之一,但我们今天聊的不是数据排序,而是如何对工作表排序。我举个例子,如下图所示,一张工作簿有N张工作表,现在需要按升序对其重新排序。操作步骤如下:首先使用以下代码将工作表的名称罗列在当前表的A列.Clear '清除所有.NumberFormat = "@" '设置文本格式End Withk = 1Cells(1, 1) = "目录"For Each sht In Sheets '遍历工作表k = k + 1 '累加个数。

nianfen的博客 6551

网页取行情数据-2

方案3 门户网站获取行情 Sina股票数据接口 (股票见网上http://www.cnblogs.com/luluping/archive/2010/11/15/1877817.html) 期指内容: 分析网页 http://finance.sina.com.cn/futures/quotes/IC1605.shtml 获取接口 hq.sinajs.cn/?&list=CFF_R

fonjames的专栏 2448
上一篇: Python 遍历目录找出包含指定字符串的文件夹
下一篇: Python 登录网站后台
KingLearnJava
博客等级 码龄12年 93粉丝 84原创
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值