VBA query - Macro to truncate no. chars in cells

Rags

Board Regular
Joined
Oct 25, 2006
Messages
202
Hi

I use the below code to truncate the number of characters in cells on a worksheet. It works well with only one workbook open.

Code:
Sub Truncate()
    Application.ScreenUpdating = False

    Dim LastHeader As Long
    Dim Cell As Range
    LastHeader = Range("IV1").End(xlToLeft).Column
    
    For Each Cell In Application.Intersect(Sheet1.UsedRange, Columns("A:AO"))
        Cell.Value = Left(Cell.Value, 80)
    Next Cell

    Application.ScreenUpdating = True

End Sub

My problem is that I need to run it on a worksheet in a different workbook. How can I specify which workbook & sheet? Currently it only works when the macro is within a module in the active workbook.

I've tried various things - adding Activeworkbook, Worksheets("Data") etc to the 'For Each Cell In Application.....' line but nothing has worked yet.

Thanks in advance

Rags
 

Excel Facts

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
Not a good habit to use Excel reserved words as variables ("Cell") so I have changed that.

** UNTESTED**
Code:
Sub Truncate()
    Dim LastHeader As Long
    Dim MyCell As Range
    Dim ws As Worksheet
    '----------------------------------------------------
    Set ws = Workbooks("Book1.xls").Worksheets("Sheet1")
    '-----------------------------------------------------
    Application.ScreenUpdating = False
    LastHeader = Range("IV1").End(xlToLeft).Column
    '- loop
    For Each MyCell In Application.Intersect(ws.UsedRange, Columns("A:AO"))
        MyCell.Value = Left(MyCell.Value, 80)
    Next MyCell
    '-
    Application.ScreenUpdating = True
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,833
Messages
6,121,869
Members
449,054
Latest member
juliecooper255

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top