如何使用VBA格式化已关闭的Excel工作表

时间:2012-06-13 13:17:38

标签: vba excel-vba excel-2007 excel

我有关闭的sheet1.xls。我在sheet2.xls VBA中工作如下。

With Range("A:XFD")
 <I need Some Code here to format entire sheet1.xls cells into string format> 
End With

Kinldy help.Thanks

3 个答案:

答案 0 :(得分:1)

这样的东西可以让你格式化已关闭的书。它打开然后格式化然后再次关闭。

Option Explicit
Public Sub Format_Closed_Sheet()
    Dim sht1book As Workbook
    Dim sht1ws As Worksheet
    Dim strValue As String
    Dim rng As Range

    Application.ScreenUpdating = False

    With Application

    '--> Open sheet1.xls
    Set sht1book = .Workbooks.Open _
    ("Path to Sheet1.xls")
    End With

    Set sht1ws = sht1book.Sheets("Sheet1")

    '--> Format the range as text

    Set rng = sht1ws.Range("A:XFD")
    rng.NumberFormat = "@"

    '--> Save sheet1.xls and close
    Application.DisplayAlerts = False
    sht1book.Save
    sht1book.Close
    Application.DisplayAlerts = True

    Application.ScreenUpdating = True
End Sub

答案 1 :(得分:1)

我就是这样做的:

Dim b As Workbook
Dim sh As Worksheet

Set b = Workbooks.Open("C:\mypath\mybook.xls") ' or wherever your workbook is

Set sh = b.Sheets("Sheet1") ' or whatever sheet
sh.Cells.NumberFormat = "@" ' format as Text

b.Close

如果要将工作簿中所有工作表的格式设置为文本,可以执行以下操作:

For Each sh In wb.Sheets
    sh.Cells.NumberFormat = "@" ' format as Text
Next sh

答案 2 :(得分:0)

只需声明工作簿和工作表:

dim oBook as excel.workbook
dim oSheet as excel.worksheet

set oBook = workbooks.open("<workbook path and filename>")
set oSheet = oBook.sheets("<SheetName>")

然后:

with oSheet.range("A:XFD") 
     <Format>
end with
oBook.close
set oBook = nothing 
set oSheet = nothing

等等。