首页 > 解决方案 > VBA: Check if files exist

问题描述

I'm creating a PowerPoint presentation which gets data and slides from different Excel and PowerPoint files. The basic code works, now I have to clean it up and deal with issues like "what if the file doesn't exist?"

In this regard I need some advice. I want two things to happen: I want the user to know about the missing files, but also that the code continues executing (one missing file shouldn't derail the whole macro). How do I do this in a clean/readable way?

My idea would be to check if the files exist before the actual code with something like

If Dir("File Path") = "" Then
   MsgBox "File doesn't exist"

However, in this case I also need the macro to skip the part of the code with the missing file(s). In the initial check I could create a variable like File1Exists = True, that switches to False if the file doesn't exist. And then for each part of code/each sub, I could do an If-statement to check if this condition is true or not.

That should work, but is that really the best solution? Seems like a bunch of code for such a simple issue. Does anyone have a better idea?

标签: excelvbapowerpoint

解决方案


Something like:

Dim file_exists as Boolean
file_exists = (Dir("File Path") <> "")

If file_exists Then
  ....
Else
  ....
End If

推荐阅读