如何在VBA excel 2010脚本中根据用户selectselect数据而不丢失原始数据?
我想做一个VBA
文件,从用户input2
或3
的Excel:
-
如何在打开
xslm
文件时运行它? -
假设我在我的文件中有这个表:
common data
对A
列B
和C
列唯一内容非常有用。 我想使用下面的代码,所以取决于用户input,它将从A
, B
或C
select唯一的数据到A's
唯一数据的位置。 但是我希望列A的数据可以重复使用,以便将来使用,例如,如果用户将提供input_num=1
那么数据将是A's
unique data
Sub main() MsgBox ("welcome") Dim input_num As Integer input_num = InputBox(Prompt:="please select device", Title:="select device", Default:=3) If input_num = 1 Then ' use the first column ElseIf input_num = 2 Then ' use the second column Else ' use the third column End If End Sub
1. How can I run it while opening the xlsm file ? 2. Using the column based on User input
要在Excel文件启动时运行代码,您可以使用
Private Sub Workbook_Open() End Sub
你将放在这里的任何代码将运行提供的macros在您的文件中启用。 例如,当您打开具有以下代码的文件时,您将看到一个消息框“Hello World”。
Private Sub Workbook_Open() MsgBox "Hello World" End Sub
Workbook_Open()
进入工作簿代码区域,如下面的截图所示
现在关于你的第二个问题
在Excel中,不仅可以通过名称引用列,还可以引用数字,例如
列A可以被称为
Sheets("Sheet1").Columns("A:A")
要么
Sheets("Sheet1").Columns(1)
这使您的工作更容易,因为您现在可以根据用户input直接参考列。 例如
Private Sub Workbook_Open() MsgBox "welcome" Dim input_num As Variant input_num = InputBox(Prompt:="please select device", _ Title:="select device", Default:=3) Select Case input_num Case 1, 2, 3 With Sheets("Sheet1").Columns(Val(input_num)) ' '~~> Do what ever you want ' End With End Select End Sub