简体   繁体   English

通过VBA打开多个Non-Office文件

[英]Opening multiple Non-Office files through VBA

This macro is suppose to open multiple Hyperlinked CAD files in a list on an excel document. 假定此宏可以在Excel文档的列表中打开多个超链接的CAD文件。 I have to use this list (using excel cells, not a drop-down) for our infrastructure. 我必须在我们的基础架构中使用此列表(使用excel单元,而不是下拉列表)。

After the first instance is met and the first file opens, the code stops. 遇到第一个实例并打开第一个文件后,代码停止。 I think this is because when a non-office application is opened, the macro stops because excel is not the active application at that point. 我认为这是因为当打开非办公应用程序时,宏会停止,因为此时excel不是活动的应用程序。

Sub OpenCadFiles()

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Dim excel As Workbook
  Set excel = ActiveWorkbook

  Dim j As Long
  For j = 32 To 133 Step 1

      If ActiveSheet.Cells(j, 14).Value <> "" And Rows([j]).EntireRow.Hidden = False Then
          URL = Cells(j, 14).Text
          'ShellExecute "explorer.exe " & URL, vbNormalFocus
          ThisWorkbook.FollowHyperlink URL
          excel.Activate
      Else
      End If
  Next j

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

Are my assumptions correct, is this not possible to do in excel VBA? 我的假设正确吗,这在excel VBA中是不可能的吗? If not, does anyone know of a way to do this? 如果没有,有人知道这样做的方法吗?

The approach almost works. 该方法几乎可行。 You should use ActiveSheet (or Active anything) sparingly since the user could change applications while the macro runs. 您应该谨慎使用ActiveSheet(或Active),因为在宏运行时用户可以更改应用程序。 This is especially true if the macro takes a long time and the user checks his or her e-mail in the in meantime, for example. 例如,如果宏需要很长时间并且用户同时检查他或她的电子邮件,则尤其如此。 A better approach would be: 更好的方法是:

Sub OpenCadFiles()
  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Dim currentWorkbook As Workbook
  Set currentWorkbook = ActiveWorkbook

  Dim currentWorksheet As Worksheet
  Set currentWorksheet = ActiveSheet

  Dim URL As String
  Dim j As Long
  For j = 32 To 133
      If currentWorksheet.Cells(j, 14).Value <> "" And Rows([j]).EntireRow.Hidden = False Then
          URL = currentWorksheet.Cells(j, 14).Text
          currentWorkbook.FollowHyperlink URL
      End If
  Next j

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True
End Sub

By using currentWorkbook and currentWorksheet only once, you're guaranteed the correct references are always made. 通过仅使用currentWorkbook和currentWorksheet一次,可以确保始终进行正确的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM