作者: littleboy 2023-10-27 10:22:13

VBA-简介

VBA 代表 Visual Basic for Aapplications,一种来自 Microsoft 的事件驱动编程语言

常见句式:

消息框

MsgBox 函数显示一个消息框并等待用户单击按钮,然后根据用户单击的按钮执行操作。

1
MsgBox(prompt[,buttons][,title][,helpfile,context])

输入框

InputBox 函数提示用户输入值。 输入值后,如果用户单击”确定”按钮或按键盘上的 ENTER 键,InputBox 函数将返回文本框中的文本。 如果用户单击”取消”按钮,该函数将返回一个空字符串 (“”)。

1
InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])

异常处理

VBA-异常处理(类比C#的try-catch),

1
2
3

On Error GoTo exitLine
exitLine:“跳转内容”

判断语句

if

1
2
3
4
If swApp Is Nothing Then
MsgBox ("未打开SOLIDWORKS")
Else: MsgBox ("已打开SOLIDWORKS")
End If

参考

Excel_SW

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
'定义全局变量
Dim swApp As Object
Dim swDoc As Object

'定义接口
Sub ConnectSW()
Set swApp = CreateObject("SldWorks.Application")
End Sub

'按钮事件
Private Sub CommandButton1_Click()

'调用接口
Call ConnectSW

'执行方法(新建零件的操作)
Set Part = swApp.NewDocument("C:\ProgramData\SolidWorks\SOLIDWORKS 2018\templates\零件.prtdot", 0, swSheetWidth, swSheetHeight)

End Sub

微软VBA手册

教程资源(w3schools.cn)

宏程序异常:重新安装和修复了.net和VC组件

Code Converter C# to VB and VB to C# – Telerik