多选vba

时间:2017-09-29 09:58:00

标签: excel vba excel-vba

下面是我打开多个文件然后对它们采取一些操作的代码。我只提到需要帮助的部分。

Sub Sample()
Dim myFile As Variant
Dim i As Integer

myFile = Application.GetOpenFilename(MultiSelect:=True)

If IsArray(myFile) Then 
    For i = LBound(myFile) To UBound(myFile)
    Set mywkbook= Workbooks.Open(myFile(i))
    Next i
End If
End Sub

这很好用。 但是我想要" mywkbook"变量为不同的工作簿具有不同的值,以便我可以处理它们。 请帮忙

3 个答案:

答案 0 :(得分:0)

一个标量变量不能同时具有不同的值,因此您必须使用数组。您可以通过修改代码来实现此目的:

Sub Sample()

  Dim myFile As Variant
  Dim i As Integer
  Dim mywkbooks() as Workbook

  myFile = Application.GetOpenFilename(MultiSelect:=True)

  If IsArray(myFile) Then 

    For i = LBound(myFile) To UBound(myFile)
    Set mywkbooks(i) = Workbooks.Open(myFile(i))
    Next i

  End If

End Sub

答案 1 :(得分:0)

希望这可以通过确定,这是我在这个论坛上的第一个答案。

Sub tryThis()

Dim myFile As Variant
Dim i As Integer
Dim workbookNames() As String ' define a empty string array variable to hold the file names

myFile = Application.GetOpenFilename(MultiSelect:=True)

If IsArray(myFile) Then
    For i = LBound(myFile) To UBound(myFile)
        Workbooks.Open (myFile(i))   ' Just open the workbook here
        ReDim Preserve workbookNames(i) ' ReDim redefines your array to 'i' number of elements.  Preserve ensures you don't lose the previous values held in the Array
        workbookNames(i) = ActiveWorkbook.Name ' Assign the Name of the Workbook to the Array
            MsgBox workbookNames(i) ' you don't need this, I just used it to demonstrate that you now have the file name and can work with it
    Next i
End If

End Sub

编辑:我和'Binarus'在同一时间关系到这个。我喜欢他们声明工作簿数组的方法,但你需要在'设置mywkbooks(i)之前添加以下行,否则你会得到一个下标超出范围的错误,因为数组是空的并且还不能保存任何值。

ReDim保留mywkbooks(i)

答案 2 :(得分:0)

我的工作方式有点像这样:

Dim paths(), wbs() As Workbook
Dim x As Integer

paths = Application.GetOpenFilename(FileFilter:="Excel Files 
(*.XLSX),*.XLSX", MultiSelect:=True)


  For x = 1 To UBound(paths)
  ReDim wbs(UBound(paths))
 Set wbs(x) = Workbooks.Open(paths(x))

   With wbs(x).Sheets("Sheet1")

  lastrow = .Range("A" & .Rows.Count).End(xlUp).Row

.Range("A2:X" & lastrow).Copy newexcel.Sheets("RawData").Range("A" & 
newexcel.Sheets("RawData").Rows.Count).End(xlUp).Offset(1)

 End With
 Next x

发布我的答案,以便将来可以帮助某人:)