实用excel宏代码(精华版)

合集下载

Excel宏大量简单常用宏

Excel宏大量简单常用宏

Excel宏大量简单常用宏代码目录链接类别打开全部隐藏工作表点击循环宏点击录制宏时调用“停止录制”工具栏点击高级筛选5列不重复数据至指定表点击双击单元执行宏(工作表代码)点击双击指定区域单元执行宏(工作表代码)点击进入单元执行宏(工作表代码)点击进入指定区域单元执行宏(工作表代码)点击在多个宏中依次循环执行一个(控件按钮代码)点击在两个宏中依次循环执行一个并相应修改按钮名称点击(控件按钮代码)在三个宏中依次循环执行一个并相应修改按钮名称点击(控件按钮代码)根据A1单元文本隐藏/显示按钮(控件按钮代码)点击当前单元返回按钮名称(控件按钮代码)点击当前单元内容返回到按钮名称(控件按钮代码)点击奇偶页分别打印点击打印自动打印多工作表第一页点击打印查找A列文本循环插入分页符点击打印将A列最后数据行以上的所有B列图片大小调整为所在点击对象单元大小返回光标所在行数点击查找和引用在A1返回当前选中单元格数量点击查找和引用返回当前工作簿中工作表数量点击查找和引用返回光标选择区域的行数和列数点击查找和引用工作表中包含数据的最大行数点击查找和引用返回A列数据的最大行数点击查找和引用将所选区域文本插入新建文本框点击对象批量插入地址批注点击批注批量插入统一批注点击批注以A1单元内容批量插入批注点击批注不连续区域插入当前文件名和表名及地址点击单元赋值不连续区域录入当前单元地址点击单元赋值连续区域录入当前单元地址点击单元赋值返回当前单元地址点击单元赋值不连续区域录入当前日期点击单元赋值不连续区域录入当前数字日期点击单元赋值不连续区域录入当前日期和时间点击单元赋值不连续区域录入对勾点击单元赋值不连续区域录入当前文件名点击单元赋值不连续区域添加文本点击单元赋值不连续区域插入文本点击单元赋值从指定位置向下同时录入多单元指定内容点击单元赋值按aa工作表A列的内容排列工作表标签顺序点击工作表工作表工作表工作表工作表文件管理工作表工作表点击单元赋值当前单元录入计算机用户名点击单元赋值解除全部工作表保护点击工作表为指定工作表加指定密码保护表点击密码在有密码的工作表执行代码点击密码执行前需要验证密码的宏(控件按钮代码)点击密码拷贝A1公式和格式到A2点击单元赋值复制单元数值点击单元赋值插入数值条件格式点击格式插入透明批注点击批注单元赋值定位定位定位定位定位定位点击单元赋值当前单元加2点击单元赋值单元赋值定位单元赋值单元赋值单元赋值单元赋值单元赋值单元赋值单元赋值单元赋值事件事件事件事件其他其他定位打印单元赋值对象事件其他信息事件单元赋值单元赋值点击事件指定允许编辑区域点击编辑解除允许编辑区域限制点击编辑删除指定行点击行列操作删除A列为指定内容的行点击行列操作删除A列非数字单元行点击行列操作有条件删除当前行点击行列操作选择下一行点击定位选择第5行开始所有数据行点击定位选择光标或选区所在行点击定位定位名称点击名称选择到指定列的最后行点击定位将Sheet1的A列的非空值写到Sheet2的A列点击单元赋值将名称1的数据写到名称2点击名称定位格式对象点击数据单元赋值名称名称点击工作表按A列数据批量修改表名称点击工作表按A列数据批量创建新表(控件按钮代码)点击工作表清除剪贴板点击其他批量清除软回车点击其他判断指定文件是否已经打开点击事件当前文件另存到指定目录点击文件管理文件管理文件管理文件管理文件管理文件管理文件管理文件管理文件管理引用指定位置单元内容为部分文件名另存文件点击文件管理将A 列数据排序到D列点击单元赋值将指定范围的数据排列到D列点击单元赋值定位行列操作点击数据取消数据有效限制点击数据重排窗口点击窗口按当前单元文本选择打开指定文件单元点击定位回车光标向右点击定位回车光标向下点击定位保护工作表时取消选定锁定单元点击工作表文件管理行列操作工作表工作表工作表工作表格式工作表工作表点击工作表工作表行列操作定位点击定位固定区域单元分类变色点击格式格式事件事件数据点击其他显示光标所在单元的批注的代码点击其他单元赋值事件事件事件事件点击单元赋值选择2至4行点击定位在当前选区有条件替换数值为文本点击事件自动筛选全部显示指定列点击筛选自动筛选第2列值为A的行点击筛选取消自动筛选()点击筛选全部显示指定表的自动筛选点击筛选强行合并单元点击格式格式单元赋值事件事件点击行列操作在A列产生不重复随机数点击单元赋值单元赋值单元赋值点击其他返回指定单元的行高和列宽点击信息指定行高和列宽点击格式指定单元的行高和列宽与A1单元相同点击格式填公式点击单元赋值工作表工作表单元赋值自定义函数信息超链接超链接超链接超链接查找和引用点击查找和引用返回表中各非空单元区域地址(行搜索)点击查找和引用查找和引用查找和引用查找和引用查找和引用查找和引用点击查找和引用返回A列非空单元数量点击查找和引用返回圆周率π点击其他定义指定单元内容为页眉/页脚点击打印提示并全部清除当前选择区域点击单元赋值全部清除当前选择区域点击单元赋值清除指定区域数值点击单元赋值对指定工作表执行取消隐藏》打印》隐藏工作表点击打印打开文件时执行指定宏(工作簿代码)点击事件关闭文件时执行指定宏(工作簿代码)点击事件信息事件点击工作表重算指定表点击工作表将第5行移到窗口的最上面点击窗口对第一张工作表的指定区域进行排序点击单元赋值显示指定工作表的打印预览点击打印用单元格A1的内容作为文件名另存当前工作簿点击文件管理[禁用/启用]保存和另存的代码点击文件管理在A和B列返回当前选区的名称和公式点击单元赋值朗读朗读A列,按ESC键中止点击语音朗读固定语句,请按ESC键终止点击语音在M和N列的14行以下选择单元时显示调用日历控件点击对象(工作表代码)添加自定义序列点击其他弹出打印对话框点击打印打印事件事件点击工作表把a列不重复值取到e列点击查找和引用查找和引用工作表点击事件事件其他点击其他按照当前行A列的图片名称插入图片到H列点击图片当前行下插入1行点击工作表取消指定行或列的隐藏点击工作表复制单元格所在行点击其他复制单元格所在列点击其他新建一个工作表点击工作表新建一个工作簿点击工作簿工作表事件工作簿点击工作簿合并A1至C1的内容写到D15单元的批注中点击批注自动重算点击其他手动重算点击其他EH帖子地址net/dispbbs.asp?boardid=4&id=239820。

excel宏命令详细讲解

excel宏命令详细讲解

excel宏命令详细讲解Excel宏命令是一种自动化操作工具,可以用来简化重复性的任务,提高工作效率。

本文将详细讲解一些较为冷门但实用的宏表函数,带你玩转宏命令。

一、自定义宏命令自定义宏命令可以根据个人的需求编写,可用于自动完成一系列复杂的操作。

以下是一个例子:Sub MyMacro'将选定的单元格背景设置为黄色Selection.Interior.Color = RGB(255, 255, 0)End Sub二、输入框函数输入框函数可以用来创建用户交互界面,用户可以在输入框中输入值,作为宏的参数。

以下是一个示例:Sub InputBoxDemoDim Value As StringValue = InputBox("请输入您的姓名:")MsgBox "欢迎您," & ValueEnd Sub三、循环函数循环函数可以重复执行一段代码。

以下是两种常用的循环函数:1. For循环For循环可以让代码块重复执行指定次数。

以下是一个示例:Sub ForLoopDemoDim i As IntegerFor i = 1 To 10Cells(i, 1).Value = iNext iEnd Sub2. Do While循环Do While循环会在条件满足时重复执行代码块。

以下是一个示例:Sub DoWhileLoopDemoDim i As Integeri=1Do While i <= 10Cells(i, 2).Value = i * 2i=i+1LoopEnd Sub四、选择函数选择函数可以用来根据条件选择性地执行不同的代码块。

以下是一个示例:Sub ChooseCaseDemoDim Value As StringValue = InputBox("请输入一个数字:")Select Case ValueCase "1"MsgBox "你输入的是数字1"Case "2"MsgBox "你输入的是数字2"Case ElseMsgBox "你输入的是其他数字"End SelectEnd Sub五、错误处理函数错误处理函数可以捕捉和处理出现的错误。

30个有用的ExcelVBA代码(16~20)

30个有用的ExcelVBA代码(16~20)

30个有用的ExcelVBA代码(16~20)16.突出显示所选内容中的可选行突出显示可选行可以极大地提高数据的可读性。

下面是一个代码,它将立即突出显示所选内容中的可选行。

Sub HighlightAlternateRows()Dim Myrange As Range Dim Myrow As Range Set Myrange = Selection For Each Myrow In Myrange.Rows If Myrow.Row Mod 2 = 1 Then Myrow.Interior.Color = vbCyan End If Next Myrow End Sub 注意,代码中指定了颜色为vbCyan(也可以修改成:vbRed, vbGreen, vbBlue)。

17.突出显示拼错单词的单元格Excel没有像在Word或PowerPoint中那样进行拼写检查。

虽然可以按F7键进行拼写检查,但当出现拼写错误时,没有视觉提示。

使用此代码可以立即突出显示其中有拼写错误的所有单元格。

Sub HighlightMisspelledCells() Dim cl As Range For Each cl I n edRange If Not Application.CheckSpelling(wor d:=cl.Text) Then cl.Interior.Color = vbRed End IfNext cl End Sub 请注意,突出显示的单元格包含Excel认为是拼写错误的文本。

当然在许多情况下,它也会其它各种错误。

18.刷新工作簿中的所有透视表如果工作簿中有多个透视表,则可以使用此代码一次刷新所有这些透视表。

Sub RefreshAllPivotTables() Dim PT As PivotTable For Each PT In ActiveSheet.PivotTables PT.RefreshTable Next PTEnd Sub 19.将所选单元格的字母大小写改为大写虽然Excel有更改文本字母大小写的公式,但它使您可以在另一组单元格中进行更改。

EXCEL实用VBA宏代码

EXCEL实用VBA宏代码

1 删除内容重复的行Sub DeleteRow()' 删除内容重复的行Dim R As IntegerDim i As IntegerWith Sheet1R = .[a65536].End(xlUp).RowFor i = R To 1 Step -1If WorksheetFunction.CountIf(.Columns(1), .Cells(i, 1)) > 1 Then.Rows(i).DeleteEnd IfNextEnd WithEnd Sub2 自动监视单元格Private Sub Worksheet_Change(ByVal Target As Range)Dim j, k, col As Integerj = Range("QTYS").Column'Range(iCol).Columnk = Target.Rowend_col = Range("end_cols").Column '13 '在这里调整颜色终止的最后一列col = Range("sum").Column'Stopqty = Target.ValueWith TargetIf .Count = 1 And .Row > 13 And .Column > col ThenIf Cells(k, col).Value = Cells(k, j).Value Then 'IsNumeric(Cells(k, col)) And Application.EnableEvents = FalseWith Range(Cells(k, 2), Cells(k, end_col)).Interior.ColorIndex = 4 'green.Pattern = xlSolidEnd WithApplication.EnableEvents = TrueElseIf Cells(k, col).Value > 0 And Cells(k, col).Value < Cells(k, j) ThenApplication.EnableEvents = FalseWith Range(Cells(k, 2), Cells(k, end_col)).Interior.ColorIndex = 6 ' yellow.Pattern = xlSolid 'xlNoneEnd WithApplication.EnableEvents = TrueElseIf Cells(k, col).Value > Cells(k, j).Value ThenApplication.EnableEvents = FalseWith Range(Cells(k, 2), Cells(k, end_col)).Interior.ColorIndex = 15.Pattern = xlSolid 'xlNoneEnd WithApplication.EnableEvents = TrueMsgBox "Actual Qty:" & qty & " > Order: " & Cells(k, j).Value & " or Wrong ?"ElseIf Cells(k, col).Value = 0 Or Cells(k, col).Value = "" ThenApplication.EnableEvents = FalseWith Range(Cells(k, 2), Cells(k, end_col)).Interior'.ColorIndex = 15.Pattern = xlNoneEnd WithApplication.EnableEvents = TrueEnd IfEnd IfEnd WithEnd Sub。

Excel-vba宏代码-大全

Excel-vba宏代码-大全

宏文件集▲打开全部隐藏工作表返回Sub 打开全部隐藏工作表()Dim i As IntegerFor i = 1 To Sheets.CountSheets(i).Visible = TrueNext iEnd Sub▲循环宏返回Sub 循环()AAA = Range("C2")Dim i As LongDim times As Longtimes = AAA'times代表循环次数,执行前把times赋值即可(不可小于1,不可大于2147483647)For i = 1 To timesCall 过滤一行If Range("完成标志") = "完成" Then Exit For '如果名为'完成标志'的命名单元的值等于'完成',则退出循环,如果一开始就等于'完成',则只执行一次循环就退出'If Sheets("传送参数").Range("A" & i).Text = "完成" Then Exit For '如果某列出现"完成"内容则退出循环Next iEnd Sub▲录制宏时调用“停止录制”工具栏返回Sub 录制宏时调用停止录制工具栏()mandBars("Stop Recording").Visible = TrueEnd Sub▲高级筛选5列不重复数据至指定表返回Sub 高级筛选5列不重复数据至Sheet2()Sheets("Sheet2").Range("A1:E65536") = "" '清除Sheet2的A:D列Range("A1:E65536").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheet2.Range( _"A1"), Unique:=TrueSheet2.Columns("A:E").Sort Key1:=Sheet2.Range("A2"), Order1:=xlAscending,Header:=xlGuess, _OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, SortMethod _:=xlPinYinEnd Sub▲双击单元执行宏(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)If Range("$A$1") = "关闭" Then Exit SubSelect Case Target.AddressCase "$A$4"Call 宏1Cancel = TrueCase "$B$4"Call 宏2Cancel = TrueCase "$C$4"Call 宏3Cancel = TrueCase "$E$4"Call 宏4Cancel = TrueEnd SelectEnd Sub▲双击指定区域单元执行宏(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)If Range("$A$1") = "关闭" Then Exit SubIf Not Application.Intersect(Target, Range("A4:A9", "C4:C9")) Is Nothing Then Call 打开隐藏表End Sub▲进入单元执行宏(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)'以单元格进入代替按钮对象调用宏If Range("$A$1") = "关闭" Then Exit SubSelect Case Target.AddressCase "$A$5" '单元地址(Target.Address),或命名单元名字()Call 宏1Case "$B$5"Call 宏2Case "$C$5"Call 宏3End SelectEnd Sub▲进入指定区域单元执行宏(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Range("$A$1") = "关闭" Then Exit SubIf Not Application.Intersect(Target, Range("A4:A9","C4:C9")) Is Nothing Then Call打开隐藏表End Sub▲在多个宏中依次循环执行一个(控件按钮代码)返回Private Sub CommandButton1_Click()Static RunMacro As IntegerSelect Case RunMacroCase 0宏1RunMacro = 1Case 1宏2RunMacro = 2Case 2宏3RunMacro = 0End SelectEnd Sub▲在两个宏中依次循环执行一个并相应修改按钮名称(控件按钮代码)返回Private Sub CommandButton1_Click()With CommandButton1If .Caption = "保护工作表" ThenCall 保护工作表.Caption = "取消工作表保护"Exit SubEnd IfIf .Caption = "取消工作表保护" ThenCall 取消工作表保护.Caption = "保护工作表"Exit SubEnd IfEnd WithEnd Sub▲在三个宏中依次循环执行一个并相应修改按钮名称(控件按钮代码)返回Option ExplicitPrivate Sub CommandButton1_Click()With CommandButton1If .Caption = "宏1" ThenCall 宏1.Caption = "宏2"Exit SubEnd IfIf .Caption = "宏2" ThenCall 宏2.Caption = "宏3"Exit SubEnd IfIf .Caption = "宏3" ThenCall 宏3.Caption = "宏1"Exit SubEnd IfEnd WithEnd Sub▲根据A1单元文本隐藏/显示按钮(控件按钮代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Range("A1") > 2 ThenCommandButton1.Visible = 1ElseCommandButton1.Visible = 0End IfEnd SubPrivate Sub CommandButton1_Click()重排窗口End Sub▲当前单元返回按钮名称(控件按钮代码)返回Private Sub CommandButton1_Click()ActiveCell = CommandButton1.CaptionEnd Sub▲当前单元内容返回到按钮名称(控件按钮代码)返回Private Sub CommandButton1_Click()CommandButton1.Caption = ActiveCellEnd Sub▲奇偶页分别打印返回Sub 奇偶页分别打印()Dim i%, Ps%Ps = ExecuteExcel4Macro("GET.DOCUMENT(50)") '总页数MsgBox "现在打印奇数页,按确定开始."For i = 1 To Ps Step 2ActiveSheet.PrintOut from:=i, To:=iNext iMsgBox "现在打印偶数页,按确定开始."For i = 2 To Ps Step 2ActiveSheet.PrintOut from:=i, To:=iNext iEnd Sub▲自动打印多工作表第一页返回Sub 自动打印多工作表第一页()Dim sh As IntegerDim xDim yDim syDim syzx = InputBox("请输入起始工作表名字:")sy = InputBox("请输入结束工作表名字:")y = Sheets(x).Indexsyz = Sheets(sy).IndexFor sh = y To syzSheets(sh).SelectSheets(sh).PrintOut from:=1, To:=1Next shEnd Sub▲查找A列文本循环插入分页符返回Sub 循环插入分页符()' Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容Dim i As LongDim times As Longtimes = Application.WorksheetFunction.CountIf(Sheet1.Range("a:a"), "分页")'times代表循环次数,执行前把times赋值即可(不可小于1,不可大于2147483647)For i = 1 To timesCall 插入分页符Next iEnd SubSub 插入分页符()Cells.Find(What:="分页", After:=ActiveCell, LookIn:=xlValues, LookAt:= _xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False) _.ActivateActiveWindow.SelectedSheets.HPageBreaks.Add Before:=ActiveCellEnd SubSub 取消原分页()Cells.SelectActiveSheet.ResetAllPageBreaksEnd Sub▲将A列最后数据行以上的所有B列图片大小调整为所在单元大小返回Sub 将A列最后数据行以上的所有B列图片大小调整为所在单元大小()Dim Pic As Picture, i&i = [A65536].End(xlUp).RowFor Each Pic In Sheet1.PicturesIf Not Application.Intersect(Pic.TopLeftCell, Range("B1:B" & i)) Is Nothing ThenPic.Top = Pic.TopLeftCell.TopPic.Left = Pic.TopLeftCell.LeftPic.Height = Pic.TopLeftCell.HeightPic.Width = Pic.TopLeftCell.WidthEnd IfNextEnd Sub▲返回光标所在行数返回Sub 返回光标所在行数()x = ActiveCell.RowRange("A1") = xEnd Sub▲在A1返回当前选中单元格数量返回Sub 在A1返回当前选中单元格数量()[A1] = Selection.CountEnd Sub▲返回当前工作簿中工作表数量返回Sub 返回当前工作簿中工作表数量()t = Application.Sheets.CountMsgBox tEnd Sub▲返回光标选择区域的行数和列数返回Sub 返回光标选择区域的行数和列数()x = Selection.Rows.County = Selection.Columns.CountRange("A1") = xRange("A2") = yEnd Sub▲工作表中包含数据的最大行数返回Sub 包含数据的最大行数()n = Cells.Find("*", , , , 1, 2).RowMsgBox nEnd Sub▲返回A列数据的最大行数返回Sub 返回A列数据的最大行数()n = Range("a65536").End(xlUp).RowRange("B1") = nEnd Sub▲将所选区域文本插入新建文本框返回Sub 将所选区域文本插入新建文本框()For Each rag In Selectionn = n & rag.Value & Chr(10)NextActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, ActiveCell.Left +ActiveCell.Width, ActiveCell.Top + ActiveCell.Height, 250#, 100).SelectSelection.Characters.Text = "问题:" & nWith Selection.Characters(Start:=1, Length:=3).Font.Name = "黑体".FontStyle = "常规".Size = 12End WithEnd Sub▲批量插入地址批注返回Sub 批量插入地址批注()On Error Resume NextDim r As RangeIf Selection.Cells.Count > 0 ThenFor Each r In Selectionment.Deleter.AddCommentment.Visible = Falsement.Text Text:="本单元格:" & r.Address & " of " & Selection.AddressNextEnd IfEnd Sub▲批量插入统一批注返回Sub 批量插入统一批注()Dim r As Range, msg As Stringmsg = InputBox("请输入欲批量插入的批注", "提示", "随便输点什么吧")If Selection.Cells.Count > 0 ThenFor Each r In Selectionr.AddCommentment.Visible = Falsement.Text Text:=msgNextEnd IfEnd Sub▲以A1单元内容批量插入批注返回Sub 以A1单元内容批量插入批注()Dim r As RangeIf Selection.Cells.Count > 0 ThenFor Each r In Selectionr.AddCommentment.Visible = Falsement.Text Text:=[a1].TextNextEnd IfEnd Sub▲不连续区域插入当前文件名和表名及地址返回Sub 批量插入当前文件名和表名及地址()For Each mycell In Selectionmycell.FormulaR1C1 = "[" + + "]" + +"!" + mycell.AddressNextEnd Sub▲不连续区域录入当前单元地址返回Sub 区域录入当前单元地址()For Each mycell In Selectionmycell.FormulaR1C1 = mycell.AddressNextEnd Sub▲连续区域录入当前单元地址返回Sub 连续区域录入当前单元地址()Selection = "=ADDRESS(ROW(),COLUMN(),4,1)"Selection.CopySelection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _:=False, Transpose:=FalseEnd Sub▲返回当前单元地址返回Sub 返回当前单元地址()d = ActiveCell.Address[A1] = dEnd Sub▲不连续区域录入当前日期返回Sub 区域录入当前日期()Selection.FormulaR1C1 = Format(Now(), "yyyy-m-d")End Sub▲不连续区域录入当前数字日期返回Sub 区域录入当前数字日期()Selection.FormulaR1C1 = Format(Now(), "yyyymmdd")End Sub▲不连续区域录入当前日期和时间返回Sub 区域录入当前日期和时间()Selection.FormulaR1C1 = Format(Now(), "yyyy-m-d h:mm:ss")End Sub▲不连续区域录入对勾返回Sub 批量录入对勾()Selection.FormulaR1C1 = "√"End Sub▲不连续区域录入当前文件名返回Sub 批量录入当前文件名()Selection.FormulaR1C1 = End Sub▲不连续区域添加文本返回Sub 批量添加文本()Dim s As RangeFor Each s In Selections = s & "文本内容"NextEnd Sub▲不连续区域插入文本返回Sub 批量插入文本()Dim s As RangeFor Each s In Selections = "文本内容" & sNextEnd Sub▲从指定位置向下同时录入多单元指定内容返回Sub 从指定位置向下同时录入多单元指定内容()Dim arrarr = Array("1", "2", "13", "25", "46", "12", "0", "20")[B2].Resize(8, 1) = Application.WorksheetFunction.Transpose(arr)End Sub▲按aa工作表A列的内容排列工作表标签顺序返回Sub 按aa工作表A列的内容排列工作表标签顺序()Dim I%, str1$I = 1Sheets("aa").SelectDo While Cells(I, 1).Value <> ""str1 = Trim(Cells(I, 1).Value)Sheets(str1).SelectSheets(str1).Move after:=Sheets(I)I = I + 1Sheets("aa").SelectLoopEnd Sub▲以A1单元文本作表名插入工作表返回Sub 以A1单元文本作表名插入工作表()Dim nm As Stringnm = [a1]Sheets.Add = nmEnd Sub▲删除全部未选定工作表返回Sub 删除全部未选定工作表()Dim sht As Worksheet, n As Integer, iFlag As BooleanDim ShtName() As Stringn = ActiveWindow.SelectedSheets.CountReDim ShtName(1 To n)n = 1For Each sht In ActiveWindow.SelectedSheetsShtName(n) = n = n + 1NextApplication.DisplayAlerts = FalseFor Each sht In SheetsiFlag = FalseFor i = 1 To n - 1If ShtName(i) = TheniFlag = TrueExit ForEnd IfNextIf Not iFlag Then sht.DeleteNextApplication.DisplayAlerts = TrueEnd Sub▲工作表标签排序返回Sub 工作表标签排序()Dim i As Long, j As Long, nums As Long, msg As Longmsg = MsgBox("工作表按升序排列请选 '是[Y]'. " & vbCrLf & vbCrLf & "工作表按降序排列请选 '否[N]'", vbYesNoCancel, "工作表排序")If msg = vbCancel Then Exit Subnums = Sheets.CountIf msg = vbYes Then 'Sort ascendingFor i = 1 To numsFor j = i To numsIf UCase(Sheets(j).Name) < UCase(Sheets(i).Name) ThenSheets(j).Move Before:=Sheets(i)End IfNext jNext iElse 'Sort descendingFor i = 1 To numsFor j = i To numsIf UCase(Sheets(j).Name) > UCase(Sheets(i).Name) ThenSheets(j).Move Before:=Sheets(i)End IfNext jNext iEnd IfEnd Sub▲定义指定工作表标签颜色返回Sub 定义指定工作表标签颜色()Sheets("Sheet1").Tab.ColorIndex = 46End Sub▲在目录表建立本工作簿中各表链接目录返回Sub 在目录表建立本工作簿中各表链接目录()Dim s%, Rng As RangeOn Error Resume NextSheets("目录").ActivateIf Err = 0 ThenSheets("目录").UsedRange.DeleteElseSheets.Add = "目录"End IfFor i = 1 To Sheets.CountIf Sheets(i).Name <> "目录" Thens = s + 1Set Rng = Sheets("目录").Cells(((s - 1) Mod 20) + 1, (s - 1) \ 20 + 1 + 1)Rng = Format(s, " 0") & ". " & Sheets(i).NameActiveSheet.Hyperlinks.Add Rng, "#" & Sheets(i).Name & "!A1",ScreenTip:=Sheets(i).NameEnd IfNextSheets("目录").Range("b:iv").EntireColumn.ColumnWidth = 20End Sub▲建立工作表文本目录返回Sub 建立工作表文本目录()Sheets.Add before:=Sheets(1)Sheets(1).Name = "目录"For i = 2 To Sheets.CountCells(i - 1, 1) = Sheets(i).Name'Sheets(1).Hyperlinks.Add Cells(i - 1, 1), "#" & Sheets(i).Name & "!A1" '添加超链接NextEnd Sub▲查另一文件的全部表名返回Sub 查另一文件的全部表名()On Error Resume NextDim i%Dim sh As WorksheetApplication.ScreenUpdating = FalseWorkbooks.Open Filename:=ThisWorkbook.Path & "\2.xls"Windows("1.xls").Activate '当前文件名称Sheets("Sheet1").Select '当前表名称i = 1 '将表名称返回到第1行For Each sh In Workbooks("2.xls").WorksheetsCells(i, 1) = '将表名称返回到第1列i = i + 1 '返回每个表名称向下移动1行Next shWindows("2.xls").Close '关闭对象文件Application.ScreenUpdating = TrueEnd Sub▲当前单元录入计算机名返回Sub 当前单元录入计算机名()Selection = Environ("COMPUTERNAME")'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲当前单元录入计算机用户名返回 Sub 当前单元录入计算机用户名()Selection = Environ("Username")'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲解除全部工作表保护返回Sub 解除全部工作表保护()Dim n As IntegerFor n = 1 To Sheets.CountSheets(n).UnprotectNext nEnd Sub▲为指定工作表加指定密码保护表返回Sub 为指定工作表加指定密码保护表()Sheet10.Protect Password:="123"End Sub▲在有密码的工作表执行代码返回Sub 在有密码的工作表执行代码()Sheets("1").Unprotect Password:=123 '假定表名为“1”,密码为“123” 打开工作表Range("C:C").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True '隐藏C列空值行Sheets("1").Protect Password:=123 '重新用密码保护工作表End Sub▲执行前需要验证密码的宏(控件按钮代码)返回Private Sub CommandButton1_Click()If InputBox("请输入密码:") <> "123" Then '密码是123MsgBox "密码错误,按确定退出!", 64, "提示"Exit SubEnd IfCells(1, 1) = 10End SubSub 执行前需要验证密码的宏()If InputBox("请输入您的使用权限:", "系统提示") = 123 Then重排窗口 '要执行的宏代码或宏名称ElseMsgBox "对不起,您没有使用该宏的权限,按确定键后退出!"End IfEnd Sub▲拷贝A1公式和格式到A2返回Sub 拷贝A1公式到A2()Workbooks("临时表").Sheets("表1").Range("A1").CopyWorkbooks("临时表").Sheets("表2").Range("A2").PasteSpecialEnd Sub▲复制单元数值返回Sub 复制数值()s = Workbooks("book1").Sheets("Sheet1").Range("A1:A2")Workbooks("book2").Sheets("Sheet1").Range("A1:A2") = sEnd Sub▲插入数值条件格式返回Sub 插入数值条件格式()Selection.FormatConditions.DeleteSelection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _Formula1:="70"Selection.FormatConditions(1).Interior.ColorIndex = 45Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _Formula1:="55"Selection.FormatConditions(2).Interior.ColorIndex = 39Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _Formula1:="60"Selection.FormatConditions(3).Interior.ColorIndex = 34End Sub▲插入透明批注返回Sub 插入透明批注()Selection.AddCommentment.Visible = FalseDim XS As WorksheetFor i = 1 To ments.Countments(i).Text "透明批注"ments(i).Shape.Fill.Visible = msoFalseNextEnd Sub▲添加文本返回Sub 添加文本()Selection = Selection + "×" '不可在数字后添加文本'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲光标定位到指定工作表A列最后数据行下一单元返回Sub 光标定位到指定工作表A列最后数据行下一单元()a = Sheets("数据库").[a65536].End(xlUp).RowSheets("数据库").SelectRange("A" & a + 1).SelectEnd Sub▲定位选定单元格式相同的全部单元格返回Sub 定位选定单元格式相同的全部单元格()Dim FirstCell As Range, FoundCell As RangeDim AllCells As RangeWith Application.FindFormat.Clear.NumberFormatLocal = Selection.NumberFormatLocal.HorizontalAlignment = Selection.HorizontalAlignment.VerticalAlignment = Selection.VerticalAlignment.WrapText = Selection.WrapText.Orientation = Selection.Orientation.AddIndent = Selection.AddIndent.IndentLevel = Selection.IndentLevel.ShrinkToFit = Selection.ShrinkToFit.MergeCells = Selection.MergeCells = .Font.FontStyle = Selection.Font.FontStyle.Font.Size = Selection.Font.Size.Font.Strikethrough = Selection.Font.Strikethrough.Font.Subscript = Selection.Font.Subscript.Font.Underline = Selection.Font.Underline.Font.ColorIndex = Selection.Font.ColorIndex.Interior.ColorIndex = Selection.Interior.ColorIndex.Interior.Pattern = Selection.Interior.Pattern.Locked = Selection.Locked.FormulaHidden = Selection.FormulaHiddenEnd WithSet FirstCell = edRange.Find(what:="", searchformat:=True)If FirstCell Is Nothing ThenExit SubEnd IfSet AllCells = FirstCellSet FoundCell = FirstCellDoSet FoundCell = edRange.Find(After:=FoundCell, what:="",searchformat:=True)If FoundCell Is Nothing Then Exit DoSet AllCells = Union(FoundCell, AllCells)If FoundCell.Address = FirstCell.Address Then Exit DoLoopAllCells.SelectEnd Sub▲按当前单元文本定位返回Sub 按当前单元文本定位()ABC = SelectionDim aa As RangeFor Each a In edRangeIf a Like ABC ThenIf aa Is Nothing ThenSet aa = a.CellsElseSet aa = Union(aa, a.Cells)End IfEnd IfNextaa.SelectEnd Sub▲按固定文本定位返回Sub 文本定位()Dim aa As RangeFor Each a In edRangeIf a Like "*合计*" ThenIf aa Is Nothing ThenSet aa = a.CellsElseSet aa = Union(aa, a.Cells)End IfEnd IfNextaa.SelectEnd Sub▲删除包含固定文本单元的行或列返回Sub 删除包含固定文本单元的行或列()DoCells.Find(what:="哈哈").ActivateSelection.EntireRow.Delete '删除行' Selection.EntireColumn.Delete '删除列Loop Until Cells.Find(what:="哈哈") Is NothingEnd Sub▲定位数据及区域以上的空值返回Sub 定位数据及区域以上的空值()Dim aa As RangeFor Each a In edRangeIf a Like 〈0 ThenIf aa Is Nothing ThenSet aa = a.CellsElseSet aa = Union(aa, a.Cells)End IfEnd IfNextaa.SelectEnd Sub▲右侧单元自动加5(工作表代码)返回Private Sub Worksheet_Change(ByVal Target As Range)Application.EnableEvents = FalseTarget.Offset(0, 1) = Target + 5Application.EnableEvents = TrueEnd Sub▲当前单元加2返回Sub 当前单元加2()Selection = Selection + 2'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲A列等于A列减B列返回Sub A列等于A列减B列()For i = 1 To 23Cells(i, 1) = Cells(i, 1) - Cells(i, 2)NextEnd Sub▲用于光标选定多区域跳转指定单元(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal T As Range)a = Array([b6:b7], [e6], [h6])For i = 0 To 2If Not Application.Intersect(T, a(i)) Is Nothing Then[a1].Select: Exit ForEnd IfNextEnd Sub▲将A1单元录入的数据累加到B1单元(工作表代码)返回Private Sub Worksheet_Change(ByVal Target As Range)Dim t As LongIf Target.Address = "$A$1" Thent = Sheet1.Range("$B$1").ValueSheet1.Range("$B$1").Value = t + Target.ValueEnd IfEnd Sub▲在指定颜色区域选择单元时添加/取消"√"(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Dim myrg As RangeFor Each myrg In TargetIf myrg.Interior.ColorIndex = 37 Then myrg = IIf(myrg <> "√", "√", "")NextEnd Sub▲在指定区域选择单元时添加/取消"√"(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Dim Rng As RangeIf Target.Count <= 15 ThenIf Not Application.Intersect(Target, Range("D6:D20")) Is Nothing ThenFor Each Rng In SelectionWith RngIf .Value = "" Then.Value = "√"Else.Value = ""End IfEnd WithNextEnd IfEnd IfEnd Sub▲双击指定单元,循环录入文本(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal T As Range, Cancel As Boolean)If T.Address <> "$A$1" Then Exit SubCancel = TrueT = IIf(T = "好", "中", IIf(T = "中", "差", "好"))End Sub双击指定单元,循环录入文本(工作表代码)Dim nums As BytePrivate Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) If Target.Address = "$A$1" Thennums = nums Mod 3 + 1Target = Mid("上中下", nums, 1)Target.Offset(1, 0).SelectEnd IfEnd Sub▲单元区域引用(工作表代码)返回Private Sub Worksheet_Activate()Sheet1.Range("A1:B3").Value = Sheet2.Range("A1:B3").ValueEnd Sub▲在指定区域选择单元时数值加1(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Not Application.Intersect([a1:e10], Target) Is Nothing ThenTarget = Val(Target) + 1End IfEnd Sub▲混合文本的编号返回Sub 混合文本的编号()Worksheets(1).Range("B2").Value = "北京" & (--(Mid(Worksheets(1).Range("B2"), 3,100)) + 1)End Sub▲指定区域单元双击数据累加(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)If Not Application.Intersect([A1:Y100], Target) Is Nothing Thenoldvalue = Val(Target.Value)inputvalue = InputBox("请输入数量,按ENTER键确认!", "数值累加器")Target.Value = oldvalue + inputvalueEnd IfEnd Sub▲选择单元区域触发事件(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Target.Address = "$A$1:$B$2" ThenMsgBox "你选择了$A$1:$B$2单元"End IfEnd Sub▲当修改指定单元内容时自动执行宏(工作表代码)返回Private Sub Worksheet_Change(ByVal Target As Range)If Not Application.Intersect(Target, [B3:B4]) Is Nothing Then重排窗口End IfEnd Sub▲被指定单元内容限制执行宏返回Sub 被指定单元限制执行宏()If Range("$A$1") = "关闭" Then Exit Sub窗口End Sub▲双击单元隐藏该行(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)Rows(Target.Row).Hidden = TrueEnd Sub▲高亮显示行(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Cells.Interior.ColorIndex = 2Rows("1:2").Interior.ColorIndex = 40 '保持1至2行的颜色推荐39,22,40,Rows(Target.Row).Interior.ColorIndex = 35 '高亮推荐颜色35,20,24,34,37,40,15End Sub▲高亮显示行和列(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Cells.Interior.ColorIndex = xlNoneRows(Target.Row).Interior.ColorIndex = 34Columns(Target.Column).Interior.ColorIndex = 34End Sub▲为指定工作表设置滚动范围(工作簿代码)返回Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target AsRange)Sheet1.ScrollArea = "A1:M30"End Sub▲在指定单元记录打印和预览次数(工作簿代码)返回Private Sub Workbook_BeforePrint(Cancel As Boolean)Range("A1") = 1 + Range("A1")End Sub▲自动数字金额转大写(工作表代码)返回Private Sub Worksheet_Change(ByVal M As Range)On Error Resume Nexty = Int(Round(100 * Abs(M)) / 100)j = Round(100 * Abs(M) + 0.00001) - y * 100f = (j / 10 - Int(j / 10)) * 10A = IIf(y < 1, "", Application.Text(y, "[DBNum2]") & "元")b = IIf(j > 9.5, Application.Text(Int(j / 10), "[DBNum2]") & "角", IIf(y < 1,"", IIf(f > 1, "零", "")))c = IIf(f < 1, "整", Application.Text(Round(f, 0), "[DBNum2]") & "分")M = IIf(Abs(M) < 0.005, "", IIf(M < 0, "负" & A & b & c, A & b & c))End Sub▲将全部工作表的A1单元作为单击按钮(工作簿代码)返回Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target AsRange)If Target.Address = "$A$1" ThenCall 宏名End IfEnd Sub▲闹钟——到指定时间执行宏(工作簿代码)返回Private Sub Workbook_Open()Application.OnTime ("11:45:00"), "提示1" '宏名字Application.OnTime ("12:00:00"), "提示2" '宏名字End Sub▲改变Excel界面标题的宏(工作簿代码)返回Private Sub Workbook_Open()Application.Caption = "春节快乐"End Sub▲在指定工作表的指定单元返回光标当前多选区地址(工作簿代码)返回Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target AsRange)Worksheets("表2").Range("A1") = Target.Address(0, 0)End Sub▲B列录入数据时在A列返回记录时间(工作表代码)返回Public Sub Worksheet_Change(ByVal Target As Range)If Target.Column = 2 ThenTarget.Offset(, -1) = NowEnd IfEnd Sub▲当指定区域修改时在其右侧的2个单元返回当前日期和时间(工作表代码)返回Public Sub Worksheet_Change(ByVal Target As Range)If Not Application.Intersect(Target, [A1:A1000]) Is Nothing ThenIf Target.Column = 1 ThenTarget.Offset(, 1) = DateTarget.Offset(, 2) = TimeEnd IfEnd IfEnd SubPublic Sub Worksheet_Change(ByVal Target As Range)If Not Application.Intersect(Target, [A1:A1000]) Is Nothing ThenIf Target.Column = 1 ThenTarget.Offset(, 1) = Format(Now(), "yyyy-mm-dd")Target.Offset(, 2) = Format(Now(), "h:mm:ss")End IfEnd IfEnd Sub▲指定单元显示光标位置内容(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal T As Range)Sheets(1).Range("A1") = SelectionEnd Sub▲每编辑一个单元保存文件返回Private Sub Worksheet_Change(ByVal Target As Range)ThisWorkbook.SaveEnd Sub▲指定允许编辑区域返回Sub 指定允许编辑区域()ActiveSheet.ScrollArea = "B8:G15"End Sub▲解除允许编辑区域限制返回Sub 解除允许编辑区域限制()ActiveSheet.ScrollArea = ""End Sub▲删除指定行返回Sub 删除指定行()Workbooks("临时表").Sheets("表2").Range("5:5").DeleteEnd Sub▲删除A列为指定内容的行返回Sub 删除A列为指定内容的行()Dim a, b As Integera = Sheet1.[a65536].End(xlUp).RowFor b = a To 2 Step -1If Cells(b, 1).Value = "删除" ThenRows(b).DeleteEnd IfNextEnd Sub▲删除A列非数字单元行返回Sub 删除A列非数字单元行()i = [a65536].End(xlUp).RowRange("A1:A" & i).SpecialCells(xlCellTypeConstants, 2).EntireRow.DeleteEnd Sub▲有条件删除当前行返回Sub 有条件删除当前行()If [A1] = 2 Or [B1] = "删除" ThenSelection.Delete Shift:=xlUpEnd IfEnd Sub▲选择下一行返回Sub 选择下一行()ActiveCell.Offset(1, 0).Rows("1:1").EntireRow.SelectEnd Sub▲选择第5行开始所有数据行返回Sub 选择第5行开始所有数据行A()Dim i%i = Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues,SearchDirection:=xlPrevious).EntireRow.RowRows("5:" & i).SelectEnd SubSub 选择第5行开始所有数据行B()Rows("5:" & Cells.Find("*", , , , 1, 2).Row).SelectEnd Sub▲选择光标或选区所在行返回Sub 选择光标或选区所在行()Selection.EntireRow.Select▲选择光标或选区所在列返回Sub 选择光标或选区所在列()Selection.EntireColumn.SelectEnd Sub▲光标定位到名称指定位置返回Sub 定位()Application.Goto Range(Evaluate("名称"))End Sub▲选择名称定义的数据区返回Sub 选择名称定义的数据区()[数据区].Select '插入名称要使用INDIRECT函数'Range("数据区").Select 或者'Sheet1.Range("数据区").Select 或者End Sub▲选择到指定列的最后行返回Sub 选择到指定列的最后行()Range("C4:G" & [G65536].End(xlUp).Row).SelectEnd Sub▲将Sheet1的A列的非空值写到Sheet2的A列返回Sub 将Sheet1的A列的非空值写到Sheet2的A列()Sheet1.Columns("A:A").SpecialCells(2, 23).SpecialCells(12).Copy Sheet2.[A1]End Sub▲将名称1的数据写到名称2返回Sub Macro2()Range("位置2") = Range("位置1").Value▲单元反选返回Sub 单元反选()Application.DisplayAlerts = FalseApplication.ScreenUpdating = FalseDim raddress As String, taddress As Stringraddress = Selection.Addresstaddress = edRange.AddressWith Sheets.Add.Range(taddress) = 0.Range(raddress) = "=0"raddress = .Range(taddress).SpecialCells(xlCellTypeConstants, 1).Address.DeleteEnd WithActiveSheet.Range(raddress).SelectApplication.ScreenUpdating = TrueEnd Sub▲调整选中对象中的文字返回Sub 调整选中对象中的文字()'文字居中、自动调整大小With Selection.HorizontalAlignment = xlCenter.VerticalAlignment = xlCenter.ReadingOrder = xlContext.Orientation = xlHorizontal.AutoSize = True.AddIndent = FalseEnd WithEnd Sub▲去除指定范围内的对象返回Sub 去除指定范围内的对象()。

Excel-259个常用宏

Excel-259个常用宏
序号
代码目录
链接 类别
1 打开全部隐藏工作表
点击
2 循环宏
点击
3 录制宏时调用“停止录制”工具栏
点击
4 高级筛选5列不重复数据至指定表
点击
5 双击单元执行宏(工作表代码)
点击
6 双击指定区域单元执行宏(工作表代码)
点击
7 进入单元执行宏(工作表代码)
点击
8 进入指定区域单元执行宏(工作表代码)
点击
9 在多个宏中依次循环执行一个(控件按钮代码)
点击
33 不连续区域录入当前日期
点击
34 不连续区域录入当前数字日期
点击
35 不连续区域录入当前日期和时间
点击
36 不连续区域录入对勾
点击
37 不连续区域录入当前文件名
点击
38 不连续区域添加文本
点击
39 不连续区域插入文本
点击
40 从指定位置向下同时录入多单元指定内容
点击
41 按aa工作表A列的内容排列工作表标签顺序
102 选择第5行开始所有数据行
103 选择光标或选区所在行
104 选择光标或选区所在列
105 光标定位到名称指定位置
106 选择名称定义的数据区
107 选择到指定列的最后行
108 将Sheet1的A列的非空值写到Sheet2的A列
109 将名称1的数据写到名称2
110 单元反选
111 调整选中对象中的文字
点击
52 为指定工作表加指定密码保护表
点击
53 在有密码的工作表执行代码
点击
54 执行前需要验证密码的宏(控件按钮代码)
点击
55 拷贝A1公式和格式到A2

_Exce宏大全(经典)

_Exce宏大全(经典)

奇偶页分别打印自动打印多工作表第一页查找A列文本循环插入分页符将A列最后数据行以上的所有B列图片大小调整为所在单元大小返回光标所在行数在A1返回当前选中单元格数量返回当前工作簿中工作表数量返回光标选择区域的行数和列数工作表中包含数据的最大行数返回A列数据的最大行数将所选区域文本插入新建文本框批量插入地址批注批量插入统一批注以A1单元内容批量插入批注不连续区域插入当前文件名和表名及地址不连续区域录入当前单元地址连续区域录入当前单元地址返回当前单元地址不连续区域录入当前日期不连续区域录入当前数字日期不连续区域录入当前日期和时间不连续区域录入对勾不连续区域录入当前文件名不连续区域添加文本不连续区域插入文本当前单元录入计算机用户名解除全部工作表保护为指定工作表加指定密码保护表在有密码的工作表执行代码执行前需要验证密码的宏(控件按钮代码)拷贝A1公式和格式到A2复制单元数值插入数值条件格式插入透明批注当前单元加2当指定区域修改时在其右侧的2个单元返回当前日期和时间(工作表代码)指定单元显示光标位置内容(工作表代码)每编辑一个单元保存文件指定允许编辑区域解除允许编辑区域限制删除指定行删除A列为指定内容的行删除A列非数字单元行有条件删除当前行选择下一行选择第5行开始所有数据行选择光标或选区所在行选择光标或选区所在列光标定位到名称指定位置选择名称定义的数据区选择到指定列的最后行将Sheet1的A列的非空值写到Sheet2的A列将名称1的数据写到名称2将全部工作表名称写到A列为当前选定的多单元插入指定名称删除全部名称以指定区域为表目录补充新表按A列数据批量修改表名称按A列数据批量创建新表(控件按钮代码)清除剪贴板批量清除软回车判断指定文件是否已经打开当前文件另存到指定目录将A列数据排序到D列将指定范围的数据排列到D列光标移动光标所在行上移一行加数据有效限制取消数据有效限制重排窗口按当前单元文本选择打开指定文件单元回车光标向右回车光标向下保护工作表时取消选定锁定单元打开文件时提示指定工作表是保护状态(ThisWorkbook)插入10行全选固定范围内小于0的单元全选选定范围内小于0的单元固定区域单元分类变色显示光标所在单元的批注的代码使单元内容保持不变的工作表代码有条件执行宏有条件执行不同的宏提示确定或取消执行宏提示开始和结束拷贝指定表不相邻多列数据到新位置选择2至4行在当前选区有条件替换数值为文本自动筛选全部显示指定列自动筛选第2列值为A的行取消自动筛选()全部显示指定表的自动筛选强行合并单元设置单元区域格式在A列产生不重复随机数将A列数据随机排列到F列取消选定区域的公式只保留值(假空转真空)处理导入的显示为科学计数法样式的身份证号返回指定单元的行高和列宽指定行高和列宽指定单元的行高和列宽与A1单元相同填公式建立当前工作表的副本为001表在第一个表前插入多工作表返回表中各非空单元区域地址(行搜索)返回第一个数值行号返回第1行最右边非空单元的列号返回连续数值单元的数量统计指定范围和内容的单元数量统计不同颜色的数字的和(自定义函数)返回非空单元数量返回A列非空单元数量返回圆周率π定义指定单元内容为页眉/页脚提示并全部清除当前选择区域全部清除当前选择区域清除指定区域数值对指定工作表执行取消隐藏》打印》隐藏工作表打开文件时执行指定宏(工作簿代码)关闭文件时执行指定宏(工作簿代码)弹出提示A1单元内容延时15秒执行重排窗口宏撤消工作表保护并取消密码重算指定表将第5行移到窗口的最上面对第一张工作表的指定区域进行排序显示指定工作表的打印预览用单元格A1的内容作为文件名另存当前工作簿[禁用/启用]保存和另存的代码在A和B列返回当前选区的名称和公式朗读朗读A列,按ESC键中止朗读固定语句,请按ESC键终止在M和N列的14行以下选择单元时显示调用日历控件(工作表代码)添加自定义序列弹出打印对话框把a列不重复值取到e列当前选区的行列数单元格录入1位字符就跳转(工作表代码)当指定日期(每月10日)打开文件执行宏提示并清空单元区域返回光标所在行号VBA返回公式结果按照当前行A列的图片名称插入图片到H列当前行下插入1行取消指定行或列的隐藏复制单元格所在行复制单元格所在列新建一个工作表新建一个工作簿选择多表为工作组在当前工作组各表中分别执行指定宏复制当前工作簿的报表到临时工作簿删除指定文件合并A1至C1的内容写到D15单元的批注中自动重算手动重算链接类别EH帖子地址net/dispbbs.asp?boardid登录点击点击宏管理点击其他点击筛选点击宏管理点击宏管理点击宏管理点击宏管理点击宏管理点击宏管理点击宏管理点击控件点击控件点击控件点击打印点击打印点击打印点击对象点击查找和引用点击查找和引用点击查找和引用点击查找和引用点击查找和引用点击查找和引用点击对象点击批注点击批注点击批注点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击工作表点击工作表点击工作表点击工作表点击工作表点击文件管理点击工作表点击工作表点击单元赋值点击单元赋值点击工作表点击密码点击密码点击密码点击单元赋值点击单元赋值点击格式点击批注点击单元赋值点击定位点击定位点击定位点击定位点击定位点击定位点击单元赋值点击单元赋值点击单元赋值点击定位点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击单元赋值点击事件点击事件点击事件点击事件点击其他点击其他点击定位点击打印点击单元赋值点击对象点击事件点击其他点击信息点击事件点击单元赋值点击单元赋值点击事件点击编辑点击编辑点击行列操作点击行列操作点击行列操作点击行列操作点击定位点击定位点击定位点击定位点击名称点击名称点击定位点击单元赋值点击名称点击定位点击格式点击对象点击数据点击单元赋值点击名称点击名称点击工作表点击工作表点击工作表点击其他点击其他点击事件点击文件管理点击文件管理点击文件管理点击文件管理点击文件管理点击文件管理点击文件管理点击文件管理点击文件管理点击文件管理点击文件管理点击单元赋值点击单元赋值点击定位点击行列操作点击数据点击数据点击窗口点击定位点击定位点击定位点击工作表点击文件管理点击行列操作点击工作表点击工作表点击工作表点击工作表点击工作表点击格式点击工作表点击工作表点击工作表点击工作表点击行列操作点击定位点击定位点击格式点击格式点击事件点击事件点击数据点击其他点击其他点击单元赋值点击事件点击事件点击事件点击事件点击单元赋值点击定位点击事件点击筛选点击筛选点击筛选点击筛选点击格式点击格式点击单元赋值点击事件点击事件点击行列操作点击单元赋值点击单元赋值点击单元赋值点击其他点击信息点击格式点击格式点击单元赋值点击工作表点击工作表点击单元赋值点击自定义函数点击信息点击超链接点击超链接点击超链接点击超链接点击查找和引用点击查找和引用点击查找和引用点击查找和引用点击查找和引用点击查找和引用点击查找和引用点击查找和引用点击查找和引用点击查找和引用点击其他点击打印点击单元赋值点击单元赋值点击单元赋值点击打印点击事件点击事件点击信息点击事件点击工作表点击工作表点击窗口点击单元赋值点击打印点击文件管理点击文件管理点击单元赋值点击语音点击语音点击对象点击其他点击打印点击打印点击事件点击事件点击工作表点击查找和引用点击查找和引用点击工作表点击事件点击事件点击其他点击其他点击图片点击工作表点击工作表点击其他点击其他点击工作表点击工作簿点击工作表点击事件点击工作簿点击工作簿点击批注点击其他点击其他。

实用Excel宏代码库

实用Excel宏代码库

Function 人民币大写转换(M)y = Int(Round(100 * Abs(M)) / 100)'NT函数将数字向下舍入到最接近的整数,即取不大于自变量的最大整数,例如:int[6.4]=6 int[-9.7]= -10.y取的为数字的整数部分。

(元)j = Round(100 * Abs(M) + 0.00001) - y * 100'j取的为小数部分(角)f = (j / 10 - Int(j / 10)) * 10'f为分,A = IIf(y < 1, "", Application.Text(y, "[DBNum2]") & "元")'IIf(expr, truepart, falsepart)b = IIf(j > 9.5, Application.Text(Int(j / 10), "[DBNum2]") & "角", IIf(y < 1, "", IIf(f > 1, "零", "")))c = IIf(f < 1, "整", Application.Text(Round(f, 0), "[DBNum2]") & "分")人民币大写转换= IIf(Abs(M) < 0.005, "", IIf(M < 0, "负" & A & b & c, A & b & c))End Function-------------------------------------------------------------------------------------为工作表瘦身(一)Sub CountShapes()Dim n As DoubleDim ws As WorksheetDim Content As StringFor Each ws In Worksheetsn = ws.Shapes.CountContent = Content & "工作表" & & " 有" & n & " 个对象" & vbCrLf NextMsgBox ContentEnd Sub(二)Sub DelAllShapes()Dim ws As WorksheetDim sp As ShapeDim n As DoubleDim Content As StringFor Each ws In WorksheetsFor Each sp In ws.ShapesIf sp.Width < 14.25 And sp.Height < 14.25 Thensp.Deleten = n + 1End IfNextContent = Content & "工作表" & & " 删除了" & n & " 个对象" & vbCrLfn = 0NextMsgBox ContentEnd Sub(三)Sub DelShapes()Dim sp As Shape, nFor Each sp In ActiveSheet.ShapesIf sp.Width < 14.25 And sp.Height < 14.25 Thensp.Deleten = n + 1End IfNext spMsgBox "共删除了" & n & "个对象"End Sub--------------------------------------------------------------------------------------- 获取超链接名称Function GetName(HyCell)Application.Volatile TrueGetName = HyCell.Hyperlinks(1).NameEnd Function获取超链接地址Function GetAddress(HyCell)Application.Volatile TrueWith HyCell.Hyperlinks(1)GetAddress = IIf(.Address = "", .SubAddress, .Address) End WithEnd Function-------------------------------------------------------------------------------------- 个性化启动画面Private Sub UserForm_Initialize()'设置窗体标题Me.Caption = "ExcelHome零售分析系统"'10秒钟后调用HideFormApplication.OnTime Now + TimeValue("00:00:10"), "HideForm"End SubPrivate Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) '禁止使用窗体关闭按钮退出If CloseMode = 0 Then Cancel = TrueEnd Sub-------------------------------------------------------------------------------------- Function 工资(zzy, a, b)y1 = 40544y2 = 40575y3 = 40603y4 = 40634y5 = 40664y6 = 40695y7 = 40725y8 = 40756y9 = 40787y10 = 40817y11 = 40848y12 = 40878Dim zzygz As SingleDim c As SingleIf zzy >= y1 And zzy < y2 Then '1月份x = 1zzygz = (y2 - zzy) / (y2 - y1) * bElseIf zzy >= y2 And zzy < y3 Then '2月份x = 2ElseIf zzy >= y3 And zzy < y4 Then '3月份x = 3ElseIf zzy >= y4 And zzy < y5 Then '4月份x = 4ElseIf zzy >= y5 And zzy < y6 Then '5月份x = 5ElseIf zzy >= y6 And zzy < y7 Then '6月份x = 6ElseIf zzy >= y7 And zzy < y8 Then '7月份x = 7ElseIf zzy >= y8 And zzy < y9 Then '8月份x = 8ElseIf zzy >= y9 And zzy < y10 Then '9月份x = 9ElseIf zzy >= y10 And zzy < y11 Then '10月份x = 10ElseIf zzy >= y11 And zzy < y12 Then '11月份x = 11ElseIf zzy >= y12 And zzy < y12 + 31 Then '12月份x = 12zzygz = (y12 + 31 - zzy) / 31 * bElseIf zzy <= y1 Then '2011年之前的x = 13ElseIf zzy >= y12 + 31 Then '2012年以后的,还没有转正x = 14Else '其他的如空白的x = 15End IfDim myrange1, myrange2 As RangeDim y As SingleDim i As IntegerReDim sz(12) As Singlei = 0Set myrange1 = aFor Each myrange2 In myrange1 '将各月数值赋值给数组sz()i = i + 1sz(i) = myrange2.ValueNext myrange2If x = 12 Or x = 13 Or x = 15 Then '如果为2011年12月份,或2010年之前,或空白,工资数据不变工资= 工资ElseIf x = 14 Then '如果为2012年,用文字显示提示工资= "转正日期为2012年,不用算年薪吧?"Else '如果为2011年1-11月份,取月基本月工资为转正后下一个月的工资数c = sz(x + 1)If zzy >= y1 And zzy < y2 Then '1月份ElseIf zzy >= y2 And zzy < y3 Then '2月份zzygz = (y3 - zzy) / (y3 - y2) * cElseIf zzy >= y3 And zzy < y4 Then '3月份zzygz = (y4 - zzy) / (y4 - y3) * cElseIf zzy >= y4 And zzy < y5 Then '4月份zzygz = (y5 - zzy) / (y5 - y4) * cElseIf zzy >= y5 And zzy < y6 Then '5月份zzygz = (y6 - zzy) / (y6 - y5) * cElseIf zzy >= y6 And zzy < y7 Then '6月份zzygz = (y7 - zzy) / (y7 - y6) * cElseIf zzy >= y7 And zzy < y8 Then '7月份zzygz = (y8 - zzy) / (y8 - y7) * cElseIf zzy >= y8 And zzy < y9 Then '8月份zzygz = (y9 - zzy) / (y9 - y8) * cElseIf zzy >= y9 And zzy < y10 Then '9月份zzygz = (y10 - zzy) / (y10 - y9) * cElseIf zzy >= y10 And zzy < y11 Then '10月份zzygz = (y11 - zzy) / (y11 - y10) * cElseIf zzy >= y11 And zzy < y12 Then '11月份zzygz = (y12 - zzy) / (y12 - y11) * cEnd IfEnd IfIf x = 14 Then '2012年的文字显示提示工资= 工资ElseIf x = 13 Or x = 15 Then '2010年以前和空白的,全年合计For i = 1 To 12工资= 工资+ sz(i)Next iElse '本年新进的从新进月份起开始加计For i = 1 To 12If i >= x Then工资= 工资+ sz(i)End IfNext iEnd IfIf x = 14 Or x = 13 Or x = 15 Then '年薪中扣除转正月工资+转正应享工资工资= 工资Else工资= 工资+ zzygz - sz(x)End IfEnd Function================================================ =====Sub 固定格式打印()Dim userin As Stringuserin = InputBox("请输入所销售的客户名称")If userin = "" ThenExit SubEnd IfDim example As WorksheetWorksheets("样表").Copy before:=Worksheets(1)Set example = Worksheets(1) = "example"Dim aim As WorksheetDim rownum As IntegerSet aim = Worksheets("sheet1")rownum = aim.Range("A2").CurrentRegion.Rows.Count example.Range("A1") = userin & "公司销售记录" example.Range("B3") = userinWith example.Range("a3:F4").Borders(xlDiagonalDown).LineStyle = xlNone.Borders(xlDiagonalUp).LineStyle = xlNone.Borders(xlEdgeLeft).LineStyle = xlNone.Borders(xlEdgeRight).LineStyle = xlNone.Borders(xlInsideVertical).LineStyle = xlNoneWith .Borders(xlEdgeTop).LineStyle = xlContinuous.ColorIndex = 1End WithWith .Borders(xlInsideHorizontal).LineStyle = xlContinuous.ColorIndex = 1End WithEnd WithDim index As Integerindex = 5For i = 2 To rownumIf aim.Cells(i, 2) = userin Thenaim.Rows(i).Copyexample.Rows(index).Insert shift:=xlshiftdwonindex = index + 1End IfNext iIf index = 5 ThenMsgBox "该表中不存在输入的内容"example.DeleteExit SubEnd IfDim total1, total2, total3, total4 As Singletotal1 = 0total2 = 0total3 = 0total4 = 0For i = 5 To index - 1total1 = total1 + CSng(example.Cells(i, 3))total2 = total2 + CSng(example.Cells(i, 4))total3 = total3 + CSng(example.Cells(i, 5))total4 = total4 + CSng(example.Cells(i, 6))Next iexample.Cells(index, 3) = total1example.Cells(index, 4) = total2example.Cells(index, 5) = total3example.Cells(index, 6) = total4With example.Range(Cells(3, 1), Cells(index, 6)).Columns.AutoFitEnd Withexample.PrintOutexample.DeleteMsgBox "打印成功"End Sub================================================ ======================Sub 打印工资条()Dim mysheet As WorksheetDim i, numrow As Integernumrow = 9Worksheets("工资表").Copy before:=Worksheets(1)Set mysheet = Worksheets(1) = "example"For i = 1 To numrowmysheet.Range("A2:I2").SelectSelection.Copymysheet.Rows(2 * i + 2).SelectSelection.Insert shift:=xlDownNext iFor i = 0 To numrow - 1With mysheet.Range(Cells(2 * i + 2, 1), Cells(2 * i + 4, 9)).Select Selection.Borders(xlDiagonalDown).LineStyle = xlNoneSelection.Borders(xlDiagonalUp).LineStyle = xlNoneWith Selection.Borders(xlEdgeTop).LineStyle = xlContinuous.Weight = xlMedium.ColorIndex = xlAutomaticEnd WithWith Selection.Borders(xlEdgeBottom).LineStyle = xlcontinous.Weight = xlMedium.ColorIndex = xlAutomaticEnd WithEnd WithNext iWith mysheet.PageSetup.Orientation = xlLandscape.PrintOutEnd WithWorksheets("example").DeleteMsgBox "打印成功"End Sub================================================ ===================会员登记Private Sub CommandButton1_Click()TextBox1.SetFocusIf TextBox1 <> "" ThenIf TextBox2 <> "" ThenActiveCell.Value = TextBox1.ValueActiveCell.Offset(0, 1).Value = TextBox2.ValueActiveCell.Offset(1, 0).SelectTextBox1.Value = ""TextBox2.Value = ""Exit SubElseMsgBox "请输入性别"TextBox2.SetFocusEnd IfElseMsgBox "请输入姓名"TextBox1.SetFocusEnd IfEnd SubPrivate Sub CommandButton2_Click()TextBox1 = ""TextBox2 = ""UserForm1.HideEnd SubSub 交互式输入()Worksheets(1).Range("A2").SelectUserForm1.ShowEnd Sub================================================ ====================Sub 统一设置数值上标()Dim myrange1, myrange2 As RangeDim numrow, numcol As Integernumrow = Range("A1").CurrentRegion.Rows.Countnumcol = Range("A1").CurrentRegion.Columns.CountSet myrange1 = Range(Cells(3, 1), Cells(numrow, numcol))For Each myrange2 In myrange1If myrange2 <> "" ThenDim i As IntegerDim slenslen = Len(myrange2.Value)For i = 1 To slenIf IsNumeric(Mid(myrange2, i, 1)) Thenmyrange2.Characters(i, 1).Font.Superscript = TrueEnd IfNext iEnd IfNext myrange2End Sub================================================ ======================Sub 添加边框()Dim myrange1 As RangeSet myrange1 = Worksheets(1).UsedRangemyrange1.SelectWith Selection.Borders(xlEdgeLeft).LineStyle = xlContinuous.Borders(xlEdgeRight).LineStyle = xlContinuous.Borders(xlEdgeTop).LineStyle = xlContinuous.Borders(xlEdgeBottom).LineStyle = xlContinuous.Borders(xlInsideVertical).LineStyle = xlContinuous.Borders(xlInsideHorizontal).LineStyle = xlContinuousEnd WithEnd SubPrivate Sub Worksheet_Change(ByVal target As Range)If Not needcheck(target) ThenExit SubEnd IfWith Selection.Borders(xlEdgeLeft).LineStyle = xlContinuous.Borders(xlEdgeRight).LineStyle = xlContinuous.Borders(xlEdgeTop).LineStyle = xlContinuous.Borders(xlEdgeBottom).LineStyle = xlContinuous.Borders(xlInsideVertical).LineStyle = xlContinuous.Borders(xlInsideHorizontal).LineStyle = xlContinuousEnd WithEnd SubPublic Function needcheck(target) As Booleanneedcheck = FalseSet myrange1 = Range("a:d")Dim myrange2 As RangeSet myrange2 = Intersect(target, myrange1)If Not myrange2 Is Nothing Thenmyrange2.Selectneedcheck = TrueEnd IfEnd Function================================================ ===========。

EXCEL常用的宏代码大全

EXCEL常用的宏代码大全

EXCEL常用的宏代码大全EXCEL 常用的宏代码大全 - [9-免费电脑学习资料]2008-04-22Tag:excel 常用宏宏代码大全本示例为设置密码窗口 (1)If Application.InputBox("请输入密码:") = 1234 Then[A1] = 1 '密码正确时执行Else: MsgBox "密码错误,即将退出!" '此行与第2行共同设置密码End If本示例为设置密码窗口 (1)X = MsgBox("是否真的要结帐?", vbYesNo)If X = vbYes ThenClose本示例为设置工作表密码ActiveSheet.Protect Password:=641112 ' 保护工作表并设置密码ActiveSheet.Unprotect Password:=641112 '撤消工作表保护并取消密码'本示例关闭除正在运行本示例的工作簿以外的其他所有工作簿,并保存其更改内容。

For Each w In WorkbooksIf <> Thenw.Close SaveChanges:=TrueEnd IfNext w'每次打开工作簿时,本示例都最大化 Microsoft Excel 窗口。

Application.WindowState = xlMaximized'本示例显示活动工作表的名称。

MsgBox "The name of the active sheet is " & '本示例保存当前活动工作簿的副本。

ActiveWorkbook.SaveCopyAs "C:\TEMP\XXXX.XLS"'下述过程激活工作簿中的第四张工作表。

Sheets(4).Activate'下述过程激活工作簿中的第1张工作表。

EXCEL个常用宏,非常实用

EXCEL个常用宏,非常实用

宏文件集▲打开全部隐藏工作表返回Sub 打开全部隐藏工作表()Dim i As IntegerFor i = 1 To Sheets.CountSheets(i).Visible = TrueNext iEnd Sub▲循环宏返回Sub 循环()AAA = Range("C2")Dim i As LongDim times As Longtimes = AAA'times代表循环次数,执行前把times赋值即可(不可小于1,不可大于2147483647)For i = 1 To timesCall 过滤一行If Range("完成标志") = "完成" Then Exit For '如果名为'完成标志'的命名单元的值等于'完成',则退出循环,如果一开始就等于'完成',则只执行一次循环就退出'If Sheets("传送参数").Range("A" & i).Text = "完成" Then Exit For '如果某列出现"完成"内容则退出循环Next iEnd Sub▲录制宏时调用“停止录制”工具栏返回Sub 录制宏时调用停止录制工具栏()mandBars("Stop Recording").Visible = TrueEnd Sub▲高级筛选5列不重复数据至指定表返回Sub 高级筛选5列不重复数据至Sheet2()Sheets("Sheet2").Range("A1:E65536") = "" '清除Sheet2的A:D列Range("A1:E65536").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheet2.Range( _"A1"), Unique:=TrueSheet2.Columns("A:E").Sort Key1:=Sheet2.Range("A2"), Order1:=xlAscending,Header:=xlGuess, _OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, SortMethod _:=xlPinYinEnd Sub▲双击单元执行宏(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)If Range("$A$1") = "关闭" Then Exit SubSelect Case Target.AddressCase "$A$4"Call 宏1Cancel = TrueCase "$B$4"Call 宏2Cancel = TrueCase "$C$4"Call 宏3Cancel = TrueCase "$E$4"Call 宏4Cancel = TrueEnd SelectEnd Sub▲双击指定区域单元执行宏(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)If Range("$A$1") = "关闭" Then Exit SubIf Not Application.Intersect(Target, Range("A4:A9", "C4:C9")) Is Nothing Then Call 打开隐藏表End Sub▲进入单元执行宏(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)'以单元格进入代替按钮对象调用宏If Range("$A$1") = "关闭" Then Exit SubSelect Case Target.AddressCase "$A$5" '单元地址(Target.Address),或命名单元名字()Call 宏1Case "$B$5"Call 宏2Case "$C$5"Call 宏3End SelectEnd Sub▲进入指定区域单元执行宏(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Range("$A$1") = "关闭" Then Exit SubIf Not Application.Intersect(Target, Range("A4:A9","C4:C9")) Is Nothing Then Call打开隐藏表End Sub▲在多个宏中依次循环执行一个(控件按钮代码)返回Private Sub CommandButton1_Click()Static RunMacro As IntegerSelect Case RunMacroCase 0宏1RunMacro = 1Case 1宏2RunMacro = 2Case 2宏3RunMacro = 0End SelectEnd Sub▲在两个宏中依次循环执行一个并相应修改按钮名称(控件按钮代码)返回Private Sub CommandButton1_Click()With CommandButton1If .Caption = "保护工作表" ThenCall 保护工作表.Caption = "取消工作表保护"Exit SubEnd IfIf .Caption = "取消工作表保护" ThenCall 取消工作表保护.Caption = "保护工作表"Exit SubEnd IfEnd WithEnd Sub▲在三个宏中依次循环执行一个并相应修改按钮名称(控件按钮代码)返回Option ExplicitPrivate Sub CommandButton1_Click()With CommandButton1If .Caption = "宏1" ThenCall 宏1.Caption = "宏2"Exit SubEnd IfIf .Caption = "宏2" ThenCall 宏2.Caption = "宏3"Exit SubEnd IfIf .Caption = "宏3" ThenCall 宏3.Caption = "宏1"Exit SubEnd IfEnd WithEnd Sub▲根据A1单元文本隐藏/显示按钮(控件按钮代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Range("A1") > 2 ThenCommandButton1.Visible = 1ElseCommandButton1.Visible = 0End IfEnd SubPrivate Sub CommandButton1_Click()重排窗口End Sub▲当前单元返回按钮名称(控件按钮代码)返回Private Sub CommandButton1_Click()ActiveCell = CommandButton1.CaptionEnd Sub▲当前单元内容返回到按钮名称(控件按钮代码)返回Private Sub CommandButton1_Click()CommandButton1.Caption = ActiveCellEnd Sub▲奇偶页分别打印返回Sub 奇偶页分别打印()Dim i%, Ps%Ps = ExecuteExcel4Macro("GET.DOCUMENT(50)") '总页数MsgBox "现在打印奇数页,按确定开始."For i = 1 To Ps Step 2ActiveSheet.PrintOut from:=i, To:=iNext iMsgBox "现在打印偶数页,按确定开始."For i = 2 To Ps Step 2ActiveSheet.PrintOut from:=i, To:=iNext iEnd Sub▲自动打印多工作表第一页返回Sub 自动打印多工作表第一页()Dim sh As IntegerDim xDim yDim syDim syzx = InputBox("请输入起始工作表名字:")sy = InputBox("请输入结束工作表名字:")y = Sheets(x).Indexsyz = Sheets(sy).IndexFor sh = y To syzSheets(sh).SelectSheets(sh).PrintOut from:=1, To:=1Next shEnd Sub▲查找A列文本循环插入分页符返回Sub 循环插入分页符()' Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容Dim i As LongDim times As Longtimes = Application.WorksheetFunction.CountIf(Sheet1.Range("a:a"), "分页")'times代表循环次数,执行前把times赋值即可(不可小于1,不可大于2147483647)For i = 1 To timesCall 插入分页符Next iEnd SubSub 插入分页符()Cells.Find(What:="分页", After:=ActiveCell, LookIn:=xlValues, LookAt:= _xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False) _.ActivateActiveWindow.SelectedSheets.HPageBreaks.Add Before:=ActiveCellEnd SubSub 取消原分页()Cells.SelectActiveSheet.ResetAllPageBreaksEnd Sub▲将A列最后数据行以上的所有B列图片大小调整为所在单元大小返回Sub 将A列最后数据行以上的所有B列图片大小调整为所在单元大小()Dim Pic As Picture, i&i = [A65536].End(xlUp).RowFor Each Pic In Sheet1.PicturesIf Not Application.Intersect(Pic.TopLeftCell, Range("B1:B" & i)) Is Nothing ThenPic.Top = Pic.TopLeftCell.TopPic.Left = Pic.TopLeftCell.LeftPic.Height = Pic.TopLeftCell.HeightPic.Width = Pic.TopLeftCell.WidthEnd IfNextEnd Sub▲返回光标所在行数返回Sub 返回光标所在行数()x = ActiveCell.RowRange("A1") = xEnd Sub▲在A1返回当前选中单元格数量返回Sub 在A1返回当前选中单元格数量()[A1] = Selection.CountEnd Sub▲返回当前工作簿中工作表数量返回Sub 返回当前工作簿中工作表数量()t = Application.Sheets.CountMsgBox tEnd Sub▲返回光标选择区域的行数和列数返回Sub 返回光标选择区域的行数和列数()x = Selection.Rows.County = Selection.Columns.CountRange("A1") = xRange("A2") = yEnd Sub▲工作表中包含数据的最大行数返回Sub 包含数据的最大行数()n = Cells.Find("*", , , , 1, 2).RowMsgBox nEnd Sub▲返回A列数据的最大行数返回Sub 返回A列数据的最大行数()n = Range("a65536").End(xlUp).RowRange("B1") = nEnd Sub▲将所选区域文本插入新建文本框返回Sub 将所选区域文本插入新建文本框()For Each rag In Selectionn = n & rag.Value & Chr(10)NextActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, ActiveCell.Left +ActiveCell.Width, ActiveCell.Top + ActiveCell.Height, 250#, 100).SelectSelection.Characters.Text = "问题:" & nWith Selection.Characters(Start:=1, Length:=3).Font.Name = "黑体".FontStyle = "常规".Size = 12End WithEnd Sub▲批量插入地址批注返回Sub 批量插入地址批注()On Error Resume NextDim r As RangeIf Selection.Cells.Count > 0 ThenFor Each r In Selectionment.Deleter.AddCommentment.Visible = Falsement.Text Text:="本单元格:" & r.Address & " of " & Selection.AddressNextEnd IfEnd Sub▲批量插入统一批注返回Sub 批量插入统一批注()Dim r As Range, msg As Stringmsg = InputBox("请输入欲批量插入的批注", "提示", "随便输点什么吧")If Selection.Cells.Count > 0 ThenFor Each r In Selectionr.AddCommentment.Visible = Falsement.Text Text:=msgNextEnd IfEnd Sub▲以A1单元内容批量插入批注返回Sub 以A1单元内容批量插入批注()Dim r As RangeIf Selection.Cells.Count > 0 ThenFor Each r In Selectionr.AddCommentment.Visible = Falsement.Text Text:=[a1].TextNextEnd IfEnd Sub▲不连续区域插入当前文件名和表名及地址返回Sub 批量插入当前文件名和表名及地址()For Each mycell In Selectionmycell.FormulaR1C1 = "[" + + "]" + +"!" + mycell.AddressNextEnd Sub▲不连续区域录入当前单元地址返回Sub 区域录入当前单元地址()For Each mycell In Selectionmycell.FormulaR1C1 = mycell.AddressNextEnd Sub▲连续区域录入当前单元地址返回Sub 连续区域录入当前单元地址()Selection = "=ADDRESS(ROW(),COLUMN(),4,1)"Selection.CopySelection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _:=False, Transpose:=FalseEnd Sub▲返回当前单元地址返回Sub 返回当前单元地址()d = ActiveCell.Address[A1] = dEnd Sub▲不连续区域录入当前日期返回Sub 区域录入当前日期()Selection.FormulaR1C1 = Format(Now(), "yyyy-m-d")End Sub▲不连续区域录入当前数字日期返回Sub 区域录入当前数字日期()Selection.FormulaR1C1 = Format(Now(), "yyyymmdd")End Sub▲不连续区域录入当前日期和时间返回Sub 区域录入当前日期和时间()Selection.FormulaR1C1 = Format(Now(), "yyyy-m-d h:mm:ss")End Sub▲不连续区域录入对勾返回Sub 批量录入对勾()Selection.FormulaR1C1 = "√"End Sub▲不连续区域录入当前文件名返回Sub 批量录入当前文件名()Selection.FormulaR1C1 = End Sub▲不连续区域添加文本返回Sub 批量添加文本()Dim s As RangeFor Each s In Selections = s & "文本内容"NextEnd Sub▲不连续区域插入文本返回Sub 批量插入文本()Dim s As RangeFor Each s In Selections = "文本内容" & sNextEnd Sub▲从指定位置向下同时录入多单元指定内容返回Sub 从指定位置向下同时录入多单元指定内容()Dim arrarr = Array("1", "2", "13", "25", "46", "12", "0", "20")[B2].Resize(8, 1) = Application.WorksheetFunction.Transpose(arr)End Sub▲按aa工作表A列的内容排列工作表标签顺序返回Sub 按aa工作表A列的内容排列工作表标签顺序()Dim I%, str1$I = 1Sheets("aa").SelectDo While Cells(I, 1).Value <> ""str1 = Trim(Cells(I, 1).Value)Sheets(str1).SelectSheets(str1).Move after:=Sheets(I)I = I + 1Sheets("aa").SelectLoopEnd Sub▲以A1单元文本作表名插入工作表返回Sub 以A1单元文本作表名插入工作表()Dim nm As Stringnm = [a1]Sheets.Add = nmEnd Sub▲删除全部未选定工作表返回Sub 删除全部未选定工作表()Dim sht As Worksheet, n As Integer, iFlag As BooleanDim ShtName() As Stringn = ActiveWindow.SelectedSheets.CountReDim ShtName(1 To n)n = 1For Each sht In ActiveWindow.SelectedSheetsShtName(n) = n = n + 1NextApplication.DisplayAlerts = FalseFor Each sht In SheetsiFlag = FalseFor i = 1 To n - 1If ShtName(i) = TheniFlag = TrueExit ForEnd IfNextIf Not iFlag Then sht.DeleteNextApplication.DisplayAlerts = TrueEnd Sub▲工作表标签排序返回Sub 工作表标签排序()Dim i As Long, j As Long, nums As Long, msg As Longmsg = MsgBox("工作表按升序排列请选 '是[Y]'. " & vbCrLf & vbCrLf & "工作表按降序排列请选 '否[N]'", vbYesNoCancel, "工作表排序")If msg = vbCancel Then Exit Subnums = Sheets.CountIf msg = vbYes Then 'Sort ascendingFor i = 1 To numsFor j = i To numsIf UCase(Sheets(j).Name) < UCase(Sheets(i).Name) ThenSheets(j).Move Before:=Sheets(i)End IfNext jNext iElse 'Sort descendingFor i = 1 To numsFor j = i To numsIf UCase(Sheets(j).Name) > UCase(Sheets(i).Name) ThenSheets(j).Move Before:=Sheets(i)End IfNext jNext iEnd IfEnd Sub▲定义指定工作表标签颜色返回Sub 定义指定工作表标签颜色()Sheets("Sheet1").Tab.ColorIndex = 46End Sub▲在目录表建立本工作簿中各表链接目录返回Sub 在目录表建立本工作簿中各表链接目录()Dim s%, Rng As RangeOn Error Resume NextSheets("目录").ActivateIf Err = 0 ThenSheets("目录").UsedRange.DeleteElseSheets.Add = "目录"End IfFor i = 1 To Sheets.CountIf Sheets(i).Name <> "目录" Thens = s + 1Set Rng = Sheets("目录").Cells(((s - 1) Mod 20) + 1, (s - 1) \ 20 + 1 + 1)Rng = Format(s, " 0") & ". " & Sheets(i).NameActiveSheet.Hyperlinks.Add Rng, "#" & Sheets(i).Name & "!A1",ScreenTip:=Sheets(i).NameEnd IfNextSheets("目录").Range("b:iv").EntireColumn.ColumnWidth = 20End Sub▲建立工作表文本目录返回Sub 建立工作表文本目录()Sheets.Add before:=Sheets(1)Sheets(1).Name = "目录"For i = 2 To Sheets.CountCells(i - 1, 1) = Sheets(i).Name'Sheets(1).Hyperlinks.Add Cells(i - 1, 1), "#" & Sheets(i).Name & "!A1" '添加超链接NextEnd Sub▲查另一文件的全部表名返回Sub 查另一文件的全部表名()On Error Resume NextDim i%Dim sh As WorksheetApplication.ScreenUpdating = FalseWorkbooks.Open Filename:=ThisWorkbook.Path & "\2.xls"Windows("1.xls").Activate '当前文件名称Sheets("Sheet1").Select '当前表名称i = 1 '将表名称返回到第1行For Each sh In Workbooks("2.xls").WorksheetsCells(i, 1) = '将表名称返回到第1列i = i + 1 '返回每个表名称向下移动1行Next shWindows("2.xls").Close '关闭对象文件Application.ScreenUpdating = TrueEnd Sub▲当前单元录入计算机名返回Sub 当前单元录入计算机名()Selection = Environ("COMPUTERNAME")'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲当前单元录入计算机用户名返回 Sub 当前单元录入计算机用户名()Selection = Environ("Username")'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲解除全部工作表保护返回Sub 解除全部工作表保护()Dim n As IntegerFor n = 1 To Sheets.CountSheets(n).UnprotectNext nEnd Sub▲为指定工作表加指定密码保护表返回Sub 为指定工作表加指定密码保护表()Sheet10.Protect Password:="123"End Sub▲在有密码的工作表执行代码返回Sub 在有密码的工作表执行代码()Sheets("1").Unprotect Password:=123 '假定表名为“1”,密码为“123” 打开工作表Range("C:C").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True '隐藏C列空值行Sheets("1").Protect Password:=123 '重新用密码保护工作表End Sub▲执行前需要验证密码的宏(控件按钮代码)返回Private Sub CommandButton1_Click()If InputBox("请输入密码:") <> "123" Then '密码是123MsgBox "密码错误,按确定退出!", 64, "提示"Exit SubEnd IfCells(1, 1) = 10End SubSub 执行前需要验证密码的宏()If InputBox("请输入您的使用权限:", "系统提示") = 123 Then重排窗口 '要执行的宏代码或宏名称ElseMsgBox "对不起,您没有使用该宏的权限,按确定键后退出!"End IfEnd Sub▲拷贝A1公式和格式到A2返回Sub 拷贝A1公式到A2()Workbooks("临时表").Sheets("表1").Range("A1").CopyWorkbooks("临时表").Sheets("表2").Range("A2").PasteSpecialEnd Sub▲复制单元数值返回Sub 复制数值()s = Workbooks("book1").Sheets("Sheet1").Range("A1:A2")Workbooks("book2").Sheets("Sheet1").Range("A1:A2") = sEnd Sub▲插入数值条件格式返回Sub 插入数值条件格式()Selection.FormatConditions.DeleteSelection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _Formula1:="70"Selection.FormatConditions(1).Interior.ColorIndex = 45Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _Formula1:="55"Selection.FormatConditions(2).Interior.ColorIndex = 39Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _Formula1:="60"Selection.FormatConditions(3).Interior.ColorIndex = 34End Sub▲插入透明批注返回Sub 插入透明批注()Selection.AddCommentment.Visible = FalseDim XS As WorksheetFor i = 1 To ments.Countments(i).Text "透明批注"ments(i).Shape.Fill.Visible = msoFalseNextEnd Sub▲添加文本返回Sub 添加文本()Selection = Selection + "×" '不可在数字后添加文本'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲光标定位到指定工作表A列最后数据行下一单元返回Sub 光标定位到指定工作表A列最后数据行下一单元()a = Sheets("数据库").[a65536].End(xlUp).RowSheets("数据库").SelectRange("A" & a + 1).SelectEnd Sub▲定位选定单元格式相同的全部单元格返回Sub 定位选定单元格式相同的全部单元格()Dim FirstCell As Range, FoundCell As RangeDim AllCells As RangeWith Application.FindFormat.Clear.NumberFormatLocal = Selection.NumberFormatLocal.HorizontalAlignment = Selection.HorizontalAlignment.VerticalAlignment = Selection.VerticalAlignment.WrapText = Selection.WrapText.Orientation = Selection.Orientation.AddIndent = Selection.AddIndent.IndentLevel = Selection.IndentLevel.ShrinkToFit = Selection.ShrinkToFit.MergeCells = Selection.MergeCells = .Font.FontStyle = Selection.Font.FontStyle.Font.Size = Selection.Font.Size.Font.Strikethrough = Selection.Font.Strikethrough.Font.Subscript = Selection.Font.Subscript.Font.Underline = Selection.Font.Underline.Font.ColorIndex = Selection.Font.ColorIndex.Interior.ColorIndex = Selection.Interior.ColorIndex.Interior.Pattern = Selection.Interior.Pattern.Locked = Selection.Locked.FormulaHidden = Selection.FormulaHiddenEnd WithSet FirstCell = edRange.Find(what:="", searchformat:=True)If FirstCell Is Nothing ThenExit SubEnd IfSet AllCells = FirstCellSet FoundCell = FirstCellDoSet FoundCell = edRange.Find(After:=FoundCell, what:="",searchformat:=True)If FoundCell Is Nothing Then Exit DoSet AllCells = Union(FoundCell, AllCells)If FoundCell.Address = FirstCell.Address Then Exit DoLoopAllCells.SelectEnd Sub▲按当前单元文本定位返回Sub 按当前单元文本定位()ABC = SelectionDim aa As RangeFor Each a In edRangeIf a Like ABC ThenIf aa Is Nothing ThenSet aa = a.CellsElseSet aa = Union(aa, a.Cells)End IfEnd IfNextaa.SelectEnd Sub▲按固定文本定位返回Sub 文本定位()Dim aa As RangeFor Each a In edRangeIf a Like "*合计*" ThenIf aa Is Nothing ThenSet aa = a.CellsElseSet aa = Union(aa, a.Cells)End IfEnd IfNextaa.SelectEnd Sub▲删除包含固定文本单元的行或列返回Sub 删除包含固定文本单元的行或列()DoCells.Find(what:="哈哈").ActivateSelection.EntireRow.Delete '删除行' Selection.EntireColumn.Delete '删除列Loop Until Cells.Find(what:="哈哈") Is NothingEnd Sub▲定位数据及区域以上的空值返回Sub 定位数据及区域以上的空值()Dim aa As RangeFor Each a In edRangeIf a Like 〈0 ThenIf aa Is Nothing ThenSet aa = a.CellsElseSet aa = Union(aa, a.Cells)End IfEnd IfNextaa.SelectEnd Sub▲右侧单元自动加5(工作表代码)返回Private Sub Worksheet_Change(ByVal Target As Range)Application.EnableEvents = FalseTarget.Offset(0, 1) = Target + 5Application.EnableEvents = TrueEnd Sub▲当前单元加2返回Sub 当前单元加2()Selection = Selection + 2'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲A列等于A列减B列返回Sub A列等于A列减B列()For i = 1 To 23Cells(i, 1) = Cells(i, 1) - Cells(i, 2)NextEnd Sub▲用于光标选定多区域跳转指定单元(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal T As Range)a = Array([b6:b7], [e6], [h6])For i = 0 To 2If Not Application.Intersect(T, a(i)) Is Nothing Then[a1].Select: Exit ForEnd IfNextEnd Sub▲将A1单元录入的数据累加到B1单元(工作表代码)返回Private Sub Worksheet_Change(ByVal Target As Range)Dim t As LongIf Target.Address = "$A$1" Thent = Sheet1.Range("$B$1").ValueSheet1.Range("$B$1").Value = t + Target.ValueEnd IfEnd Sub▲在指定颜色区域选择单元时添加/取消"√"(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Dim myrg As RangeFor Each myrg In TargetIf myrg.Interior.ColorIndex = 37 Then myrg = IIf(myrg <> "√", "√", "")NextEnd Sub▲在指定区域选择单元时添加/取消"√"(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Dim Rng As RangeIf Target.Count <= 15 ThenIf Not Application.Intersect(Target, Range("D6:D20")) Is Nothing ThenFor Each Rng In SelectionWith RngIf .Value = "" Then.Value = "√"Else.Value = ""End IfEnd WithNextEnd IfEnd IfEnd Sub▲双击指定单元,循环录入文本(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal T As Range, Cancel As Boolean)If T.Address <> "$A$1" Then Exit SubCancel = TrueT = IIf(T = "好", "中", IIf(T = "中", "差", "好"))End Sub双击指定单元,循环录入文本(工作表代码)Dim nums As BytePrivate Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) If Target.Address = "$A$1" Thennums = nums Mod 3 + 1Target = Mid("上中下", nums, 1)Target.Offset(1, 0).SelectEnd IfEnd Sub▲单元区域引用(工作表代码)返回Private Sub Worksheet_Activate()Sheet1.Range("A1:B3").Value = Sheet2.Range("A1:B3").ValueEnd Sub▲在指定区域选择单元时数值加1(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Not Application.Intersect([a1:e10], Target) Is Nothing ThenTarget = Val(Target) + 1End IfEnd Sub▲混合文本的编号返回Sub 混合文本的编号()Worksheets(1).Range("B2").Value = "北京" & (--(Mid(Worksheets(1).Range("B2"), 3,100)) + 1)End Sub▲指定区域单元双击数据累加(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)If Not Application.Intersect([A1:Y100], Target) Is Nothing Thenoldvalue = Val(Target.Value)inputvalue = InputBox("请输入数量,按ENTER键确认!", "数值累加器")Target.Value = oldvalue + inputvalueEnd IfEnd Sub▲选择单元区域触发事件(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Target.Address = "$A$1:$B$2" ThenMsgBox "你选择了$A$1:$B$2单元"End IfEnd Sub▲当修改指定单元内容时自动执行宏(工作表代码)返回Private Sub Worksheet_Change(ByVal Target As Range)If Not Application.Intersect(Target, [B3:B4]) Is Nothing Then重排窗口End IfEnd Sub▲被指定单元内容限制执行宏返回Sub 被指定单元限制执行宏()If Range("$A$1") = "关闭" Then Exit Sub窗口End Sub▲双击单元隐藏该行(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)Rows(Target.Row).Hidden = TrueEnd Sub▲高亮显示行(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Cells.Interior.ColorIndex = 2Rows("1:2").Interior.ColorIndex = 40 '保持1至2行的颜色推荐39,22,40,Rows(Target.Row).Interior.ColorIndex = 35 '高亮推荐颜色35,20,24,34,37,40,15End Sub▲高亮显示行和列(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Cells.Interior.ColorIndex = xlNoneRows(Target.Row).Interior.ColorIndex = 34Columns(Target.Column).Interior.ColorIndex = 34End Sub▲为指定工作表设置滚动范围(工作簿代码)返回Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target AsRange)Sheet1.ScrollArea = "A1:M30"End Sub▲在指定单元记录打印和预览次数(工作簿代码)返回Private Sub Workbook_BeforePrint(Cancel As Boolean)Range("A1") = 1 + Range("A1")End Sub▲自动数字金额转大写(工作表代码)返回Private Sub Worksheet_Change(ByVal M As Range)On Error Resume Nexty = Int(Round(100 * Abs(M)) / 100)j = Round(100 * Abs(M) + 0.00001) - y * 100f = (j / 10 - Int(j / 10)) * 10A = IIf(y < 1, "", Application.Text(y, "[DBNum2]") & "元")b = IIf(j > 9.5, Application.Text(Int(j / 10), "[DBNum2]") & "角", IIf(y < 1,"", IIf(f > 1, "零", "")))c = IIf(f < 1, "整", Application.Text(Round(f, 0), "[DBNum2]") & "分")M = IIf(Abs(M) < 0.005, "", IIf(M < 0, "负" & A & b & c, A & b & c))End Sub▲将全部工作表的A1单元作为单击按钮(工作簿代码)返回Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target AsRange)If Target.Address = "$A$1" ThenCall 宏名End IfEnd Sub▲闹钟——到指定时间执行宏(工作簿代码)返回Private Sub Workbook_Open()Application.OnTime ("11:45:00"), "提示1" '宏名字Application.OnTime ("12:00:00"), "提示2" '宏名字End Sub▲改变Excel界面标题的宏(工作簿代码)返回Private Sub Workbook_Open()Application.Caption = "春节快乐"End Sub▲在指定工作表的指定单元返回光标当前多选区地址(工作簿代码)返回Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target AsRange)Worksheets("表2").Range("A1") = Target.Address(0, 0)End Sub▲B列录入数据时在A列返回记录时间(工作表代码)返回Public Sub Worksheet_Change(ByVal Target As Range)If Target.Column = 2 ThenTarget.Offset(, -1) = NowEnd IfEnd Sub▲当指定区域修改时在其右侧的2个单元返回当前日期和时间(工作表代码)返回Public Sub Worksheet_Change(ByVal Target As Range)If Not Application.Intersect(Target, [A1:A1000]) Is Nothing ThenIf Target.Column = 1 ThenTarget.Offset(, 1) = DateTarget.Offset(, 2) = TimeEnd IfEnd IfEnd SubPublic Sub Worksheet_Change(ByVal Target As Range)If Not Application.Intersect(Target, [A1:A1000]) Is Nothing ThenIf Target.Column = 1 ThenTarget.Offset(, 1) = Format(Now(), "yyyy-mm-dd")Target.Offset(, 2) = Format(Now(), "h:mm:ss")End IfEnd IfEnd Sub▲指定单元显示光标位置内容(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal T As Range)Sheets(1).Range("A1") = SelectionEnd Sub▲每编辑一个单元保存文件返回Private Sub Worksheet_Change(ByVal Target As Range)ThisWorkbook.SaveEnd Sub▲指定允许编辑区域返回Sub 指定允许编辑区域()ActiveSheet.ScrollArea = "B8:G15"End Sub▲解除允许编辑区域限制返回Sub 解除允许编辑区域限制()ActiveSheet.ScrollArea = ""End Sub▲删除指定行返回Sub 删除指定行()Workbooks("临时表").Sheets("表2").Range("5:5").DeleteEnd Sub▲删除A列为指定内容的行返回Sub 删除A列为指定内容的行()Dim a, b As Integera = Sheet1.[a65536].End(xlUp).RowFor b = a To 2 Step -1If Cells(b, 1).Value = "删除" ThenRows(b).DeleteEnd IfNextEnd Sub▲删除A列非数字单元行返回Sub 删除A列非数字单元行()i = [a65536].End(xlUp).RowRange("A1:A" & i).SpecialCells(xlCellTypeConstants, 2).EntireRow.DeleteEnd Sub▲有条件删除当前行返回Sub 有条件删除当前行()If [A1] = 2 Or [B1] = "删除" ThenSelection.Delete Shift:=xlUpEnd IfEnd Sub▲选择下一行返回Sub 选择下一行()ActiveCell.Offset(1, 0).Rows("1:1").EntireRow.SelectEnd Sub▲选择第5行开始所有数据行返回Sub 选择第5行开始所有数据行A()Dim i%i = Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues,SearchDirection:=xlPrevious).EntireRow.RowRows("5:" & i).SelectEnd SubSub 选择第5行开始所有数据行B()Rows("5:" & Cells.Find("*", , , , 1, 2).Row).SelectEnd Sub▲选择光标或选区所在行返回Sub 选择光标或选区所在行()Selection.EntireRow.Select▲选择光标或选区所在列返回Sub 选择光标或选区所在列()Selection.EntireColumn.SelectEnd Sub▲光标定位到名称指定位置返回Sub 定位()Application.Goto Range(Evaluate("名称"))End Sub▲选择名称定义的数据区返回Sub 选择名称定义的数据区()[数据区].Select '插入名称要使用INDIRECT函数'Range("数据区").Select 或者'Sheet1.Range("数据区").Select 或者End Sub▲选择到指定列的最后行返回Sub 选择到指定列的最后行()Range("C4:G" & [G65536].End(xlUp).Row).SelectEnd Sub▲将Sheet1的A列的非空值写到Sheet2的A列返回Sub 将Sheet1的A列的非空值写到Sheet2的A列()Sheet1.Columns("A:A").SpecialCells(2, 23).SpecialCells(12).Copy Sheet2.[A1]End Sub▲将名称1的数据写到名称2返回Sub Macro2()Range("位置2") = Range("位置1").Value▲单元反选返回Sub 单元反选()Application.DisplayAlerts = FalseApplication.ScreenUpdating = FalseDim raddress As String, taddress As Stringraddress = Selection.Addresstaddress = edRange.AddressWith Sheets.Add.Range(taddress) = 0.Range(raddress) = "=0"raddress = .Range(taddress).SpecialCells(xlCellTypeConstants, 1).Address.DeleteEnd WithActiveSheet.Range(raddress).SelectApplication.ScreenUpdating = TrueEnd Sub▲调整选中对象中的文字返回Sub 调整选中对象中的文字()'文字居中、自动调整大小With Selection.HorizontalAlignment = xlCenter.VerticalAlignment = xlCenter.ReadingOrder = xlContext.Orientation = xlHorizontal.AutoSize = True.AddIndent = FalseEnd WithEnd Sub▲去除指定范围内的对象返回Sub 去除指定范围内的对象()。

excel_259个常用宏

excel_259个常用宏

宏文件集▲打开全部隐藏工作表返回Sub 打开全部隐藏工作表()Dim i As IntegerFor i = 1 To Sheets.CountSheets(i).Visible = TrueNext iEnd Sub▲循环宏返回Sub 循环()AAA = Range("C2")Dim i As LongDim times As Longtimes = AAA'times代表循环次数,执行前把times赋值即可(不可小于1,不可大于2147483647)For i = 1 To timesCall 过滤一行If Range("完成标志") = "完成" Then Exit For '如果名为'完成标志'的命名单元的值等于'完成',则退出循环,如果一开始就等于'完成 'If Sheets("传送参数").Range("A" & i).Text = "完成" Then Exit For '如果某列出现"完成"内容则退出循环Next iEnd Sub▲录制宏时调用“停止录制”工具栏返回Sub 录制宏时调用停止录制工具栏()mandBars("Stop Recording").Visible = TrueEnd Sub▲高级筛选5列不重复数据至指定表返回Sub 高级筛选5列不重复数据至Sheet2()Sheets("Sheet2").Range("A1:E65536") = "" '清除Sheet2的A:D列Range("A1:E65536").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheet2.Range( _"A1"), Unique:=TrueSheet2.Columns("A:E").Sort Key1:=Sheet2.Range("A2"), Order1:=xlAscending, Header:=xlGuess, _OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, SortMethod _:=xlPinYinEnd Sub▲双击单元执行宏(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)If Range("$A$1") = "关闭" Then Exit SubSelect Case Target.AddressCase "$A$4"Call 宏1Cancel = TrueCase "$B$4"Call 宏2Cancel = TrueCase "$C$4"Call 宏3Cancel = TrueCase "$E$4"Call 宏4Cancel = TrueEnd SelectEnd Sub▲双击指定区域单元执行宏(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)If Range("$A$1") = "关闭" Then Exit SubIf Not Application.Intersect(Target, Range("A4:A9", "C4:C9")) Is Nothing Then Call 打开隐藏表End Sub▲进入单元执行宏(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)'以单元格进入代替按钮对象调用宏If Range("$A$1") = "关闭" Then Exit SubSelect Case Target.AddressCase "$A$5" '单元地址(Target.Address),或命名单元名字()Call 宏1Case "$B$5"Call 宏2Case "$C$5"Call 宏3End SelectEnd Sub▲进入指定区域单元执行宏(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Range("$A$1") = "关闭" Then Exit SubIf Not Application.Intersect(Target, Range("A4:A9","C4:C9")) Is Nothing Then Call 打开隐藏表End Sub▲在多个宏中依次循环执行一个(控件按钮代码)返回Private Sub CommandButton1_Click()Static RunMacro As IntegerSelect Case RunMacroCase 0宏1RunMacro = 1Case 1宏2RunMacro = 2Case 2宏3RunMacro = 0End SelectEnd Sub▲在两个宏中依次循环执行一个并相应修改按钮名称(控件按钮代码)返回Private Sub CommandButton1_Click()With CommandButton1If .Caption = "保护工作表" ThenCall 保护工作表.Caption = "取消工作表保护"Exit SubEnd IfIf .Caption = "取消工作表保护" ThenCall 取消工作表保护.Caption = "保护工作表"Exit SubEnd IfEnd WithEnd Sub▲在三个宏中依次循环执行一个并相应修改按钮名称(控件按钮代码)返回Option ExplicitPrivate Sub CommandButton1_Click()With CommandButton1If .Caption = "宏1" ThenCall 宏1.Caption = "宏2"Exit SubEnd IfIf .Caption = "宏2" ThenCall 宏2.Caption = "宏3"Exit SubEnd IfIf .Caption = "宏3" ThenCall 宏3.Caption = "宏1"Exit SubEnd IfEnd WithEnd Sub▲根据A1单元文本隐藏/显示按钮(控件按钮代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Range("A1") > 2 ThenCommandButton1.Visible = 1ElseCommandButton1.Visible = 0End IfEnd SubPrivate Sub CommandButton1_Click()重排窗口End Sub▲当前单元返回按钮名称(控件按钮代码)返回Private Sub CommandButton1_Click()ActiveCell = CommandButton1.CaptionEnd Sub▲当前单元内容返回到按钮名称(控件按钮代码)返回Private Sub CommandButton1_Click()CommandButton1.Caption = ActiveCellEnd Sub▲奇偶页分别打印返回Sub 奇偶页分别打印()Dim i%, Ps%Ps = ExecuteExcel4Macro("GET.DOCUMENT(50)") '总页数MsgBox "现在打印奇数页,按确定开始."For i = 1 To Ps Step 2ActiveSheet.PrintOut from:=i, To:=iNext iMsgBox "现在打印偶数页,按确定开始."For i = 2 To Ps Step 2ActiveSheet.PrintOut from:=i, To:=iNext iEnd Sub▲自动打印多工作表第一页返回Sub 自动打印多工作表第一页()Dim sh As IntegerDim xDim yDim syDim syzx = InputBox("请输入起始工作表名字:")sy = InputBox("请输入结束工作表名字:")y = Sheets(x).Indexsyz = Sheets(sy).IndexFor sh = y To syzSheets(sh).SelectSheets(sh).PrintOut from:=1, To:=1Next shEnd Sub▲查找A列文本循环插入分页符返回Sub 循环插入分页符()' Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容Dim i As LongDim times As Longtimes = Application.WorksheetFunction.CountIf(Sheet1.Range("a:a"), "分页")'times代表循环次数,执行前把times赋值即可(不可小于1,不可大于2147483647)For i = 1 To timesCall 插入分页符Next iEnd SubSub 插入分页符()Cells.Find(What:="分页", After:=ActiveCell, LookIn:=xlValues, LookAt:= _xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False) _.ActivateActiveWindow.SelectedSheets.HPageBreaks.Add Before:=ActiveCellEnd SubSub 取消原分页()Cells.SelectActiveSheet.ResetAllPageBreaksEnd Sub▲将A列最后数据行以上的所有B列图片大小调整为所在单元大小返回Sub 将A列最后数据行以上的所有B列图片大小调整为所在单元大小()Dim Pic As Picture, i&i = [A65536].End(xlUp).RowFor Each Pic In Sheet1.PicturesIf Not Application.Intersect(Pic.TopLeftCell, Range("B1:B" & i)) Is Nothing ThenPic.Top = Pic.TopLeftCell.TopPic.Left = Pic.TopLeftCell.LeftPic.Height = Pic.TopLeftCell.HeightPic.Width = Pic.TopLeftCell.WidthEnd IfNextEnd Sub▲返回光标所在行数返回Sub 返回光标所在行数()x = ActiveCell.RowRange("A1") = xEnd Sub▲在A1返回当前选中单元格数量返回Sub 在A1返回当前选中单元格数量()[A1] = Selection.CountEnd Sub▲返回当前工作簿中工作表数量返回Sub 返回当前工作簿中工作表数量()t = Application.Sheets.CountMsgBox tEnd Sub▲返回光标选择区域的行数和列数返回Sub 返回光标选择区域的行数和列数()x = Selection.Rows.County = Selection.Columns.CountRange("A1") = xRange("A2") = yEnd Sub▲工作表中包含数据的最大行数返回Sub 包含数据的最大行数()n = Cells.Find("*", , , , 1, 2).RowMsgBox nEnd Sub▲返回A列数据的最大行数返回Sub 返回A列数据的最大行数()n = Range("a65536").End(xlUp).RowRange("B1") = n▲将所选区域文本插入新建文本框返回Sub 将所选区域文本插入新建文本框()For Each rag In Selectionn = n & rag.Value & Chr(10)NextActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, ActiveCell.Left + ActiveCell.Width, ActiveCell.Top + Active Selection.Characters.Text = "问题:" & nWith Selection.Characters(Start:=1, Length:=3).Font.Name = "黑体".FontStyle = "常规".Size = 12End WithEnd Sub▲批量插入地址批注返回Sub 批量插入地址批注()On Error Resume NextDim r As RangeIf Selection.Cells.Count > 0 ThenFor Each r In Selectionment.Deleter.AddCommentment.Visible = Falsement.Text Text:="本单元格:" & r.Address & " of " & Selection.AddressNextEnd IfEnd Sub▲批量插入统一批注返回Sub 批量插入统一批注()Dim r As Range, msg As Stringmsg = InputBox("请输入欲批量插入的批注", "提示", "随便输点什么吧")If Selection.Cells.Count > 0 ThenFor Each r In Selectionr.AddCommentment.Visible = Falsement.Text Text:=msgNextEnd IfEnd Sub▲以A1单元内容批量插入批注返回Sub 以A1单元内容批量插入批注()Dim r As RangeIf Selection.Cells.Count > 0 ThenFor Each r In Selectionr.AddCommentment.Visible = Falsement.Text Text:=[a1].TextNextEnd IfEnd Sub▲不连续区域插入当前文件名和表名及地址返回Sub 批量插入当前文件名和表名及地址()For Each mycell In Selectionmycell.FormulaR1C1 = "[" + + "]" + + "!" + mycell.AddressNextEnd Sub▲不连续区域录入当前单元地址返回Sub 区域录入当前单元地址()For Each mycell In Selectionmycell.FormulaR1C1 = mycell.AddressNext▲连续区域录入当前单元地址返回Sub 连续区域录入当前单元地址()Selection = "=ADDRESS(ROW(),COLUMN(),4,1)"Selection.CopySelection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _:=False, Transpose:=FalseEnd Sub▲返回当前单元地址返回Sub 返回当前单元地址()d = ActiveCell.Address[A1] = dEnd Sub▲不连续区域录入当前日期返回Sub 区域录入当前日期()Selection.FormulaR1C1 = Format(Now(), "yyyy-m-d")End Sub▲不连续区域录入当前数字日期返回Sub 区域录入当前数字日期()Selection.FormulaR1C1 = Format(Now(), "yyyymmdd")End Sub▲不连续区域录入当前日期和时间返回Sub 区域录入当前日期和时间()Selection.FormulaR1C1 = Format(Now(), "yyyy-m-d h:mm:ss")End Sub▲不连续区域录入对勾返回Sub 批量录入对勾()Selection.FormulaR1C1 = "√"End Sub▲不连续区域录入当前文件名返回Sub 批量录入当前文件名()Selection.FormulaR1C1 = End Sub▲不连续区域添加文本返回Sub 批量添加文本()Dim s As RangeFor Each s In Selections = s & "文本内容"NextEnd Sub▲不连续区域插入文本返回Sub 批量插入文本()Dim s As RangeFor Each s In Selections = "文本内容" & sNextEnd Sub▲从指定位置向下同时录入多单元指定内容返回Sub 从指定位置向下同时录入多单元指定内容()Dim arrarr = Array("1", "2", "13", "25", "46", "12", "0", "20")[B2].Resize(8, 1) = Application.WorksheetFunction.Transpose(arr)End Sub▲按aa工作表A列的内容排列工作表标签顺序返回Sub 按aa工作表A列的内容排列工作表标签顺序()Dim I%, str1$I = 1Sheets("aa").SelectDo While Cells(I, 1).Value <> ""str1 = Trim(Cells(I, 1).Value)Sheets(str1).SelectSheets(str1).Move after:=Sheets(I)I = I + 1Sheets("aa").SelectLoopEnd Sub▲以A1单元文本作表名插入工作表返回Sub 以A1单元文本作表名插入工作表()Dim nm As Stringnm = [a1]Sheets.Add = nmEnd Sub▲删除全部未选定工作表返回Sub 删除全部未选定工作表()Dim sht As Worksheet, n As Integer, iFlag As BooleanDim ShtName() As Stringn = ActiveWindow.SelectedSheets.CountReDim ShtName(1 To n)n = 1For Each sht In ActiveWindow.SelectedSheetsShtName(n) = n = n + 1NextApplication.DisplayAlerts = FalseFor Each sht In SheetsiFlag = FalseFor i = 1 To n - 1If ShtName(i) = TheniFlag = TrueExit ForEnd IfNextIf Not iFlag Then sht.DeleteNextApplication.DisplayAlerts = TrueEnd Sub▲工作表标签排序返回Sub 工作表标签排序()Dim i As Long, j As Long, nums As Long, msg As Longmsg = MsgBox("工作表按升序排列请选 '是[Y]'. " & vbCrLf & vbCrLf & "工作表按降序排列请选 '否[N]'", vbYesNoCancel, "工作表排序If msg = vbCancel Then Exit Subnums = Sheets.CountIf msg = vbYes Then 'Sort ascendingFor i = 1 To numsFor j = i To numsIf UCase(Sheets(j).Name) < UCase(Sheets(i).Name) ThenSheets(j).Move Before:=Sheets(i)End IfNext jNext iElse 'Sort descendingFor i = 1 To numsFor j = i To numsIf UCase(Sheets(j).Name) > UCase(Sheets(i).Name) ThenSheets(j).Move Before:=Sheets(i)End IfNext jNext iEnd IfEnd Sub▲定义指定工作表标签颜色返回Sub 定义指定工作表标签颜色()Sheets("Sheet1").Tab.ColorIndex = 46End Sub▲在目录表建立本工作簿中各表链接目录返回Sub 在目录表建立本工作簿中各表链接目录()Dim s%, Rng As RangeOn Error Resume NextSheets("目录").ActivateIf Err = 0 ThenSheets("目录").UsedRange.DeleteElseSheets.Add = "目录"End IfFor i = 1 To Sheets.CountIf Sheets(i).Name <> "目录" Thens = s + 1Set Rng = Sheets("目录").Cells(((s - 1) Mod 20) + 1, (s - 1) \ 20 + 1 + 1)Rng = Format(s, " 0") & ". " & Sheets(i).NameActiveSheet.Hyperlinks.Add Rng, "#" & Sheets(i).Name & "!A1", ScreenTip:=Sheets(i).NameEnd IfNextSheets("目录").Range("b:iv").EntireColumn.ColumnWidth = 20End Sub▲建立工作表文本目录返回Sub 建立工作表文本目录()Sheets.Add before:=Sheets(1)Sheets(1).Name = "目录"For i = 2 To Sheets.CountCells(i - 1, 1) = Sheets(i).Name'Sheets(1).Hyperlinks.Add Cells(i - 1, 1), "#" & Sheets(i).Name & "!A1" '添加超链接NextEnd Sub▲查另一文件的全部表名返回Sub 查另一文件的全部表名()On Error Resume NextDim i%Dim sh As WorksheetApplication.ScreenUpdating = FalseWorkbooks.Open Filename:=ThisWorkbook.Path & "\2.xls"Windows("1.xls").Activate '当前文件名称Sheets("Sheet1").Select '当前表名称i = 1 '将表名称返回到第1行For Each sh In Workbooks("2.xls").WorksheetsCells(i, 1) = '将表名称返回到第1列i = i + 1 '返回每个表名称向下移动1行Next shWindows("2.xls").Close '关闭对象文件Application.ScreenUpdating = TrueEnd Sub▲当前单元录入计算机名返回Sub 当前单元录入计算机名()Selection = Environ("COMPUTERNAME")'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲当前单元录入计算机用户名返回 Sub 当前单元录入计算机用户名()Selection = Environ("Username")'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲解除全部工作表保护返回Sub 解除全部工作表保护()Dim n As IntegerFor n = 1 To Sheets.CountSheets(n).UnprotectNext nEnd Sub▲为指定工作表加指定密码保护表返回Sub 为指定工作表加指定密码保护表()Sheet10.Protect Password:="123"End Sub▲在有密码的工作表执行代码返回Sub 在有密码的工作表执行代码()Sheets("1").Unprotect Password:=123 '假定表名为“1”,密码为“123” 打开工作表Range("C:C").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True '隐藏C列空值行Sheets("1").Protect Password:=123 '重新用密码保护工作表End Sub▲执行前需要验证密码的宏(控件按钮代码)返回Private Sub CommandButton1_Click()If InputBox("请输入密码:") <> "123" Then '密码是123MsgBox "密码错误,按确定退出!", 64, "提示"Exit SubEnd IfCells(1, 1) = 10End SubSub 执行前需要验证密码的宏()If InputBox("请输入您的使用权限:", "系统提示") = 123 Then重排窗口 '要执行的宏代码或宏名称ElseMsgBox "对不起,您没有使用该宏的权限,按确定键后退出!"End IfEnd Sub▲拷贝A1公式和格式到A2返回Sub 拷贝A1公式到A2()Workbooks("临时表").Sheets("表1").Range("A1").CopyWorkbooks("临时表").Sheets("表2").Range("A2").PasteSpecialEnd Sub▲复制单元数值返回Sub 复制数值()s = Workbooks("book1").Sheets("Sheet1").Range("A1:A2")Workbooks("book2").Sheets("Sheet1").Range("A1:A2") = sEnd Sub▲插入数值条件格式返回Sub 插入数值条件格式()Selection.FormatConditions.DeleteSelection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _Formula1:="70"Selection.FormatConditions(1).Interior.ColorIndex = 45Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _Formula1:="55"Selection.FormatConditions(2).Interior.ColorIndex = 39Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _Formula1:="60"Selection.FormatConditions(3).Interior.ColorIndex = 34End Sub▲插入透明批注返回Sub 插入透明批注()Selection.AddCommentment.Visible = FalseDim XS As WorksheetFor i = 1 To ments.Countments(i).Text "透明批注"ments(i).Shape.Fill.Visible = msoFalseNextEnd Sub▲添加文本返回Sub 添加文本()Selection = Selection + "×" '不可在数字后添加文本'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲光标定位到指定工作表A列最后数据行下一单元返回Sub 光标定位到指定工作表A列最后数据行下一单元()a = Sheets("数据库").[a65536].End(xlUp).RowSheets("数据库").SelectRange("A" & a + 1).SelectEnd Sub▲定位选定单元格式相同的全部单元格返回Sub 定位选定单元格式相同的全部单元格()Dim FirstCell As Range, FoundCell As RangeDim AllCells As RangeWith Application.FindFormat.Clear.NumberFormatLocal = Selection.NumberFormatLocal.HorizontalAlignment = Selection.HorizontalAlignment.VerticalAlignment = Selection.VerticalAlignment.WrapText = Selection.WrapText.Orientation = Selection.Orientation.AddIndent = Selection.AddIndent.IndentLevel = Selection.IndentLevel.ShrinkToFit = Selection.ShrinkToFit.MergeCells = Selection.MergeCells = .Font.FontStyle = Selection.Font.FontStyle.Font.Size = Selection.Font.Size.Font.Strikethrough = Selection.Font.Strikethrough.Font.Subscript = Selection.Font.Subscript.Font.Underline = Selection.Font.Underline.Font.ColorIndex = Selection.Font.ColorIndex.Interior.ColorIndex = Selection.Interior.ColorIndex.Interior.Pattern = Selection.Interior.Pattern.Locked = Selection.Locked.FormulaHidden = Selection.FormulaHiddenEnd WithSet FirstCell = edRange.Find(what:="", searchformat:=True)If FirstCell Is Nothing ThenExit SubEnd IfSet AllCells = FirstCellSet FoundCell = FirstCellDoSet FoundCell = edRange.Find(After:=FoundCell, what:="", searchformat:=True)If FoundCell Is Nothing Then Exit DoSet AllCells = Union(FoundCell, AllCells)If FoundCell.Address = FirstCell.Address Then Exit DoLoopAllCells.SelectEnd Sub▲按当前单元文本定位返回Sub 按当前单元文本定位()ABC = SelectionDim aa As RangeFor Each a In edRangeIf a Like ABC ThenIf aa Is Nothing ThenSet aa = a.CellsElseSet aa = Union(aa, a.Cells)End IfEnd IfNextaa.SelectEnd Sub▲按固定文本定位返回Sub 文本定位()Dim aa As RangeFor Each a In edRangeIf a Like "*合计*" ThenIf aa Is Nothing ThenSet aa = a.CellsElseSet aa = Union(aa, a.Cells)End IfEnd IfNextaa.SelectEnd Sub▲删除包含固定文本单元的行或列返回Sub 删除包含固定文本单元的行或列()DoCells.Find(what:="哈哈").ActivateSelection.EntireRow.Delete '删除行' Selection.EntireColumn.Delete '删除列Loop Until Cells.Find(what:="哈哈") Is NothingEnd Sub▲定位数据及区域以上的空值返回Sub 定位数据及区域以上的空值()Dim aa As RangeFor Each a In edRangeIf a Like 〈0 ThenIf aa Is Nothing ThenSet aa = a.CellsElseSet aa = Union(aa, a.Cells)End Ifaa.SelectEnd Sub▲右侧单元自动加5(工作表代码)返回Private Sub Worksheet_Change(ByVal Target As Range)Application.EnableEvents = FalseTarget.Offset(0, 1) = Target + 5Application.EnableEvents = TrueEnd Sub▲当前单元加2返回Sub 当前单元加2()Selection = Selection + 2'Selection = Workbooks("临时表").Sheets("表2").Range("A1") 调用指定地址内容End Sub▲A列等于A列减B列返回Sub A列等于A列减B列()For i = 1 To 23Cells(i, 1) = Cells(i, 1) - Cells(i, 2)NextEnd Sub▲用于光标选定多区域跳转指定单元(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal T As Range)a = Array([b6:b7], [e6], [h6])For i = 0 To 2If Not Application.Intersect(T, a(i)) Is Nothing Then[a1].Select: Exit ForEnd IfNextEnd Sub▲将A1单元录入的数据累加到B1单元(工作表代码)返回Private Sub Worksheet_Change(ByVal Target As Range)Dim t As LongIf Target.Address = "$A$1" Thent = Sheet1.Range("$B$1").ValueSheet1.Range("$B$1").Value = t + Target.ValueEnd IfEnd Sub▲在指定颜色区域选择单元时添加/取消"√"(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Dim myrg As RangeFor Each myrg In TargetIf myrg.Interior.ColorIndex = 37 Then myrg = IIf(myrg <> "√", "√", "")NextEnd Sub▲在指定区域选择单元时添加/取消"√"(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Dim Rng As RangeIf Target.Count <= 15 ThenIf Not Application.Intersect(Target, Range("D6:D20")) Is Nothing ThenFor Each Rng In SelectionWith RngIf .Value = "" Then.Value = "√"Else.Value = ""End IfEnd WithNextEnd If▲双击指定单元,循环录入文本(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal T As Range, Cancel As Boolean)If T.Address <> "$A$1" Then Exit SubCancel = TrueT = IIf(T = "好", "中", IIf(T = "中", "差", "好"))End Sub双击指定单元,循环录入文本(工作表代码)Dim nums As BytePrivate Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)If Target.Address = "$A$1" Thennums = nums Mod 3 + 1Target = Mid("上中下", nums, 1)Target.Offset(1, 0).SelectEnd IfEnd Sub▲单元区域引用(工作表代码)返回Private Sub Worksheet_Activate()Sheet1.Range("A1:B3").Value = Sheet2.Range("A1:B3").ValueEnd Sub▲在指定区域选择单元时数值加1(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Not Application.Intersect([a1:e10], Target) Is Nothing ThenTarget = Val(Target) + 1End IfEnd Sub▲混合文本的编号返回Sub 混合文本的编号()Worksheets(1).Range("B2").Value = "北京" & (--(Mid(Worksheets(1).Range("B2"), 3, 100)) + 1)End Sub▲指定区域单元双击数据累加(工作表代码)返回Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)If Not Application.Intersect([A1:Y100], Target) Is Nothing Thenoldvalue = Val(Target.Value)inputvalue = InputBox("请输入数量,按ENTER键确认!", "数值累加器")Target.Value = oldvalue + inputvalueEnd IfEnd Sub▲选择单元区域触发事件(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)If Target.Address = "$A$1:$B$2" ThenMsgBox "你选择了$A$1:$B$2单元"End IfEnd Sub▲当修改指定单元内容时自动执行宏(工作表代码)返回Private Sub Worksheet_Change(ByVal Target As Range)If Not Application.Intersect(Target, [B3:B4]) Is Nothing Then重排窗口End IfEnd Sub▲被指定单元内容限制执行宏返回Sub 被指定单元限制执行宏()If Range("$A$1") = "关闭" Then Exit Sub窗口End Sub▲双击单元隐藏该行(工作表代码)返回End Sub▲高亮显示行(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Cells.Interior.ColorIndex = 2Rows("1:2").Interior.ColorIndex = 40 '保持1至2行的颜色推荐39,22,40,Rows(Target.Row).Interior.ColorIndex = 35 '高亮推荐颜色35,20,24,34,37,40,15End Sub▲高亮显示行和列(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal Target As Range)Cells.Interior.ColorIndex = xlNoneRows(Target.Row).Interior.ColorIndex = 34Columns(Target.Column).Interior.ColorIndex = 34End Sub▲为指定工作表设置滚动范围(工作簿代码)返回Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)Sheet1.ScrollArea = "A1:M30"End Sub▲在指定单元记录打印和预览次数(工作簿代码)返回Private Sub Workbook_BeforePrint(Cancel As Boolean)Range("A1") = 1 + Range("A1")End Sub▲自动数字金额转大写(工作表代码)返回Private Sub Worksheet_Change(ByVal M As Range)On Error Resume Nexty = Int(Round(100 * Abs(M)) / 100)j = Round(100 * Abs(M) + 0.00001) - y * 100f = (j / 10 - Int(j / 10)) * 10A = IIf(y < 1, "", Application.Text(y, "[DBNum2]") & "元")b = IIf(j > 9.5, Application.Text(Int(j / 10), "[DBNum2]") & "角", IIf(y < 1, "", IIf(f > 1, "零", "")))c = IIf(f < 1, "整", Application.Text(Round(f, 0), "[DBNum2]") & "分")M = IIf(Abs(M) < 0.005, "", IIf(M < 0, "负" & A & b & c, A & b & c))End Sub▲将全部工作表的A1单元作为单击按钮(工作簿代码)返回Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)If Target.Address = "$A$1" ThenCall 宏名End IfEnd Sub▲闹钟——到指定时间执行宏(工作簿代码)返回Private Sub Workbook_Open()Application.OnTime ("11:45:00"), "提示1" '宏名字Application.OnTime ("12:00:00"), "提示2" '宏名字End Sub▲改变Excel界面标题的宏(工作簿代码)返回Private Sub Workbook_Open()Application.Caption = "春节快乐"End Sub▲在指定工作表的指定单元返回光标当前多选区地址(工作簿代码)返回Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)Worksheets("表2").Range("A1") = Target.Address(0, 0)End Sub▲B列录入数据时在A列返回记录时间(工作表代码)返回Public Sub Worksheet_Change(ByVal Target As Range)If Target.Column = 2 ThenTarget.Offset(, -1) = Now▲当指定区域修改时在其右侧的2个单元返回当前日期和时间(工作表代码)返回Public Sub Worksheet_Change(ByVal Target As Range)If Not Application.Intersect(Target, [A1:A1000]) Is Nothing ThenIf Target.Column = 1 ThenTarget.Offset(, 1) = DateTarget.Offset(, 2) = TimeEnd IfEnd IfEnd SubPublic Sub Worksheet_Change(ByVal Target As Range)If Not Application.Intersect(Target, [A1:A1000]) Is Nothing ThenIf Target.Column = 1 ThenTarget.Offset(, 1) = Format(Now(), "yyyy-mm-dd")Target.Offset(, 2) = Format(Now(), "h:mm:ss")End IfEnd IfEnd Sub▲指定单元显示光标位置内容(工作表代码)返回Private Sub Worksheet_SelectionChange(ByVal T As Range)Sheets(1).Range("A1") = SelectionEnd Sub▲每编辑一个单元保存文件返回Private Sub Worksheet_Change(ByVal Target As Range)ThisWorkbook.SaveEnd Sub▲指定允许编辑区域返回Sub 指定允许编辑区域()ActiveSheet.ScrollArea = "B8:G15"End Sub▲解除允许编辑区域限制返回Sub 解除允许编辑区域限制()ActiveSheet.ScrollArea = ""End Sub▲删除指定行返回Sub 删除指定行()Workbooks("临时表").Sheets("表2").Range("5:5").DeleteEnd Sub▲删除A列为指定内容的行返回Sub 删除A列为指定内容的行()Dim a, b As Integera = Sheet1.[a65536].End(xlUp).RowFor b = a To 2 Step -1If Cells(b, 1).Value = "删除" ThenRows(b).DeleteEnd IfNextEnd Sub▲删除A列非数字单元行返回Sub 删除A列非数字单元行()i = [a65536].End(xlUp).RowRange("A1:A" & i).SpecialCells(xlCellTypeConstants, 2).EntireRow.DeleteEnd Sub▲有条件删除当前行返回Sub 有条件删除当前行()If [A1] = 2 Or [B1] = "删除" Then▲选择下一行返回Sub 选择下一行()ActiveCell.Offset(1, 0).Rows("1:1").EntireRow.SelectEnd Sub▲选择第5行开始所有数据行返回Sub 选择第5行开始所有数据行A()Dim i%i = Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).EntireRow.RowRows("5:" & i).SelectEnd SubSub 选择第5行开始所有数据行B()Rows("5:" & Cells.Find("*", , , , 1, 2).Row).SelectEnd Sub▲选择光标或选区所在行返回Sub 选择光标或选区所在行()Selection.EntireRow.SelectEnd Sub▲选择光标或选区所在列返回Sub 选择光标或选区所在列()Selection.EntireColumn.SelectEnd Sub▲光标定位到名称指定位置返回Sub 定位()Application.Goto Range(Evaluate("名称"))End Sub▲选择名称定义的数据区返回Sub 选择名称定义的数据区()[数据区].Select '插入名称要使用INDIRECT函数'Range("数据区").Select 或者'Sheet1.Range("数据区").Select 或者End Sub▲选择到指定列的最后行返回Sub 选择到指定列的最后行()Range("C4:G" & [G65536].End(xlUp).Row).SelectEnd Sub▲将Sheet1的A列的非空值写到Sheet2的A列返回Sub 将Sheet1的A列的非空值写到Sheet2的A列()Sheet1.Columns("A:A").SpecialCells(2, 23).SpecialCells(12).Copy Sheet2.[A1]End Sub▲将名称1的数据写到名称2返回Sub Macro2()Range("位置2") = Range("位置1").ValueEnd Sub▲单元反选返回Sub 单元反选()Application.DisplayAlerts = FalseApplication.ScreenUpdating = FalseDim raddress As String, taddress As Stringraddress = Selection.Addresstaddress = edRange.AddressWith Sheets.Add.Range(taddress) = 0End WithActiveSheet.Range(raddress).SelectApplication.ScreenUpdating = TrueEnd Sub▲调整选中对象中的文字返回Sub 调整选中对象中的文字()'文字居中、自动调整大小With Selection.HorizontalAlignment = xlCenter.VerticalAlignment = xlCenter.ReadingOrder = xlContext.Orientation = xlHorizontal.AutoSize = True.AddIndent = FalseEnd WithEnd Sub▲去除指定范围内的对象返回Sub 去除指定范围内的对象()Dim p As ShapeSet My = Worksheets("工作表名")For Each p In My.ShapesIf Not Application.Intersect(p.TopLeftCell, Range("范围")) Is Nothing Then p.DeleteNextEnd Sub▲更新透视表数据项返回Sub DeleteMissingItems2002All()'防止数据透视表中显示无用的数据项'在 Excel 2002 或更高版本中'如果无用的数据项已经存在,'运行这个宏可以更新Dim pt As PivotTableDim ws As WorksheetFor Each ws In ActiveWorkbook.WorksheetsFor Each pt In ws.PivotTablespt.PivotCache.MissingItemsLimit = xlMissingItemsNoneNext ptNext wsEnd Sub▲将全部工作表名称写到A列返回Sub 将全部表名称写到A列()k = 1For Each Sht In SheetsCells(k + 1, 1) = '指定写入的行和列k = k + 1NextEnd Sub▲为当前选定的多单元插入指定名称返回Sub 为当前选定的多单元插入指定名称() = "临时"s.Add Name:="临时", RefersTo:=Selection '或者换用这行代码也可以End Sub▲删除全部名称返回Sub 删除全部名称()On Error Resume NextDim l As Integerl = s.CountFor i = l To 1 Step -1s(i).Delete。

EXCEL宏代码大全

EXCEL宏代码大全

EXCEL宏代码大全000. A列半角内容变红Sub A列半角内容变红() ? Dim rg As Range, i As Long ? Application.ScreenUpdating = False ? For Each rg In Cells.SpecialCells(xlCellTypeConstants, 3) ??? For i = 1 To Len(rg) ????? If Asc(Mid(rg, i, 1))001. A列等于A列减B列Sub A列等于A列减B列() For i = 1 To 23 Cells(i, 1) = Cells(i, 1) - Cells(i, 2) Next End Sub002. B列录入数据时在A列返回记录时间(工作表代码)Public Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 2 Then Target.Offset(, -1) = Now End If End Sub003. Excel宏常用代码本大类暂没有内容,以下是关于本类的所有记录集。

004. Sub 以当前日期为名称另存文件()ActiveWorkbook.SaveAs Filename:=Date & ".xls" End Sub005. Sub 启用保存()mandBars("File").Controls(4).Enabled = True mandBars("File").Controls(5).Enabled = True End Sub006. Sub 执行前需要验证密码的宏()If InputBox("请输入您的使用权限:", "系统提示") = 123 Then 重排窗口'要执行的宏代码或宏名称Else MsgBox "对不起,您没有使用该宏的权限,按确定键后退出!" End If End Sub007. Sub 选择第5行开始所有数据行B()Rows("5:" & Cells.Find("*", , , , 1, 2).Row).Select End Sub008. VBA返回公式结果Sub VBA返回公式结果() x = Application.WorksheetFunction.Sum(Range("a2:a100")) Range("B1") = x End Sub009. 不连续区域录入对勾Sub 批量录入对勾() Selection.FormulaR1C1 = "√" End Sub010. 不连续区域录入当前单元地址Sub 区域录入当前单元地址() For Each mycell In Selection mycell.FormulaR1C1 = mycell.Address Next End Sub011. 不连续区域录入当前数字日期Sub 区域录入当前数字日期() Selection.FormulaR1C1 = Format(Now(), "yyyymmdd") End Sub012. 不连续区域录入当前文件名Sub 批量录入当前文件名() Selection.FormulaR1C1 = End Sub013. 不连续区域录入当前日期Sub 区域录入当前日期() Selection.FormulaR1C1 = Format(Now(), "yyyy-m-d") End Sub014. 不连续区域录入当前日期和时间Sub 区域录入当前日期和时间() Selection.FormulaR1C1 = Format(Now(), "yyyy-m-d h:mm:ss") End Sub015. 不连续区域插入当前文件名和表名及地址Sub 批量插入当前文件名和表名及地址() For Each mycell In Selection mycell.FormulaR1C1 = "[" + + "]" + + "!" + mycell.Address Next End Sub016. 不连续区域插入文本Sub 批量插入文本() Dim s As Range For Each s In Selection s = "文本内容" & s Next End Sub017. 不连续区域添加文本Sub 批量添加文本() Dim s As Range For Each s In Selection s = s & "文本内容" Next End Sub018. 为当前选定的多单元插入指定名称Sub 为当前选定的多单元插入指定名称() = "临时" s.Add Name:="临时", RefersTo:=Selection '或者换用这行代码也可以End Sub019. 为指定工作表加指定密码保护表Sub 为指定工作表加指定密码保护表() Sheet10.Protect Password:="123" End Sub020. 为指定工作表设置滚动范围(工作簿代码)Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) Sheet1.ScrollArea = "A1:M30" End Sub021. 从指定位置向下同时录入多单元指定内容Sub 从指定位置向下同时录入多单元指定内容() Dim arr arr = Array("1", "2", "13", "25", "46", "12", "0", "20") [B2].Resize(8, 1) = Application.WorksheetFunction.Transpose(arr) End Sub022. 以A1单元内容批量插入批注Sub 以A1单元内容批量插入批注() Dim r As Range If Selection.Cells.Count > 0 Then For Each r In Selection r.AddComment ment.Visible = False ment.Text Text:=[a1].Text Next End If End Sub023. 以A1单元文本作表名插入工作表Sub 以A1单元文本作表名插入工作表() Dim nm As String nm = [a1] Sheets.Add = nm End Sub024. 以当前日期为新文件名另存文件Sub 以当前日期为新文件名另存文件() ThisWorkbook.SaveAs ThisWorkbook.Path & "\" & Format(Now(), "yyyymmdd") & ".xls" End Sub025. 以当前日期和时间为新文件名另存文件Sub 以当前日期和时间为新文件名另存文件() ThisWorkbook.SaveAs。

157个常用宏(有代码可直接复制)

157个常用宏(有代码可直接复制)

奇偶页分别打印点击自动打印多工作表第一页点击查找A列文本循环插入分页符(模块)点击将A列最后数据行以上的所有B列图片大小调整为所在点击单元大小返回光标所在行数点击在A1返回当前选中单元格数量点击返回当前工作簿中工作表数量点击返回光标选择区域的行数和列数点击工作表中包含数据的最大行数点击返回A列数据的最大行数点击将所选区域文本插入新建文本框点击批量插入地址批注点击批量插入统一批注点击以A1单元内容批量插入批注点击不连续区域插入当前文件名和表名及地址点击不连续区域录入当前单元地址点击连续区域录入当前单元地址点击返回当前单元地址点击不连续区域录入当前日期点击不连续区域录入当前数字日期点击不连续区域录入当前日期和时间点击不连续区域录入对勾点击不连续区域录入当前文件名点击不连续区域添加文本点击点击当前单元录入计算机用户名点击为指定工作表加指定密码保护表点击在有密码的工作表执行代码点击执行前需要验证密码的宏(控件按钮代码)点击拷贝A1公式和格式到A2点击插入数值条件格式点击点击当前单元加2点击A列等于A列减B列点击点击每编辑一个单元保存文件点击指定允许编辑区域点击解除允许编辑区域限制点击删除A列为指定内容的行点击删除A列非数字单元行点击有条件删除当前行点击选择第5行开始所有数据行点击选择光标或选区所在行点击选择到指定列的最后行点击将Sheet1的A列的非空值写到Sheet2的A列点击将全部工作表名称写到A列点击按A列数据批量创建新表(控件按钮代码)点击判断指定文件是否已经打开点击点击将指定范围的数据排列到D列点击光标移动点击光标所在行上移一行点击点击打开文件时提示指定工作表是保护状态点击(ThisWorkbook)全选固定范围内小于0的单元点击全选选定范围内小于0的单元点击固定区域单元分类变色点击点击显示光标所在单元的批注的代码点击提示确定或取消执行宏点击拷贝指定表不相邻多列数据到新位置点击在当前选区有条件替换数值为文本点击自动筛选第2列值为A的行点击取消自动筛选()点击全部显示指定表的自动筛选点击点击在A列产生不重复随机数点击将A列数据随机排列到F列点击取消选定区域的公式只保留值(假空转真空)点击填公式点击在第一个表前插入多工作表点击点击返回表中第一个非空单元地址(行搜索)点击返回表中各非空单元区域地址(行搜索)点击返回第一个数值行号点击返回第1行最右边非空单元的列号点击返回连续数值单元的数量点击统计指定范围和内容的单元数量点击统计不同颜色的数字的和(自定义函数)点击返回圆周率π点击定义指定单元内容为页眉/页脚点击提示并全部清除当前选择区域点击对指定工作表执行取消隐藏》打印》隐藏工作表点击弹出提示A1单元内容点击撤消工作表保护并取消密码点击将第5行移到窗口的最上面点击对第一张工作表的指定区域进行排序点击显示指定工作表的打印预览点击用单元格A1的内容作为文件名另存当前工作簿点击添加自定义序列点击弹出打印对话框点击点击把a列不重复值取到e列点击当前选区的行列数点击返回光标所在行号点击VBA返回公式结果点击合并A1至C1的内容写到D15单元的批注中点击重算模式点击分离字符串到每个单元格点击条件格式点击自动录入一个符号点击保护所有工作表点击判断正负数点击判断奇偶数点击选中变色点击自动输入当前日期点击高亮显示当前行点击按A列数据批量修改表名称点击光标指定到名称指定位置(模块)点击删除指定列含空格的所有行点击删除指定列所有重复行点击。

(word完整版)Excel VBA常用技巧代码

(word完整版)Excel VBA常用技巧代码

1.删除重复行 (1)2. ActiveX控件的相关操作 (1)3. 单元格内容匹配 (2)4。

单元格填充公式 (3)5。

弹出打开对话框 (3)6. 操作文件夹下的所有工作簿 (3)7. 获取数据区域的最后一行和最后一列 (4)8. 获取列的字母顺序[A~IV] (4)9. 自定义函数返回数组并填充至单元格区域 (4)10. 绘制曲线图 (5)11. 单元格区域拷贝 (5)12. 操纵数据库(查、增、删、改) (6)13。

待定XX (6)1.删除重复行关键字:[a65536].End(xlUp).Row、Offset()、相关双层循环Sub RemoveDuplicate()'删除重复行For i = [a65536].End(xlUp)。

Row — 1 To 1 Step —1 '按倒叙删除For j = [a65536]。

End(xlUp).Row To i + 1 Step —1If Cells(i, 1)。

Value = Cells(j, 1).Value ThenRows(i)。

DeleteEnd IfNextNextEnd SubSub RemoveItem()'删除相邻重复,但不删除隔行重复Dim i As LongWith Range("A2”)’以A2为基准进行单元格偏移Do While .Offset(i, 0)If .Offset(i, 0)。

Value = .Offset(i — 1, 0)。

Value Then 。

Offset(i, 0).EntireRow.Delete i = i + 1LoopEnd WithEnd Sub2.ActiveX控件的相关操作关键字:ActiveX、OLEObjects、ActiveSheet。

OLEObjects遍历控件Dim c As ObjectFor Each c In ActiveSheet.OLEObjectsIf = ”ComboBox” & i Then’…………。

EXCEL宏命令大全

EXCEL宏命令大全

EXCEL宏命令⼤全Excel表格公式⼤全1、查找重复内容公式:=IF(COUNTIF(A:A,A2)>1,"重复","")。

2、⽤出⽣年⽉来计算年龄公式:=TRUNC((DAYS360(H6,"2009/8/30",FALSE))/360,0)。

3、从输⼊的18位⾝份证号的出⽣年⽉计算公式:=CONCATENATE(MID(E2,7,4),"/",MID(E2,11,2),"/",MID(E2,13,2))。

4、从输⼊的⾝份证号码内让系统⾃动提取性别,可以输⼊以下公式:=IF(LEN(C2)=15,IF(MOD(MID(C2,15,1),2)=1,"男","⼥"),IF(MOD(MID(C2,17,1),2)=1,"男","⼥"))公式内的“C2”代表的是输⼊⾝份证号码的单元格。

1、求和:=SUM(K2:K56)——对K2到K56这⼀区域进⾏求和;2、平均数:=AVERAGE(K2:K56)——对K2K56这⼀区域求平均数;3、排名:=RANK(K2,K$2:K$56)——对55名学⽣的成绩进⾏排名;4、等级:=IF(K2>=85,"优",IF(K2>=74,"良",IF(K2>=60,"及格","不及格")))5、学期总评:=K20.3+M20.3+N20.4——假设K列、M列和N列分别存放着学⽣的“平时总评”、“期中”、“期末”三项成绩;6、最⾼分:=MAX(K2:K56)——求K2到K56区域(55名学⽣)的最⾼分;7、最低分:=MIN(K2:K56)——求K2到K56区域(55名学⽣)的最低分;8、分数段⼈数统计:(1)=COUNTIF(K2:K56,"100")——求K2到K56区域100分的⼈数;假设把结果存放于K57单元格;(2)=COUNTIF(K2:K56,">=95")-K57——求K2到K56区域95~99.5分的⼈数;假设把结果存放于K58单元格;(3)=COUNTIF(K2:K56,">=90")-SUM(K57:K58)——求K2到K56区域90~94.5分的⼈数;假设把结果存放于K59单元格;(4)=COUNTIF(K2:K56,">=85")-SUM(K57:K59)——求K2到K56区域85~89.5分的⼈数;假设把结果存放于K60单元格;(5)=COUNTIF(K2:K56,">=70")-SUM(K57:K60)——求K2到K56区域70~84.5分的⼈数;假设把结果存放于K61单元格;(6)=COUNTIF(K2:K56,">=60")-SUM(K57:K61)——求K2到K56区域60~69.5分的⼈数;假设把结果存放于K62单元格;(7)=COUNTIF(K2:K56,"<60")——求K2到K56区域60分以下的⼈数;假设把结果存放于K63单元格;说明:COUNTIF函数也可计算某⼀区域男、⼥⽣⼈数。

OFFICE-259个常用宏(代码)

OFFICE-259个常用宏(代码)

点击
查找A列文本循环插入分页符
点击
将A列最后数据行以上的所有B列图片大小调整为所在 单元大小
点击
返回光标所在行数
点击
在A1返回当前选中单元格数量
点击
返回当前工作簿中工作表数量
点击
返回光标选择区域的行数和列数
点击
工作表中包含数据的最大行数
点击
返回A列数据的最大行数
点击
将所选区域文本插入新建文本框
点击
批量插入地址批注
点击
高亮显示行和列(工作表代码)
点击
为指定工作表设置滚动范围(工作簿代码)
点击
在指定单元记录打印和预览次数(工作簿代码)
点击
自动数字金额转大写(工作表代码)
点击
将全部工作表的A1单元作为单击按钮(工作簿代码) 点击
工作表 工作表 工作表 工作表 文件管理 工作表 工作表 单元赋值 单元赋值 工作表 密码 密码 密码 单元赋值
点击 点击 点击 点击 点击 点击 点击 点击
窗口 单元赋值 打印 文件管理 文件管理 单元赋值 语音 语音
点击
延时15秒执行重排窗口宏
点击
撤消工作表保护并取消密码
点击
重算指定表
点击
筛选 格式 格式 单元赋值 事件 事件 行列操作 单元赋值 单元赋值 单元赋值 其他 信息 格式 格式 单元赋值 工作表 工作表 单元赋值 自定义函数 信息 超链接 超链接 超链接
超链接
查找和引用 查找和引用 查找和引用 查找和引用 查找和引用 查找和引用 查找和引用 查找和引用 查找和引用 查找和引用 其他 打印 单元赋值 单元赋值 单元赋值 打印 事件 事件 信息 事件 工作表 工作表
分离临时表A列数据的文本和超链接并会同其他数据整 理到数据库表

Excel 宏编程的常用代码

Excel 宏编程的常用代码

Excel 宏编程的常用代码用过VB的人都应该知道如何声明变量,在VBA中声明变量和VB中是完全一样的!使用Dim语句Dim a as integer '声明a为整型变量Dim a '声明a为变体变量Dim a as string '声明a为字符串变量Dim a as currency ,b as currency ,c as currency '声明a,b,c为货币变量......声明变量可以是:Byte、Boolean、Integer、Long、Currency、Single、Double、Decimal(当前不支持)、Date、String(只限变长字符串)、String * length(定长字符串)、Object、V ariant、用户定义类型或对象类型。

强制声明变量Option Explicit说明:该语句必在任何过程之前出现在模块中。

声明常数用来代替文字值。

Const' 常数的默认状态是Private。

Const My = 456' 声明Public 常数。

Public Const MyString = "HELP"' 声明Private Integer 常数。

Private Const MyInt As Integer = 5' 在同一行里声明多个常数。

Const MyStr = "Hello", MyDouble As Double = 3.4567选择当前单元格所在区域在EXCEL97中,有一个十分好的功能,他就是把鼠标放置在一个有效数据单元格中,执行该段代码,你就可以将连在一起的一片数据全部选中。

只要将该段代码加入到你的模块中。

Sub My_SelectSelection.CurrentRegion.SelectEnd sub返回当前单元格中数据删除前后空格后的值sub my_trimmsgbox Trim(ActiveCell.Value)end sub单元格位移sub my_offsetActiveCell.Offset(0, 1).Select'当前单元格向左移动一格ActiveCell.Offset(0, -1).Select'当前单元格向右移动一格ActiveCell.Offset(1 , 0).Select'当前单元格向下移动一格ActiveCell.Offset(-1 , 0).Select'当前单元格向上移动一格end sub如果上述程序产生错误那是因为单元格不能移动,为了解除上述错误,我们可以往sub my_offset 之下加一段代码on error resume next注意以下代码都不再添加sub “代码名称” 和end sub请自己添加!给当前单元格赋值ActiveCell.Value = "你好!!!"给指定单元格赋值例如:A1单元格内容设为"HELLO"Range("a1").value="hello"又如:你现在的工作簿在sheet1上,你要往sheet2的A1单元格中插入"HELLO"1.sheets("sheet2").selectrange("a1").value="hello"或2.Sheets("sheet1").Range("a1").V alue = "hello"说明:1.sheet2被选中,然后在将“HELLO"赋到A1单元格中。

excel代码大全

excel代码大全

mandBars("File").Controls(4).Enabled = True Applicaቤተ መጻሕፍቲ ባይዱmandBars("File").Controls(5).Enabled = True End Sub
006. Sub 执行前需要验证密码的宏()
011. 不连续区域录入当前数字日期
Sub 区域录入当前数字日期() Selection.FormulaR1C1 = Format(Now(), "yyyymmdd") End Sub
012. 不连续区域录入当前文件名
Sub 批量录入当前文件名() Selection.FormulaR1C1 = End Sub
025. 以当前日期和时间为新文件名另存文件
Sub 以当前日期和时间为新文件名另存文件() ThisWorkbook.SaveAs
003. Excel宏常用代码
本大类暂没有内容,以下是关于本类的所有记录集。
004. Sub 以当前日期为名称另存文件()
ActiveWorkbook.SaveAs Filename:=Date & ".xls" End Sub
005. Sub 启用保存()
022. 以A1单元内容批量插入批注
Sub 以A1单元内容批量插入批注() Dim r As Range If Selection.Cells.Count > 0 Then For Each r In Selection r.AddComment ment.Visible = False ment.Text Text:=[a1].Text Next End If End Sub
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

非常实用excel宏代码代码功能包含:显示所有隐藏工作表,按指定列拆分工作表,将一个工作簿内的多个工作表拆分为一个个独立的工作簿,在工作簿打开的状态下直接重命名活动工作簿,工作表保护密码破解,一次性关闭所有工作簿,将所选单元格数值单位转换为万显示,一次性提取所有工作表名称等--------------------------------------------------Sub 显示所有隐藏工作表()For Each St In SheetsIf St.Visible = False Then St.Visible = True NextEnd Sub-------------------------------------------Sub 按指定列拆分工作表()Dim i%, m%, h$h = Range("a1").Selectm = InputBox("请输入列数")Columns(m).CopyWorksheets.Add After:=Sheets(Sheets.Count) = "B"Range("A1").SelectActiveSheet.PasteRange("A:A").RemoveDuplicates (1)Sheets("B").Visible = FalseFor i = 2 To Application.WorksheetFunction.CountA(Sheets("B").Range(" A:A"))Sheets(h).ActivateedRange.AutoFilter Field:=m, Criteria1:=Sheets("B").Cells(i, 1)Sheets(h).UsedRange.CopySheets.Add After:=Sheets(Sheets.Count)ActiveSheet.Paste = Sheets("B").Cells(i, 1)Sheets(h).SelectNextSelection.AutoFilterApplication.DisplayAlerts = FalseSheets("B").DeleteApplication.DisplayAlerts = TrueEnd Sub----------------------------------------Sub 重命名活动工作簿()'如果利用DIR提取的活动工作簿的名称长度为0(即未保存),那么提示用户,然后退出程序If Len(Dir(ActiveWorkbook.FullName)) = 0 Then MsgBox "请先保存工作簿", vbOKOnly, "友情提示": Exit Sub Dim 原名称As String, 新名称As String, 后缀名As String, 路径As String '声明变量原名称= '提取活动工作簿名称后缀名= StrReverse(Mid(StrReverse(原名称), 1, InStr(StrReverse(原名称), "."))) '提取活动工作簿的后缀名新名称= Application.InputBox("请输入文件名", "新名称", Replace(原名称, 后缀名, ""), , , , , 2) '弹出输入框让用户输入新的名称If 新名称= "False" Then End '如果选择了取消键则结束过程路径= Replace(ActiveWorkbook.FullName, 原名称, "") '提取活动工作簿的路径On Error Resume Next '当有错误时继续执行MkDir "C:\" & 新名称'在C盘创建一个同名的文件夹(测试字符串能否作为文件名称)If Err <> 0 Then '如果有错误MsgBox "您输入的字符不允许作为文件名,请重新输入!", vbOKOnly, "友情提示" '提示Else'否则RmDir "C:\" & 新名称'删除创建的文件夹ActiveWorkbook.SaveAs 路径& 新名称& 后缀名'将活动工作簿另存为指定的名称(与原文件相同路径下)Kill 路径& 原名称'删除原来的文件End IfEnd Sub---------------------------------------------------Public Sub 工作表保护密码破解()Const DBLSPACE As String = vbNewLine & vbNewLine Const AUTHORS As String = DBLSPACE & vbNewLine & _ "作者:McCormick JE McGimpsey "Const HEADER As String = "工作表保护密码破解"Const VERSION As String = DBLSPACE & "版本Version 1.1.1"Const REPBACK As String = DBLSPACE & ""Const ZHENGLI As String = DBLSPACE & " hfhzi3—戊冥整理"Const ALLCLEAR As String = DBLSPACE & "该工作簿中的工作表密码保护已全部解除!!" & DBLSPACE & "请记得另保存" _& DBLSPACE & "注意:不要用在不当地方,要尊重他人的劳动成果!"Const MSGNOPWORDS1 As String = "该文件工作表中没有加密"Const MSGNOPWORDS2 As String = "该文件工作表中没有加密2"Const MSGTAKETIME As String = "解密需花费一定时间,请耐心等候!" & DBLSPACE & "按确定开始破解!"Const MSGPWORDFOUND1 As String = "密码重新组合为:"& DBLSPACE & "$$" & DBLSPACE & _"如果该文件工作表有不同密码,将搜索下一组密码并修改清除"Const MSGPWORDFOUND2 As String = "密码重新组合为:" & DBLSPACE & "$$" & DBLSPACE & _"如果该文件工作表有不同密码,将搜索下一组密码并解除" Const MSGONLYONE As String = "确保为唯一的?"Dim w1 As Worksheet, w2 As WorksheetDim i As Integer, j As Integer, k As Integer, l As IntegerDim m As Integer, n As Integer, i1 As Integer, i2 As Integer Dim i3 As Integer, i4 As Integer, i5 As Integer, i6 As Integer Dim PWord1 As StringDim ShTag As Boolean, WinTag As BooleanApplication.ScreenUpdating = FalseWith ActiveWorkbookWinTag = .ProtectStructure Or .ProtectWindowsEnd WithShTag = FalseFor Each w1 In WorksheetsShTag = ShTag Or w1.ProtectContentsNext w1If Not ShTag And Not WinTag ThenMsgBox MSGNOPWORDS1, vbInformation, HEADER Exit SubEnd IfMsgBox MSGTAKETIME, vbInformation, HEADERIf Not WinTag ThenElseOn Error Resume NextDo 'dummy do loopFor i = 65 To 66: For j = 65 To 66: For k = 65 To 66For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66 For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66 For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126 With ActiveWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)If .ProtectStructure = False And _.ProtectWindows = False ThenPWord1 = Chr(i) & Chr(j) & Chr(k) & Chr(l) & _Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)MsgBox Application.Substitute(MSGPWORDFOUND1, _"$$", PWord1), vbInformation, HEADERExit Do 'Bypass all for...nextsEnd IfEnd WithNext: Next: Next: Next: Next: NextNext: Next: Next: Next: Next: NextLoop Until TrueOn Error GoTo 0End IfIf WinTag And Not ShTag ThenMsgBox MSGONLYONE, vbInformation, HEADER Exit SubEnd IfOn Error Resume NextFor Each w1 In Worksheets'Attempt clearance with PWord1w1.Unprotect PWord1Next w1On Error GoTo 0ShTag = FalseFor Each w1 In Worksheets'Checks for all clear ShTag triggered to 1 if not.ShTag = ShTag Or w1.ProtectContentsNext w1If ShTag ThenFor Each w1 In WorksheetsWith w1If .ProtectContents ThenOn Error Resume NextDo 'Dummy do loopFor i = 65 To 66: For j = 65 To 66: For k = 65 To 66For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66 For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66 For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126 .Unprotect Chr(i) & Chr(j) & Chr(k) & _Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)If Not .ProtectContents ThenPWord1 = Chr(i) & Chr(j) & Chr(k) & Chr(l) & _Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)MsgBox Application.Substitute(MSGPWORDFOUND2, _ "$$", PWord1), vbInformation, HEADER'leverage finding Pword by trying on other sheetsFor Each w2 In Worksheetsw2.Unprotect PWord1Next w2Exit Do 'Bypass all for...nextsEnd IfNext: Next: Next: Next: Next: NextNext: Next: Next: Next: Next: NextLoop Until TrueOn Error GoTo 0End IfEnd WithNext w1End IfMsgBox ALLCLEAR & AUTHORS & VERSION & REPBACK & ZHENGLI, vbInformation, HEADEREnd Sub---------------------------------------------------Sub 关闭所有工作簿()Application.DisplayAlerts = FalseWorkbooks.CloseApplication.DisplayAlerts = TrueEnd Sub--------------------------------------------------- Sub 将一个工作簿内的多个工作表拆分为一个个独立的工作簿()Application.DisplayAlerts = FalseDim sht As WorksheetDim MyBook As WorkbookSet MyBook = ActiveWorkbookFor Each sht In MyBook.Sheetssht.CopyActiveWorkbook.SaveAsFileName:=MyBook.Path & "\" & , FileFormat:=xlNormal '将工作簿另存为EXCEL默认格式ActiveWorkbook.CloseNextApplication.DisplayAlerts = TrueMsgBox "文件已经被分拆完毕!"End Sub---------------------------------------------------Sub 所选单元格数值单位转换为万显示()'' 格式万宏'' 快捷键: Ctrl+Shift+ZSelection.NumberFormatLocal = "0!.0,万"End Sub--------------------------------------------------- Sub 提取所有工作表名称()Dim xFor x = 1 To Sheets.CountCells(x, 1) = Sheets(x).NameNext xEnd Sub。

相关文档
最新文档