我试图将整个Excel工作表格式化为所有单元格的宽度和高度相同。
以下代码不起作用,但也不会出错:
transposeSheet.Cells.UseStandardHeight = 15
transposeSheet.Cells.UseStandardWidth = 15
有很多代码用于执行单个范围,但我找不到如何将整个工作表设置为指定的高度和宽度。
答案 0 :(得分:1)
注意我刚刚在以下内容中创建了MSDN code sample。
这是一个确保正确处理所有对象的示例,这就是为什么我们可以使用更少的代码执行此操作的原因,其中很多代码可以通过网络来完成工作,但会留下un的残余 - 计算机内存中的处理对象有时如果幸运将在应用程序关闭时处理,而不是其他时间。
致电示例
Dim FileName As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WorksheetsTest.xlsx")
Dim SheetName As String = "Sheet1"
SetWidthHeight(FileName, SheetName, 10, 50)
上面的代码模块
Option Strict On
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Module OpenWorkSheets4
Public Sub SetWidthHeight(ByVal FileName As String, ByVal SheetName As String, ByVal RowHeight As Integer, ByVal ColumnHeight As Integer)
If IO.File.Exists(FileName) Then
Dim Proceed As Boolean = False
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
Dim xlCells As Excel.Range = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
Proceed = True
Exit For
End If
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
If Proceed Then
xlCells = xlWorkSheet.Cells
Dim EntireRow As Excel.Range = xlCells.EntireRow
EntireRow.RowHeight = RowHeight
EntireRow.ColumnWidth = ColumnHeight
ReleaseComObject(xlCells)
ReleaseComObject(EntireRow)
Else
MessageBox.Show(SheetName & " not found.")
End If
xlWorkSheet.SaveAs(FileName)
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
Else
MessageBox.Show("'" & FileName & "' not located.")
End If
End Sub
Private Sub ReleaseComObject(ByVal obj As Object)
Try
If obj IsNot Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
End If
Catch ex As Exception
obj = Nothing
End Try
End Sub
End Module
答案 1 :(得分:0)
您想要使用以下
Cells.Select // Selects all cells on active sheet
Selection.RowHeight = Yournumberhere // Changes height of selected rows
Selection.ColumnWidth = Yournumberhere // Changes width of selected columns