0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ExcelVBAで「人によってファイルパスが違う問題」の解決法

Posted at

事例

複数人で使用するExcelツールを作る場面でたまに遭遇するのが、
共有フォルダにある「example.txt」をExcelツールから参照したいが、PCによってファイルパスが異なるというケース。

(例)PC1:  C:\Folder1\example.txt
   PC2:  D:\AnotherFolder\example.txt

対応策

Windowsの「環境変数」の設定をつかう方法がある。

(1)事前設定

各PCで参照するフォルダ(C:\Folder1やD:\AnotherFolder)に対して、共通の環境変数名を設定する。

【手順】
Windowsの「環境変数」を開く。
変数名を「MyTools」などに設定し、フォルダパスを登録する。
(このあたりの設定方法は「パスを通す」などで検索すると詳しい解説あり)

小規模の部署であれば、個別にデスクを回って設定させてもらうのがよいと思います

(2)ExcelVBAでのファイル参照方法

Environ("環境変数名")で、事前設定したフォルダパスを取得できる。

Sub sample()
    Dim folderPath As String
    Dim fullPath As String

    ' 環境変数「MyTools」からフォルダパスを取得
    folderPath = Environ("MyTools")

    ' フルパスを作成
    fullPath = folderPath & "\example.txt"
End Sub

補足

OneDriveのフォルダはあらかじめ環境変数に設定されているので、事前設定せずにEnviron("OneDrive")で参照できる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?