VBA Excel 2010.
This is only for user to select the excel files.
Private Sub OptionButton1_Click()
Set fd1 = Application.FileDialog(msoFileDialogFilePicker)
With fd1
.AllowMultiSelect = True
.Title = "Select the EXCEL FILES to extract."
.Filters.Clear
.Filters.Add "All Files", "*.*"
If .Show = False Then
End
End If
End With
And i have in:
Private Sub OptionButton2_Click()
strFilePath = Environ("Temp") & "\" & Format(Now, "DD.MM.YYYY HH.MM.SS")
MkDir strFilePath 'create a path to store selected email
Set ObjOL = CreateObject("Outlook.Application")
Set fd2 = Application.FileDialog(msoFileDialogFilePicker)
With fd2
.AllowMultiSelect = False
.Title = "Select CASH DIVISION EMAIL that contains attachment to extract."
.Filters.Clear
.Filters.Add "All Files", "*.*"
If .Show = True Then
SourceEmail2 = .SelectedItems(1)
End If
End With
Set msg = ObjOL.CreateItemFromTemplate(SourceEmail2)
msg.display
msg.Close olDiscard
So basically i have 10 Excel files, selected using the first FileDialog(fd1)
, and i have 1 email selected using fd2
.
fd1
and fd2
both declared public
the issue is when i run another subroutine:
For x = 1 To fd1.SelectedItems.Count
Workbooks.Open Filename:=fd1.SelectedItems(x)
'..code here..
Next x
Problem now is fd1.SelectedItems(x)
is now fd2.SelectedItems(x)
. Apparently fd1
is being overwritten by fd2
.
How to solve this?
答案 0 :(得分:1)
如下所示(虽然你真的想在最后打开Excel文件吗?)。这里的关键点是将Excel文件名加载到一个集合变量中并在子集之间传递,以便以后可以访问。
Option Explicit
Public Sub test()
two
three one
End Sub
Public Function one() As Collection
Dim fd1 As FileDialog
Set fd1 = Application.FileDialog(msoFileDialogFilePicker)
With fd1
.AllowMultiSelect = True
.Title = "Select the EXCEL FILES to extract."
.Filters.Clear
.Filters.Add "All Files", "*.*"
If .Show = False Then
End
End If
Dim col As Collection
Set col = New Collection
Dim i As Long
With fd1.SelectedItems
For i = 1 To .Count
col.Add .Item(i)
Next i
End With
Set one = col
End With
End Function
Public Sub two()
Dim strFilePath As String
strFilePath = Environ$("Temp") & "\" & Format$(Now, "DD.MM.YYYY HH.MM.SS")
MkDir strFilePath 'create a path to store selected email
Dim ObjOL As Object
Set ObjOL = CreateObject("Outlook.Application")
Dim fd2 As FileDialog
Set fd2 = Application.FileDialog(msoFileDialogFilePicker)
Dim SourceEmail2 As String
With fd2
.AllowMultiSelect = False
.Title = "Select CASH DIVISION EMAIL that contains attachment to extract."
.Filters.Clear
.Filters.Add "All Files", "*.*"
If .Show = True Then
SourceEmail2 = .SelectedItems(1)
End If
End With
Dim msg As Object
Set msg = ObjOL.CreateItemFromTemplate(SourceEmail2)
msg.display
' msg.Close olDiscard
End Sub
Public Sub three(ByVal col As Collection)
Dim x As Long
For x = 1 To col.Count
Workbooks.Open Filename:=col.Item(x)
'..code here..
Next x
End Sub