简体   繁体   中英

Opening multiple Non-Office files through VBA

This macro is suppose to open multiple Hyperlinked CAD files in a list on an excel document. I have to use this list (using excel cells, not a drop-down) for our infrastructure.

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.

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? 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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