【发布时间】:2021-06-07 19:38:34
【问题描述】:
我有以下函数(VBA 代码),我通常在一些 Excel 宏中使用。它允许我列出我打开的工作簿并选择其中之一。效果很好。
Function PromptForWorkbook() As String
Dim N As Long
Dim s As String
Dim WB As Workbook
For Each WB In Workbooks
N = N + 1
s = s & CStr(N) & " - " & WB.Name & vbNewLine
'CStr deve converter o número N numa string
Next WB
N = Application.InputBox( _
prompt:="Select the source data excel file, by the ID number:" & _
vbNewLine & s, Type:=1)
If N <= 0 Or N > Workbooks.Count Then
PromptForWorkbook = vbNullString
Else
PromptForWorkbook = Workbooks(N).Name
End If
End Function
现在,我想调整上面的代码以从 PowerPoint 宏 运行它,目的相同,即有一个 PowerPoint 宏允许我选择一个在我打开的几个 Excel 工作簿中。这是我到目前为止所做的,但您可能会猜到它无法正常工作。与 Excel 宏相比,Powerpoint 宏中的不同之处之一是 InputBox 函数,它在 Excel 中可以返回一个数字,而在 Powerpoint 中只返回字符串。我适应了,但它仍然不起作用。它甚至没有列出我打开的 Excel 文件。
Function PromptForWorkbook() As String
Dim N As Long
Dim s As String
Dim myString As String
Dim WB As Workbook
For Each WB In Workbooks
N = N + 1
s = s & CStr(N) & " - " & WB.Name & vbNewLine
'CStr deve converter o número N numa string
Next WB
myString = InputBox( _
prompt:="Select the source data excel file, by the ID number:" & _
vbNewLine & s)
N = CInt(myString)
If N <= 0 Or N > Workbooks.Count Then
PromptForWorkbook = vbNullString
Else
PromptForWorkbook = Workbooks(N).Name
End If
End Function
有人可以帮我吗?
提前致谢
【问题讨论】:
-
您需要一个对 Excel 实例的引用...您可以使用
GetObject来获取对现有实例的引用。 -
你能给我看一个带有示例代码的例子吗?
-
我链接到的文档中有一个代码 sn-p。网上也有很多类似的例子。
-
使用 N = Clng(myString) 代替 N = CInt(myString) var 类型正确)。在进行转换之前,您还需要测试 Len(myString) > 0,因为空白的 myString 会引发错误。
标签: excel vba powerpoint