如何在VBA excel 2010脚本中根据用户selectselect数据而不丢失原始数据?

我想做一个VBA文件,从用户input23的Excel:

  1. 如何在打开xslm文件时运行它?

  2. 假设我在我的文件中有这个表:

在这里输入图像说明

common dataABC列唯一内容非常有用。 我想使用下面的代码,所以取决于用户input,它将从ABCselect唯一的数据到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