我在修整范围内的单元格时遇到溢出错误。我得到错误的那一行是C.Value = .Trim(C.Value)
也许可以做到不相交?我尝试过不使用它,但是会导致不匹配错误。
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
任何帮助将不胜感激。
答案 0 :(得分:3)
.Select
或.Activate
您的工作簿/工作表。您声明了工作簿变量,以便使用它们!UsedRange
可能不可靠。我建议切换到更标准的最后一行计算。现在,该代码正在使用Column A
确定范围内所有列的最后一行,这反过来又确定了您要循环经过的范围。TRIM
调用VBA
函数。 请参阅下面@Tim Williams的评论,以确定VBA版本的Trim是否可接受
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
如果您只是修整值,则可以将范围加载到数组中,将值修改到新数组中,然后将新修整后的数组的值转移到范围中
答案 1 :(得分:0)
尝试一下。使用变体数组更快。
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