1、vba 中简单实用的语句(Simple and practical sentences in VBA)常用语句(1) 。工作簿1。错误恢复的忽略错误继续执行 VBA 代码,避免出现错误消息2,GoTo ErrorHandler 当错误发生时跳转到过程中的某个位置误差3。应用。displayalerts =假”在程序执行过程中使出现的警告框不显示4。应用。screenupdating =假”关闭屏幕刷新screenupdating =真正的打开屏幕刷新应用。5.activeworkbook.name”返回活动工作薄的名称6。activeworkbook WindowState = xlmaxim
2、ized”将当前工作簿最大化。7。表(Sheet1) 。名称=“和” “将 Sheet1 命名为总和8。工作表(数组(“Sheet1” 、 “Sheet2”) ) 。选择“同时选择工作表 1 和工作表 29.activesheet.usedrange.formatconditions.delete”删除当前工作表中所有的条件格式10,在当前工作表的 pagesetup。定位= xllandscape 或活动表。pagesetup。定位= 2 将页面设置更改为横向11.cells.select”选定当前工作表的所有单元格12。范围(“A1” ) 。一个 clearContents”清除活动工作表
3、上单元格 A1 中的内容selection.clearcontents”清除选定区域内容范围(“A1:D4) 。清晰的彻底清除 A1 至 D4 单元格区域的内容,包括格式13 活动单元格的偏移(1,0) 。选择“活动单元格下移一行,同理,可下移一列范围(“A1” ) 。偏移(columnoffset:= 1)或范围(“A1” ) 。偏移(,1) ”偏移一列范围(“A1” ) 。偏移(rowoffset:= 1)或范围(“A1” ) 。偏移(1)的向上偏移一行14 活动窗口选择的价值= XX XX 输入到所选单元格区域中将值15.activewindow.rangeselection.count
4、”活动窗口中选择的单元格数16。范围(“A1” ) 。interior.colorindex 或细胞(1,1) 。interior.colorindex”获取单元格 A1 背景色17.names.add 名称:=“MyArray” ,指的是:= arraynum”将数组arraynum 命名为 MyArray18.names.add 名称:=“producenum” ,是指:=“= $ 1 美元” ,可见:=假”将名称隐藏19。细胞(8,8) 。formulaarray =“=总和(R2c 1 1 :R C 1 * 1 R2c:R C) ”在单元格中输入数组公式注意必须使用R1C1 样式的表达
5、式。(2) 。图表1.activesheet.chartobjects.count”获取当前工作表中图表的个数2。将。ChartObjects(“Chart1” ) 。选择“选中当前工作表中图表Chart13。表(“表 2”) 。chartarea。内饰颜色= 2 更改图表工作表中图表区的颜色4.charts.add”添加新的图表工作表5.activechart.plotarea.interior。“将绘图区颜色变为白色 xlnone ColorIndex =(3) 。窗体“你好 1.msgbox!“消息框中显示消息你好2。ANS = MsgBox(“继续吗?” ,vbyesno)的在消息框中
6、点击”是”按钮,则 ANS 值为 vbyes;点击”否”按钮,则 ANS 值为 vbno。如果 MsgBox(“继续吗?” ,vbyesno) vbyes 然后退出的返回值不为”是” ,则退出3.msgbox”这是第一行。 ”vbnewline 与“二线”的在消息框中强制换行,可用 vbcrlf 代替 vbnewline。4.userform1.show”显示用户窗体将隐藏的隐藏用户窗体将我的卸载用户窗体或卸载卸载5。应用。EnableEvents =假”禁用所有事件应用。EnableEvents =真正的启用所有事件6.application.ontime 现在+时间价值(“00:00:15
7、” ) ,“myprocedure”等待 15 秒后运行 myprocedure 过程7.application.ontime DateSerial(2006,6,6)+时间价值(“16:16:16” ) 、 “BaoPo”在 2006 年 6 月 6 日的 16:16:16 开始运行宝珀过程8.application.calculation = xlcalculationmanual”设置工作簿手动计算应用计算 xlcalculationautomatic”工作簿自动计算=。9.application.autocorrect.addreplacement”葛洲坝” 、 “三峡”自动将在工作表
8、中进行输入的”葛洲坝”更正为”三峡”10。日期= # 6/6/2006 #时间= # 6:16:16 是#”将系统时间更改为 2006 年 6 月 6 6 16 16秒分日上午时11.activecell.hyperlinks.add 锚:=当前活动,_address:=“C: Windows System32 calc.exe” ,屏幕提示:=“按下我,就会开启 Windows 计算器” ,texttodisplay:=“Windows 计算器”在活动单元格中设置开启 Windows 计算器链接当前活动。值=壳(“C: Windows System32 calc.exe” ,可包含路径)的开
9、启 Windows 计算器12。工作表中的窗体按钮禁用后,按钮形状不变,字体不变,从外表上无法看出其已禁用,如何设置属性使其像控件按纽那样明显的禁用?与将按钮(1) 。启用= false在当前工作表的形状(。字幕) 。drawingobject.font.colorindex = 15结束復原的方法与将按钮(1) 。启用=真在当前工作表的形状(drawingobject.font.colorindex = xlautomatic。字幕) 。结束(4) 。对象1 集 excelsheet = CreateObject(“Excel 表” )的创建一个 Excel工作表对象excelsheet.a
10、pplication.visible =真正的设置应用 Excel 可见对象使保存表格 ExcelSheet.应用。细胞(1, 1) 。值=“数据”在表格的第一个单元中输入文本ExcelSheet.SaveAs 的“C:测试。XLS saves the table to the C:test.xls directoryExcelSheet.Application.Quit close ExcelSet ExcelSheet = Nothing frees the object variable2. declare and create a Excel object referenceDim x
11、lApp As Excel.ApplicationDim xlBook As Excel.WorkbookDim xlSheet As Excel.WorkSheetSet xlApp = CreateObject (“Excel.Application“)Set xlBook = xlApp.Workbooks.AddSet xlSheet = xlBook.Worksheets (1)3.Application.OnKey “I“, “macro“. Set the Ctrl+I key as the shortcut key for the macro processApplicatio
12、n.Transpose (“Sun“, “Mon“, “Tur“, “Wed“, “Thu“, “Fri“, “Sat“) return a vertical array, Array, and “ “ “ “ “ “returns a vertical array.“Application.WindowState returns the current state of the windowApplication.WindowState = xlMinimized window minimizationApplication.WindowState = xlMaximized window
13、maximizationApplication.WindowState = xlNormal window normal stateApplication.Interactive=False ignores keyboard or mouse input4.Range (“A65536“).End (xlUp).Row+1 “returns the next line of the last row of the A columnCell.Range (“A1“).HasFormula “checks whether the first cell in a cell or cell regio
14、n contains a formulaCell.HasFormula “does the cell in the worksheet contain formulas?Range (“D5:D10“).Cells (1,1) return to the upper left cell range D5:D105.rng.Replace “, “0“ replaces the empty cells in the cell area with 0(5) Workbook1.ThisWorkbook.BuiltinDocumentProperties (“Last Save Time“) orA
15、pplication.Caller.Parent.Parent.BuiltinDocumentProperties (“Last Save Time“) returns the date and time of the last workbook saved2.ThisWorkbook.BuiltinDocumentProperties (“Last Print Date“) orApplication.Caller.Parent.Parent.BuiltinDocumentProperties (“Last Print Date“) returns the date and time of
16、the last print or preview Workbook3.ThisWorkbook.Path ActiveWorkbook.Path returns the path to the current workbook. (Note: if the workbook is not saved, it is empty)4.Application.Visible = False hide WorkbookApplication.Visible = True displays Workbook(6) worksheet1.ActiveSheet.Columns (“B“).Insert
17、“inserts the column on the right side of the A column, that is, insert the B columnActiveSheet.Columns (“E“).CutActiveSheet.Columns (“B“).Insert “above two“ moves the E column data to the B column, and the original B column and the subsequent data are shifted accordinglyActiveSheet.Columns (“B“).Cut
18、The ActiveSheet.Columns (“E“).Insert “above two“ moves the B column data to the D column, and the original C column and the D column data are shifted to the left column2.ThisWorkbook.Worksheets (“Sheet1“)可见,xlsheethidden”正常隐藏工作表,同在 Excel 菜单中选择”格式-工作表-隐藏”操作一样工作簿,工作表(“Sheet1” ) 。可见= xlsheetveryhidden”
19、隐藏工作表,不能通过在 Excel 菜单中选择”格式-工作表-取消隐藏”来重新显示工作表工作簿,工作表(“Sheet1” ) 。可见= xlsheetvisible”显示被隐藏的工作表3。工作簿。工作表(“Sheet1” ) ,行(1) 。隐=真正的“将工作表Sheet1 中的行 1 隐藏activecell.entirerow.hidden =真正的将当前工作表中活动单元格所在的行隐藏(7) 。公式与函数1。worksheetfunction。CountA(细胞。entirecolumn)的返回该单元格所在列非空单元格的数量worksheetfunction。CountA(细胞。entire
20、row)的返回该单元格所在行非空单元格的数量worksheetfunction。COUNTA(细胞)的返回工作表中非空单元格数量2,在当前工作表的范围(“A20:D20” ) 。公式=“=总和(R 19 1 C R C”对一列至 D 列前 19 个数值求和3。私有子 worksheet_selectionchange(ByVal 目标范围的选定 A1时要输入密码如果目标=地址“$ 1 美元” ,那么= InputBox(“请输入密码” 、 “officefans”)如果 A1,则选择其他选项。最后如果端子方法1。计算两日期之间相差多少天DateDiff(“D” ,开始时间,结束时间) ”(“D
21、”是表示要计算相差天数,如果要计算年则用“Y”月用“M” )工作日(日期)的获取今天的星期,以数值表示,1-7 分别对应星期日至星期六例:(1) 。语句示例:DateDiff(“D” ,范围(“A1” ) 。值范围(B1)的价值。 )(2) 。函数示例:昏暗的日期日期昏暗的味精日期= inpurbox(“请输入一个日期” )味精=“日:“DateDiff(“D” ,现在,日期)MsgBox 味精(3) 。单元格公式:= datedif(日期(MID(f42,1,4) 、中(f42,5,2) 、中(f42,7,2) ) 、日期(MID(g42,1,4) 、中(g42,5,2) 、中(g42,7,
22、2) ) , “D”)*注*先把字符串格式的日期解析成日期类型,用中方法:中期(文本,start_num,num_chars)可以从字符串中取出子字符串,这里 start_num 是开始位置(最小值为 1,不是 0) ,num_chars 是取出多少个字符串例如 F42 单元格内容为 20111203,那么解析成日期可以用=日期(MID(f42,1,4) 、中(f42,5,2) 、中(f42,7,2) )中期(f42,1,4)就是将 F42 单元格从第一位开始截取 4 位这样就得到了 2011 作为年,中期(f42,5,2) 、中(f42,7,2)同理得到月份和日期2。得到包含指定内容的单元格
23、所在行,列昏暗的 thiscloumn,ThisRow对于 maxc = 1 细胞(1, 256) 。端(xlUp) 。列步骤 1 的第二列内容为”更新日期”的单元格所在列如果 InStr(细胞(2,maxc) , “更新日期:” )然后thiscloumn = maxc退出最后如果下一 maxc1 细胞为 MAXR =(65536,1).End (xlUp).Row Step 1 Tenth row of content is “predetermined“ cell rowIf InStr (Cells (MaxR, 10), “scheduled“) ThenThisRow = MaxR
24、Exit ForEnd IfNext MaxRGet the required row and column number, and then jump out of the For loop with Exit ForExample of 3. cell assignmentExample 1Sub test1 ()Worksheets (“Sheet1“).Range (“A5“).Value = 22MsgBox sheet in Sheet1 cells in the A5 value of “Worksheets _& (“ Sheet1 “).Range (“ A5 “).Valu
25、eEnd SubExample twoSub test2 ()Worksheets (“Sheet1“).Range (“A1“).Value = _Worksheets (“Sheet1“).Range (“A5“).ValueMsgBox “the value in the A1 cell is also“ & _Worksheets (“Sheet1“).Range (“A5“).ValueEnd SubExample threeSub test3 ()“MsgBox“ fills a cell with a formula. This example is a random numbe
26、r formula“Range (“A1:H8“).Formula = “=Rand ()“End SubExample fourSub test4 ()Worksheets (1).Cells (1, 1).Value = 24MsgBox “the value of the current cell A1 is 24“End SubExample fiveSub test5 ()MsgBox sets the formula for the cell and calculates the sum of the B2 to B5 cell regions“ActiveSheet.Cells
27、(2, 1).Formula = “=Sum (B1:B5)“End SubExample sixSub TEST6 ()MsgBox sets the formula in the cell C5“Worksheets (1).Range (“C5:C10“).Cells (1, 1).Formula = “=Rand ()“End Sub4. cell reference examplesSub Random ()Dim myRange As Rangeset a reference to the cell regionSet myRange = Worksheets (“Sheet1“)
28、.Range (“A1:D5“)operate on Range objectsMyRange.Formula = “=RAND ()“MyRange.Font.Bold = TrueEnd SubThe example shows: you can set the Range object variable to refer to the cell region, and then manipulate the cell region represented by the variable.5. clear cell examplesExample 1Clear the contents o
29、f the cell (ClearContents method)Sub testClearContents ()MsgBox clears the contents of the specified cell area“Worksheets (1).Range (“A1:H8“).ClearContentsEnd SubExample twoClear formatting in cells (ClearFormats method)Sub testClearFormats ()MsgBox “clear the format in the specified cell area.“Work
30、sheets (1).Range (“A1:H8“).ClearFormatsEnd SubExample threeClear the annotation in the cell (ClearComments method)Sub testClearComments ()MsgBox clears the annotation in the specified cell area“Worksheets (1).Range (“A1:H8“).ClearCommentsEnd SubExample fourClear all of the cells, including content,
31、format, and notation (Clear method)Sub testClear ()MsgBox “completely clear the specified cell area.“Worksheets (1).Range (“A1:H8“).ClearEnd Sub6. other examplesThe usage of Range and CellsSub test ()Set the border line style of the cell area A1:J10With Worksheets (1).Range (.Cells (1, 1), _.Cells (
32、10, 10).Borders.LineStyle = xlThickEnd WithEnd SubThe example shows that Range (cell1, cell2) can be used to return a Range object, where cell1 and cell2 are the Range objects of the specified starting and ending positions.Select cell area (Select method)Sub testSelect ()select cell region A1:D5Work
33、sheets (“Sheet1“).Range (“A1:D5“).SelectEnd SubDeviation from the selected region to another region (Offset attribute)Sub testOffset ()工作表(“Sheet1”激活) 。选择。偏移量(3, 1) 。选择端子示例说明:可用偏移(行,列) (其中排和柱为行偏移量和列偏移量返回相对于另一区域在指定偏移量处的区域如上例选定位于当前选定区域左上角单元格的向下三行且向右一列处单元格区域) 。选取距当前单元格指定行数和列数的单元格子 activecelloffice()本显示
34、距当前单元格第 3 列、第 2 行的单元格中的值”显示当前活动。偏移(3, 2)的价值。端子调整区域的大小(大小属性)子 resizerange()昏暗的 numrows 为整数,整数 numcolumns工作表(“Sheet1”激活) 。numrows = selection.rows.countnumcolumns = selection.columns.count选择。调整(numrows + 1,numcolumns + 1) ,选择端子示例说明:本示例调整所选区域的大小,使之增加一行一列。选取多个区域(联盟方法)子 testunion()昏暗的 rng1 RNG2 范围,范围,mym
35、ultiarearange 范围工作表(“Sheet1”激活) 。集 rng1 =范围(“A1:B2” )集 RNG2 =范围(“C3:D4” )集 mymultiarearange =联盟(rng1,RNG2)选择 mymultiarearange。端子示例说明:可用联盟(范围,范围,)返回多块区域,即该区域由两个或多个连续的单元格区域所组成。如上例创建由单元格区域A1 B2 C3:D4:和组合定义的对象,然后选定该定义区域。激活已选区域中的单元格子 activaterange()本选取单元格区域 B2:D6 并将 C4 选中”在当前工作表的范围(“B3:D6”选择) 。范围(“C5” )
36、。端子选取指定条件的单元格(specialcells 方法)子 selectspecialcells()本选择当前工作表中所有公式单元格”在当前工作表的单元格。specialcells(xlcelltypeformulas 选择)。端子选取矩形区域(currentregion 属性)“选取包含当前单元格的矩形区域“该区域周边为空白行和空白列子 selectcurrentregion()本选取包含当前单元格的矩形区域”activecell.currentregion.select端子选取当前工作表中已用单元格(当前属性)“选取当前工作表中已使用的单元格区域子 selectusedrange()本
37、选取当前工作表中已使用的单元格区域”_和 vbcrlf &“并显示其地址”activesheet.usedrange.select本 activesheet.usedrange.address端子7。动态数组ARR(19 至 8)这个数组的编号就是从- 19 开始的。那么它的最小编号就是- 19,最大编号是 8,如果用语句返回就是:子 t1()昏暗的 ARR(19 至 8)MsgBox UBound(ARR)的返回最大编号,结果为 8MsgBox LBound(ARR)的返回最小编号,结果为- 19端子如果是有行列组成的二维数组呢?二维数组返回行的下标和列的下标见下例子 t2()昏暗的 ARR
38、(19 到 8, 2 到 5)MsgBox UBound(ARR)的返回第 1 维(行的)最大编号,结果为 8MsgBox LBound(ARR)的返回第 1 维(行的)小编号,结果为- 19MsgBox UBound(ARR,2) returns the maximum number of second dimensions (columns), and the result is 5MsgBox LBound (arr, 2) returns the minimum number of second dimensions (columns), and the result is 2End SubSub T3 ()Dim arrThe number of rows and the number of rows of arr = Sheets (1).UsedRangeUsedrange are unknownMsgBox UBound (arr, 1) can calculate how many rows there are in this areaMsgBox UBound (arr, 2) can calculate how many columns there are in this areaEnd Sub