用户输入多列

时间:2017-03-27 16:31:49

标签: excel vba excel-vba

我试图允许用户定义从中提取数据的多个列。这些列不相邻,即列“A”,“D”,“H”,“P”中有数据。这只是一个例子,每个用户的相关列将有所不同。使用这样的东西:

dim data_col as range
dim data_col_1 as integer

set data_col = application.inputbox("Select your columns", Type:= 8 )

data_col_1 = data_col.column

仅返回范围中的第一个(最左侧)列索引。我需要一种方法将这个输入分成多个列索引,或者分成许多不同的变量或数组。

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

尝试下面的代码,它将循环遍历您的所有Areas,并且每个区域将遍历所有列,并将在data_col_Arr数组中输入它们的数字。

Option Explicit

Sub RangetoColumns()

Dim data_col As Range
Dim data_col_Arr() As Long
Dim Area As Range
Dim Col As Range
Dim i As Long

Set data_col = Application.InputBox("Select your columns", Type:=8)

ReDim data_col_Arr(1 To 1000)  ' init to large size >> will optimize at the end
i = 1
Dim MsgStr  As String
For Each Area In data_col.Areas
    For Each Col In Area.Columns
        data_col_Arr(i) = Col.Column
        MsgStr = MsgStr & data_col_Arr(i) & vbCr ' <-- for Debug Only
        i = i + 1
    Next Col
Next Area

ReDim Preserve data_col_Arr(1 To i - 1) 'Redim array size to number of columns populated
MsgBox MsgStr ' <-- for Debug Only

End Sub