vba编程代码大全

VBA是一种用于Microsoft Office应用程序的编程语言,允许用户通过编写宏来自动化任务和增强功能。

Excel VBA 示例:

在单元格中显示消息框:

vba
Sub ShowMessage() MsgBox "Hello, World!", vbInformation, "Greeting" End Sub

循环处理工作表中的单元格:

vba
Sub LoopThroughCells() Dim cell As Range For Each cell In ActiveSheet.UsedRange ' 进行处理,例如: cell.Value = cell.Value * 2 Next cell End Sub

在新工作簿中创建图表:

vba
Sub CreateChart() Dim chartSheet As Chart Set chartSheet = Charts.Add chartSheet.SetSourceData Source:=Range("Sheet1!A1:B10") chartSheet.ChartType = xlColumnClustered End Sub

Word VBA 示例:

插入文本:

vba
Sub InsertText() Selection.TypeText Text:="Hello, World!" End Sub

创建表格:

vba
Sub CreateTable() Dim tbl As Table Set tbl = ActiveDocument.Tables.Add(Range:=Selection.Range, NumRows:=3, NumColumns:=3) End Sub

设置字体样式:

vba
Sub SetFontStyle() With Selection.Font .Bold = True .Italic = True .Color = RGB(255, 0, 0) ' 红色 End With End Sub

Access VBA 示例:

执行SQL查询:

vba
Sub RunQuery() DoCmd.OpenQuery "Query1" End Sub

创建新记录:

vba
Sub CreateRecord() DoCmd.GoToRecord , , acNewRec Me![FieldName] = "New Value" End Sub

打开表单:

vba
Sub OpenForm() DoCmd.OpenForm "CustomerForm" End Sub

PowerPoint VBA 示例:

创建新幻灯片:

vba
Sub AddSlide() ActivePresentation.Slides.Add Index:=2, Layout:=ppLayoutText End Sub

设置文本框内容:

vba
Sub SetTextBoxText() ActivePresentation.Slides(1).Shapes("TextBox1").TextFrame.TextRange.Text = "Hello, World!" End Sub

添加形状:

vba
Sub AddShape() ActivePresentation.Slides(1).Shapes.AddShape Type:=msoShapeRectangle, Left:=100, Top:=100, Width:=200, Height:=100 End Sub

Outlook VBA 示例:

创建新邮件:

vba
Sub CreateEmail() Dim outlookApp As Object Dim newEmail As Object Set outlookApp = CreateObject("Outlook.Application") Set newEmail = outlookApp.CreateItem(olMailItem) newEmail.Subject = "Subject" newEmail.Body = "Hello, World!" newEmail.To = "recipient@example.com" newEmail.Display End Sub

自动响应收件箱中的邮件:

vba
Sub AutoRespond() Dim item As Object For Each item In Application.Session.GetDefaultFolder(olFolderInbox).Items If TypeOf item Is MailItem Then If item.Subject = "Specific Subject" Then item.ReplyAll item.Body = "Thank you for your email." item.Send End If End If Next item End Sub