下面的代码在工作表中循环,并将指定范围更改为数字格式,然后将该范围乘以常量以删除以文本格式存储的数字。
我遇到的问题是,它将整个范围乘以1,从而在范围之后留下一串空零。
我尝试创建一个找到最后一行的变量,但无济于事,尾随零仍然存在。感谢您的帮助。
Sub copy_paste()
Dim ws As Worksheet
Dim rConst As Range
Dim lrow As Long
Application.ScreenUpdating = False
Set rConst = Cells(40, 40)
rConst = 1
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "GA_AVERAGE" Then
lrow = Cells(Cells.Rows.Count, "A").End(xlUp).Row
ws.Range("D1:F" & lrow).NumberFormat = "0"
ws.Range("M1:N" & lrow).NumberFormat = "0"
rConst.Copy
ws.Range("D1:F" & lrow).PasteSpecial xlPasteValues, xlPasteSpecialOperationMultiply
ws.Range("M1:N" & lrow).PasteSpecial xlPasteValues, xlPasteSpecialOperationMultiply
End If
Next ws
rConst.Clear
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:2)
尝试一下:
Sub test()
Dim wb As Excel.Workbook
Dim ws As Worksheet
Dim lrow As Long
Dim rng As Range
Application.ScreenUpdating = False
Set wb = Workbooks("Book1") 'change to your workbook name
For Each ws In wb.Worksheets
If ws.Name <> "GA_AVERAGE" Then
lrow = ws.Cells(ws.Cells.Rows.count, "A").End(xlUp).row
Set rng = ws.Range("D1:F" & lrow & ", " & "M1:N" & lrow)
rng.NumberFormat = "0"
For Each cel In rng
If cel.Value <> vbNullString Then cel.Value = cel.Value * 1
Next
Set rng = Nothing
End If
Next ws
Application.ScreenUpdating = True
End Sub
/ e:我建议您还设置一个工作簿,以确保您引用了correst工作簿和工作表;编辑了代码
/ e2:我明白您在这里所做的!对于大型电子表格,您的方法要高效得多。下面是完成此操作的另一种方法,虽然丑陋但可行,所有注释均已说明。此方法将保留现有的零并将其转换为数字,并且不会创建新的不需要的零:
Sub test()
Dim wb As Excel.Workbook
Dim ws As Worksheet
Dim lrow As Long
Dim rng As Range
Dim tempStr As String, origVal As String
Application.ScreenUpdating = False
Set wb = Workbooks("Book3") 'change to your workbook name
tempStr = "tempStr"
For Each ws In wb.Worksheets
If ws.Name <> "GA_AVERAGE" Then
lrow = ws.Cells(ws.Cells.Rows.count, "A").End(xlUp).row
Set rng = ws.Range("D1:F" & lrow & ", " & "M1:N" & lrow)
With rng
'first, replace original blank cells with random string to keep them blank, otherwise they will appear as 0
.Replace What:=vbNullString, Replacement:=tempStr
'change format to number
.NumberFormat = "0"
'remember value to retrieve it later
origVal = ws.Range("A1").Value
'this is the value used for xlPasteSpecialOperationMultiply
ws.Range("A1").Value = 1
ws.Range("A1").Copy
'multiply range by 1
rng.PasteSpecial xlPasteValues, xlPasteSpecialOperationMultiply
'retrieve original value of A1
ws.Range("A1").Value = origVal
'retrieve original blank cells
.Replace What:=tempStr, Replacement:=vbNullString
End With
tempStr = Empty
origVal = Empty
Set rng = Nothing
End If
Next ws
Application.ScreenUpdating = True
End Sub
要在电子表格上查找包含数据的最后一行,可以使用代码打击;如果电子表格为空,则会出错,将wb.Sheets(1)
替换为您的wb和工作表
lrow = wb.Sheets(1).Cells.Find(What:="*", After:=wb.Sheets(1).Range("A1"), SearchDirection:=xlPrevious).row