2017-01-27 6 views
0

시각적 기본 응용 프로그램 내에서 Excel 스프레드 시트의 행 높이 및 열 너비를 설정하는 데 실패했습니다.Visual Basic with excel

나는 내 클립 보드에 데이터가있는 시각적 기본 응용 프로그램이 있습니다. 이 코드를 Excel의 인스턴스에 복사 한 다음 결과 스프레드 시트를 저장하고 Excel을 닫은 다음 Excel을 닫습니다. 프로그래밍 방식으로 스프레드 시트를 저장하기 전에 행 높이와 셀 너비를 설정하려고했지만 그렇게 할 수 없었습니다. , oSheet.Selection.RowHeight = 11.4, 및 oSheet.Cells.EntireColumn.AutoFit() 라인

If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then 
    Dim oXL As Excel.Application 
    Dim oWB As Excel.Workbook 
    Dim oSheet As Excel.Worksheet 
    oXL = CreateObject("Excel.Application") 
    oXL.Visible = True 
    oWB = oXL.Workbooks.Add 
    oSheet = oWB.ActiveSheet 

    oSheet.Paste() 
    oSheet.Cells.Select() 
    oSheet.Selection.RowHeight = 11.4 
    oSheet.Cells.EntireColumn.AutoFit() 
    oSheet = Nothing 
    oWB.Close(True, SaveFileDialog1.FileName) 
    oWB = Nothing 
    oXL.Quit() 
    oXL = Nothing 
    MsgBox("Finished!") 
End If 

응용 프로그램은 oSheet.Cells.Select()없이 실행 : 이것은 내가 실행하고 코드입니다. 이 줄을 사용하면 다음과 같은 오류 메시지가 나타납니다.

'워크 시트'형식의 공용 멤버를 찾을 수 없습니다.

Visual Studio에서 프로그램을 추적하면 oSheet.Paste() 명령이 실행되고 oSheet.Cells.Select() 명령이 실행됩니다. oSheet.Selection.RowHeight = 11.4 명령을 실행하려고하면 예외가 생성됩니다.

도움을 주시면 감사하겠습니다.

조나단

+1

보십시오이'oSheet.Rows ("1 : 1") rowHeight를 = 11.4'도'oSheet.Cells.Select()가' – Codexer

+0

당신이'그것의 .Select'를 사용하려고한다면 제거합니다. [매우 피하는 것이 좋습니다] (https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros), 그냥'.Select' 일 것입니다. '.Select()'. – BruceWayne

+0

@Zaggler - 나는 당신의 제안을 시도했다. 오류 메시지가 더 이상 표시되지 않지만 결과 스프레드 시트에 높이가 11.4 인 행이없고 열이 자동으로 채워지지 않습니다. 다른 제안? –

답변

0

다음은, 런타임에 바인딩되지는 초기 바인딩입니다하지만 패턴이 마이너 코드 변경없이 작동합니다.

Option Strict On 
Imports Excel = Microsoft.Office.Interop.Excel 
Imports System.Runtime.InteropServices 
Imports System.IO 

Public Class Operations 
    Public HasError As Boolean 
    Public ErrorMessage As String 
    ''' <summary> 
    ''' 
    ''' </summary> 
    ''' <param name="FileName">Path and file name for Excel file</param> 
    ''' <param name="SheetName">Sheet name to work on</param> 
    ''' <param name="RowHeight">Used to set row height in SheetName</param> 
    ''' <returns></returns> 
    Public Function SetWidthHeight(
     ByVal FileName As String, 
     ByVal SheetName As String, 
     ByVal RowHeight As Integer) As Boolean 

     If 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 

       Marshal.FinalReleaseComObject(xlWorkSheet) 
       xlWorkSheet = Nothing 

      Next 
      If Proceed Then 

       xlCells = xlWorkSheet.Cells 
       xlCells.PasteSpecial() 

       Dim EntireRow As Excel.Range = xlCells.EntireRow 
       ' 
       ' Set row height 
       ' 
       EntireRow.RowHeight = RowHeight 
       Dim ColRange = xlCells.EntireColumn 
       ' 
       ' Auto fit all columns 
       ' 
       ColRange.AutoFit() 
       ReleaseComObject(ColRange) 

       ReleaseComObject(xlCells) 
       ReleaseComObject(EntireRow) 

      Else 
       HasError = True 
       ErrorMessage = 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 
      HasError = True 
      ErrorMessage = "'" & FileName & 
       "' not located. Try one of the write examples first." 
     End If 

     Return HasError 
    End Function 
    Private Sub ReleaseComObject(ByVal excelObject As Object) 
     Try 
      If excelObject IsNot Nothing Then 
       Marshal.ReleaseComObject(excelObject) 
       excelObject = Nothing 
      End If 
     Catch ex As Exception 
      excelObject = Nothing 
     End Try 
    End Sub 
End Class