2012-12-06 172 views
0

我認爲這是一個非常簡單的代碼,用於在工作表中的所有活動單元格周圍放置邊界(數據將始終駐留在單元格(1,1)中)。但我得到臭名昭着的「運行時錯誤1004」,我很難過。無法找到運行時錯誤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 
+0

@Doug感謝代碼不幸的是其在「與myrange.borders」 – Atwp67

+0

這是更好地使我的回答如下評論拋出一個錯誤 - 這樣我會收到通知。請告訴我錯誤(在我的答案下面)。 –

回答

6

對我來說,它實際上在下一行.Range(myrange).Select錯誤。您已經定義了myrange,並且您不需要(實際上不能)來限定它。

此外,Dim x, y As Integer,只宣佈y作爲Integerx被宣告爲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 
+0

錯誤被拋出With myrange.Borders – Atwp67

+0

錯誤信息說什麼? –

+0

運行時錯誤'1004':應用程序定義或對象定義的錯誤 – Atwp67

0

這是在黑暗中的一點點,但我認爲你可能想嘗試定義一個精確的工作表在你的With語句中使用。

Dim mySheet as WorkSheet 
Set mySheet = ActiveWorkbook.Sheets(<name of your sheet>) 
[etc etc] 

有時VBA很難搞清楚活動工作表是什麼。我傾向於使用這種解決方案,因爲它使用硬編碼代替使用相對變量。我理論上你可以簡單地放一些像Sheets()這樣的東西。激活並使用你的代碼...但我不是一個很大的粉絲。