问题
I am getting an overflow error on my attempt to trim cells within my range. The line I get the error on is, C.Value = .Trim(C.Value) Perhaps this can be done without intersect? I've tried without it but it leads to mismatch error.
Dim masterWB As Workbook
Dim dailyWB As Workbook
Dim C As Range
Application.DisplayAlerts = False
'Set Current Workbook as Master
Set masterWB = Application.ThisWorkbook
'Set some Workbook as the one you are copying from
Set dailyWB = Workbooks.Open("excelguy.xlsm")
'Copy the Range from dailyWB and Paste it into the MasterWB
dailyWB.Sheets("Summary").Range("A1:BJ200").Copy masterWB.Sheets("Master Summary").Range("A1").Rows("1:1")
'formatting and paste as values
Workbooks("excelguy Master.xlsm").Activate
Worksheets("Master Summary").Select
'trim values
columns("A:BJ").Select
With Application.WorksheetFunction
For Each C In Intersect(columns("A:BJ"), ActiveSheet.UsedRange)
C.Value = .Trim(C.Value) 'Overflow Error
Next C
End With
Any help would be appreciated.
回答1:
- No need to
.Selector.Activateyour workbooks/sheets. You declared workbook variables so use them! UsedRangecan be unreliable. I recomend switching to a more standard last row calculation. Right now, the code is usingColumn Ato determine last row for all columns in your range, which in return determines the range you are going to loop through.- As stated by @dwirony, the
TRIMfunction can be called directly fromVBA.
Please see comment from @Tim Williams below to determine if the VBA version of Trim is acceptable
Option Explicit
Sub Test()
Dim masterWB As Workbook, dailyWB As Workbook
Dim C As Range, LRow As Long
Set masterWB = Application.ThisWorkbook
Set dailyWB = Workbooks.Open("excelguy.xlsm")
dailyWB.Sheets("Summary").Range("A1:BJ200").Copy masterWB.Sheets("Master Summary").Range("A1").Rows("1:1")
With masterWB.Sheets("Master Summary")
LRow = .Range("A" & .Rows.Count).End(xlUp).Row
For Each C In .Range("A2:BJ" & LRow)
C.Value = Trim(C)
'C.Value = Application.WorksheetFunction.Trim(C)
Next C
End With
End Sub
If you are just trimming the values, you could load your range into an array, modify the values into a new array, and then do a value transfer of your new trimmed array to a range
回答2:
Try this. To use Variant Array is faster.
Sub Test()
Dim masterWB As Workbook, dailyWB As Workbook
Dim C As Range, LRow As Long
Dim Ws As Worksheet
Dim rngDB As Range, vDB As Variant
Dim i As Long, j As Long
Set masterWB = ThisWorkbook
Set dailyWB = Workbooks.Open("excelguy.xlsm")
Set Ws = masterWB.Sheets("Master Summary")
dailyWB.Sheets("Summary").Range("A1:BJ200").Copy Ws.Range("A1")
Ws.Activate
With Ws
Set rngDB = .UsedRange
vDB = rngDB
For i = 1 To UBound(vDB, 1)
For j = 1 To UBound(vDB, 2)
vDB(i, j) = Trim(vDB(i, j))
Next j
Next i
rngDB = vDB
End With
End Sub
来源:https://stackoverflow.com/questions/53485664/vba-avoid-overflow-error-trim-worksheet-function