首先,我是一个乞丐。欢迎任何建议!只是尝试在工作中编码以节省管理100个文件的时间。
我正在构建一个Excel宏,和其他许多用户一样,我正在尝试执行以下操作:
这在某种程度上会提示用户输入工作簿“C”,定义变量并将工作簿C放入其中。
以下代码是宏的一部分,只能在x中运行一次,显然是“崩溃”而没有警告或错误代码,甚至让我知道它已经崩溃。
'All the following code is in workbook "A"
Dim fd As FileDialog
Dim ffs As FileDialogFilters
Dim DestWkb As Workbook
Dim SourceWkb As Workbook
Dim SourceWkbPath As String
'Set active workbook as destination workbook (this is workbook "B")
Set DestWkb = ActiveWorkbook
'Prompt user for source workbook (this will be workbook "C")
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
Set ffs = .Filters
With ffs
.Clear
.Add "Excel", "*.xlsx"
End With
.AllowMultiSelect = False
If .Show = False Then Exit Sub
SourceWkbPath = fd.SelectedItems(1)
End With
'Here is where it starts to go wrong..
'This message box will show up with correct data in it :
MsgBox SourceWkbPath
'This line seems to work, as I can see in VB the workbook specified by the user
Set SourceWkb = GetObject(SourceWkbPath)
'From here... it's like there was an Exit Sub. I will rarely see the following msgbox :
MsgBox "Success"
有人已经遇到过这样的麻烦吗?非常感谢你!
答案 0 :(得分:0)
使用GetObject设置对已打开的外部应用程序的引用。以相同的方式使用CreateObject设置创建新的外部应用程序。
Dim fd As FileDialog
Dim ffs As FileDialogFilters
Dim SourceWkb As Workbook
Dim SourceWkbPath As String
Dim SourceWkbShortName As String
'Prompt user for source workbook (this will be workbook "C")
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
Set ffs = .Filters
With ffs
.Clear
.Add "Excel", "*.xlsx"
End With
.AllowMultiSelect = False
.Show
SourceWkbPath = fd.SelectedItems(1)
SourceWkbShortName = Mid(SourceWkbPath, InStrRev(SourceWkbPath, "\") + 1)
End With
On Error Resume Next
Set SourceWkb = Workbooks(SourceWkbShortName)
If Err.Number <> 0 Then
Set SourceWkb = Workbooks.Open(SourceWkbPath)
End If
On Error GoTo 0
MsgBox """Hello World!""", vbInformation, SourceWkb.Name & " Says:"
&#13;
MSDN说:ThisWorkbook总是返回运行代码的工作簿。
问题是:&#34;如果WorkBook A在工作簿B中运行宏,那么ThisWorkBook会引用什么?
WorkBook A
Sub RunExternalCode()
WorkBookAName= ThisWorkBook.Name
WorkBookBName = Application.Run ""
End Sub
WorkBook B
Function GetThisWorkBooksName()
GetThisWorkBooksName = ThisworkBook.Name
End Function
结果:
WorkBookAName =&#34; WorkBookA&#34;
WorkBookBName =&#34; WorkBookB&#34;