2015-06-07 62 views
0

我正在嘗試創建一個VBA腳本,用於更改保存在一個文件夾中的多個工作簿中的字體。但是,它不起作用。請看看代碼Excel 2010:幫助更改多個工作簿中的字體

Sub changefont() 
Dim wb As Workbook, sh As Worksheet, fpath As String, fname As String 
fpath = "D:\reports" 
If Right(fpath, 1) <> "\" Then fpath = fpath & "\" 
fname = Dir(fpath & ".xls") 
Do 
On Error Resume Next 
Set wb = Workbooks.Open(fname) 
Set sh = wb.Sheets("REPORT") 
On Error GoTo 0 
If Not sh Is Nothing Then 
With sh.Range(Cells(10, 1), Cells(90, 11)) 
.Font.Size = "18" 
.Font = "Arial" 
End With 
End If 
wb.Close True 
fname = Dir 
Loop While fname <> "" 
End Sub 

注:我的工作表Sheet1被命名爲報告中的所有工作簿

+0

請修復縮進。 –

回答

0

試試這個(未經檢驗)。我已在相關部分添加了評論。如果您發現錯誤或有任何問題,請告訴我。

Sub changefont() 
    Dim wb As Workbook, sh As Worksheet 
    Dim fpath As String, fname As String 

    fpath = "D:\reports" 

    If Right(fpath, 1) <> "\" Then fpath = fpath & "\" 

    fname = Dir(fpath & ".xls") 

    Do While fname <> "" 
     Set wb = Workbooks.Open(fname) 

     '~~> This is important 
     Set sh = Nothing 

     On Error Resume Next 
     Set sh = wb.Sheets("REPORT") 
     On Error GoTo 0 

     If Not sh Is Nothing Then 
      '~~> You need to fully qualify the cells object 
      With sh.Range(sh.Cells(10, 1), sh.Cells(90, 11)) 
       '~> Font Size is not a string 
       .Font.Size = 18 
       '~~> Add .Name 
       .Font.Name = "Arial" 
      End With 

      wb.Close True 
      DoEvents 
     Else 
      wb.Close False 
     End If 

     fname = Dir 
    Loop 
End Sub 
+0

嗨,@ siddharth-rout感謝您的幫助,但它不工作。 – Suhel

相關問題