2016-07-18 7 views
0

フォルダ内に異なる名前を持つ200個のフォルダがあります。今、別の名前を持つ各フォルダには、マクロのExcelファイル(.xlsm)があります。私は別のファイルで一度にすべてのファイルを編集しようとしています。コードは次のようになります。1つのフォルダに複数の異なるフォルダにある複数のExcelファイルを編集する

Sub Button1_Click() 

Dim wb  As Workbook 
Dim ws  As Excel.Worksheet 
Dim strPath As String 
Dim strFile As String 

'Get the directories 
strPath = "C:\Users\generaluser\Desktop\testing main folder\" 
strFile = Dir(strPath) 

'Loop through the dirs 
Do While strFile <> "" 

    'Open the workbook. 
    strFileName = Dir(strPath & strFile & "*.xlsm") 
    'Open the workbook. 
    Set wb = Workbooks.Open(Filename:=strPath & strFile & "\" & strFileName , ReadOnly:=False) 

    'Loop through the sheets. 

    Set ws = Application.Worksheets(1) 

    'Do whatever 
    ws.Range("A1").Interior.ColorIndex = 0 



    'Close the workbook 
    wb.Close SaveChanges:=True 

    'Move to the next dir. 
    strFile = Dir 
Loop 

End Sub 

これは機能しません。私はそれを調整しようとしましたが、私は何もしないか、エラーを引き起こします。誰かがこのコードを動作させる手助けをしてくれますか? (また、 "testing main folder"は、.xlsmファイルを保持する200個の他のフォルダを保持する私のデスクトップ上のフォルダです)

+0

[この回答](http://stackoverflow.com/questions/22645347/loop-through-all-subfolders-using-vba)があなたを助けますサブフォルダをループする方法を理解する。 –

+1

[ユーザー指定のルートディレクトリ内のサブフォルダとファイルを循環する](http://stackoverflow.com/questions/14245712/cycle-through-sub-folders-and-files-in-a-user)の可能な複製-specified-root-directory) – Comintern

答えて

0

Option Explicitをモジュールの先頭に置きます。いくつかのコンパイルエラーが発生し、そのうちの1つはstrFileNameが宣言されていないということです。このとなります。問題が読んだときにおおよそ同じ意味を持つ2つの変数名を使用していて、混乱しているためです。

変数の修正が完了したら、Dir functionのドキュメントをご覧ください。 2番目の問題は、ループ内でDirを複数回呼び出していることです。つまり、結果をスキップしています。

それはより多くのこのようなものになります。

Dim wb As Workbook 
Dim ws As Excel.Worksheet 
Dim file As String 

'path never changes, so make it a Const 
Const path = "C:\Users\generaluser\Desktop\testing main folder\" 
'This returns the first result. 
file = Dir$(path & "*.xlsm") 

Do While file <> vbNullString 
    Set wb = Workbooks.Open(Filename:=path & file, ReadOnly:=False) 
    Set ws = Application.Worksheets(1) 
    'Do whatever 
    wb.Close SaveChanges:=True 
    'This returns the next result, or vbNullString if none. 
    file = Dir$ 
Loop 
+0

これはまだ**サブフォルダ内の '.xlsm'ファイルを開きません** –

+0

@ScottHoltzman - 質問のサブフォルダについては何も見ませんでしたが、1つのディレクトリを反復する方法を理解しています確かに正しい方向への一歩。 – Comintern

+0

質問の最初の2つの文をもう一度読んでください。 –

関連する問題