[英]Can't locate run-time error 1004
我認為這是一個非常簡單的代碼,旨在在工作表中的所有活動單元格周圍放置邊框(數據將始終駐留在cell(1,1)中)。 但是我得到了臭名昭著的“運行時錯誤1004”,我很困惑。
任何幫助,將不勝感激。
Sub test()
Dim myrange As Range
Dim x, y As Integer
x = ActiveSheet.Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByRows).Row
MsgBox x
'------------------------------'
y = ActiveSheet.Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByColumns).Column
MsgBox y
Set myrange = ActiveSheet.Range(Cells(1, 1), Cells(x, y))
With ActiveSheet '<-- erroring here'
.Range(myrange).Select
With Selection.Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
End With
End Sub
對我來說,它實際上在下一行.Range(myrange).Select
。 您已經定義了myrange,並且實際上不需要定義它。
同樣, Dim x, y As Integer
,僅將y
聲明為Integer
。 x
被聲明為Variant
。 在使用它時,應將它們聲明為Longs
,這是本機VBA類型。
另外,除非必要,請避免使用“ Select
。 說了這么多,這就是我的編碼方式:
Sub test()
Dim myrange As Range
Dim x As Long, y As Long
x = ActiveSheet.Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByRows).Row
y = ActiveSheet.Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByColumns).Column
Set myrange = ActiveSheet.Range(Cells(1, 1), Cells(x, y))
With myrange.Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
End Sub
在黑暗中有點困難,但是我認為您可能想嘗試定義要在With語句中使用的確切工作表。
Dim mySheet as WorkSheet
Set mySheet = ActiveWorkbook.Sheets(<name of your sheet>)
[etc etc]
有時VBA很難弄清楚活動表是什么。 我傾向於使用此解決方案,因為它是硬編碼而不是使用相對變量。 我認為您可以簡單地放入Sheets()之類的東西。激活並使用您的代碼...但是我不是一個大粉絲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.