简体   繁体   中英

MS Access VBA format Excel

Hi I am trying to format an excel spread sheet created by my MS access macro. I wanted to select rows with only values in it. So for example I want to select the first row and text wrap it

I thought this logic would work, but gives me error 1004 (Application-defined or Object defined Error)

Dim my_xl_app As Object
Dim my_xl_workbook As Object

Set my_xl_app = CreateObject("Excel.Application")
Set my_xl_workbook = my_xl_app.Workbooks.Open(C:\PATH)

For x = 1 To 23
my_xl_workbook.sheets(x).Range("A1",my_xl_workbook.sheets(x).Range("A1").End(xlToright)).WrapText = True
Next x

my_xl_workbook.Sheets(x).Range("A1", my_xl_workbook.Sheets(x).Range("A1").End(xlToRight)).WrapTex‌​t = True is what is being highlighted when I press debug

Thanks in advance

You are probably not closing properly the file, thus it stays opened and unvisible. Check in your task manager how many excel files do you have opened. Try to close them all. Furthermore, you refer to xlToRight , which is member of the MS Excel Object Library , which is not present in your application.

Thus, try the following:

Public Sub TestMe()

    Dim x               As Long
    Dim my_xl_app       As Object
    Dim my_xl_workbook  As Object

    Set my_xl_app = CreateObject("Excel.Application")
    Set my_xl_workbook = my_xl_app.Workbooks.Open("C:\Users\v.doynov\Desktop\file.xlsx")

    my_xl_app.Visible = True

    For x = 1 To my_xl_workbook.Sheets.Count
        With my_xl_workbook.Sheets(x)
            .Range("A1", .Range("A1").End(xlToRight)).WrapText = True

            Debug.Print "Wrapping " & .Range("A1", .Range("A1").End(-4161)).Address & _
            " From " & .Range("A1", .Range("A1").End(-4161)).Parent.Name

        End With
    Next x

    my_xl_workbook.Save
    my_xl_workbook.Close (True)

End Sub

This is how I found -4161 . Add a reference to MS Excel 14.0 Object Library in the Visual Basic Editor.

在此处输入图片说明

Then in the immediate window write ?xlToRight . Thats quite enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM