【发布时间】:2018-04-20 10:22:53
【问题描述】:
我有以下宏,它将搜索三个不同的列标题,选择这些标题下的数据并将数据从货币格式更改为数字格式。数据存储在我的工作簿的表 2 中,当我在此表中单独运行宏时,它可以正常工作。
Sub ProjectFundingFormat()
'
Dim WS As Worksheet
Dim lastCol As Long, lastRow As Long, srcRow As Range
Dim found1 As Range, found2 As Range
Set WS = Workbooks("Workbook1.xlsm").Worksheets("Sheet2") 'Needs to be open
With WS
lastCol = .Cells(1, Columns.count).End(xlToLeft).Column
Set srcRow = .Range("A1", .Cells(1, lastCol))
Set found1 = srcRow.Find(What:="2018FundingLabor", LookAt:=xlWhole, MatchCase:=False)
If Not found1 Is Nothing Then
lastRow = .Cells(Rows.count, found1.Column).End(xlUp).Row
.Range(.Cells(2, found1.Column), .Cells(lastRow, found1.Column)).Select
Selection.NumberFormat = "0.00"
End If
End With
With WS
lastCol = .Cells(1, Columns.count).End(xlToLeft).Column
Set srcRow = .Range("A1", .Cells(1, lastCol))
Set found1 = srcRow.Find(What:="2018FundingNonlabor", LookAt:=xlWhole, MatchCase:=False)
If Not found1 Is Nothing Then
lastRow = .Cells(Rows.count, found1.Column).End(xlUp).Row
.Range(.Cells(2, found1.Column), .Cells(lastRow, found1.Column)).Select
Selection.NumberFormat = "0.00"
End If
End With
With WS
lastCol = .Cells(1, Columns.count).End(xlToLeft).Column
Set srcRow = .Range("A1", .Cells(1, lastCol))
Set found1 = srcRow.Find(What:="2018 Total Funding", LookAt:=xlWhole, MatchCase:=False)
If Not found1 Is Nothing Then
lastRow = .Cells(Rows.count, found1.Column).End(xlUp).Row
.Range(.Cells(2, found1.Column), .Cells(lastRow, found1.Column)).Select
Selection.NumberFormat = "0.00"
End If
End With
End Sub
我想将此宏与另外两个结合起来,这样我就可以进入工作表 1,单击我插入的“运行”按钮,我的所有宏将一起运行以更新我的数据。
但是,我得到错误
运行时错误 1004 - 范围类的选择方法失败
在线上
.Range(.Cells(2, found1.Column), .Cells(lastRow, found1.Column)).Select
有人知道我的代码有什么问题吗?我很困惑,因为它本身可以正常工作,但与我的其他宏结合使用时不会运行。
我正在使用以下宏来组合我现有的两个宏:
Sub ProjectUpdate()
Call ProjectName
Call ProjectFunding
Call ProjectFundingFormat
MsgBox "Done"
End Sub
【问题讨论】:
-
我建议阅读和使用How to avoid using Select in Excel VBA 这应该可以解决您的问题。
-
同意PEH,特别是这里的问题可能是您试图在非活动工作表上选择一个范围。
-
@Pᴇʜ 谢谢!我已经在我的宏中添加了一行来激活工作表,它现在可以正常工作了! Worksheets("Projects").Activate
-
@nw201827 你做到了,但你做错了。请参阅下面的答案。
标签: vba excel select multiple-columns