簡體   English   中英

Excel VBA設置變量以選擇特定工作表中的單元格區域

[英]Excel VBA set variable to select a range of cells in a specific worksheet

我一直在嘗試運行一個腳本,該腳本遍歷C列並在單元格中的文本左側或右側修剪掉任何空格。 當我運行它時,我收到關於設置rr的錯誤(當我嘗試運行它時,也會出現SS,UU,VV)。

調試器在這里找到錯誤“運行時錯誤'1004':應用程序定義的錯誤或對象定義的錯誤。

Set rr = Worksheets("EOD").Range(Cells(2, 3), Cells(100, 3))

我還在下面提供了完整的代碼,以防萬一可能提供更好的見解。 我曾經使用過JS和PHP,但是VBA卻使我感到困惑。

預先感謝您提供的任何幫助。

中號

Sub Workbook_Open()
Dim r As Range
Dim s As Range
Dim t As Range
Dim u As Range
Dim v As Range
Dim a As Integer
Dim b As Integer
Dim c As Integer
Dim d As Integer
Dim e As Integer
Dim rr As Range
Dim ss As Range
Dim tt As Range
Dim uu As Range
Dim vv As Range
Set rr = Worksheets("EOD").Range(Cells(2, 3), Cells(100, 3))
Set ss = Worksheets("9AM Report").Range(Cells(2, 3), Cells(100, 3))
Set uu = Worksheets("1PM CST").Range(Cells(2, 3), Cells(100, 3))
Set vv = Worksheets("3PM ST").Range(Cells(2, 3), Cells(100, 3))
Set tt = Worksheets("11AM Report").Range(Cells(2, 3), Cells(100, 3))

For Each r In rr
    r = Trim(r)
    a = a + 1
    If a = 199 Then Call RefreshAllPivotTables
    If a > 200 Then End
Next
For Each s In ss
    s = Trim(s)
    b = b + 1
    If b = 199 Then Call RefreshAllPivotTables
    If b > 200 Then End
Next
For Each t In tt
    t = Trim(t)
    c = c + 1
    If c = 199 Then Call RefreshAllPivotTables
    If c > 200 Then End
Next
For Each u In uu
    u = Trim(u)
    d = d + 1
    If d = 199 Then Call RefreshAllPivotTables
    If d > 200 Then End
Next
For Each v In vv
    v = Trim(v)
    e = e + 1
    If e = 199 Then Call RefreshAllPivotTables
    If e > 200 Then End
Next
End Sub

Sub RefreshAllPivotTables()

Dim PT As PivotTable
Dim WS As Worksheet

For Each WS In ThisWorkbook.Worksheets

    For Each PT In WS.PivotTables
      PT.RefreshTable
    Next PT

Next WS

End Sub

當另一個工作表處於活動狀態時,我能夠重現您的錯誤。 您需要像對Range一樣完全定義Cells的圖紙位置。

代替:

Set rr = Worksheets("EOD").Range(Cells(2, 3), Cells(100, 3))

嘗試:

Dim wks1 As Worksheet
Set wks1 = Worksheets("EOD")

Set rr = wks1.Range(wks1.Cells(2, 3), wks1.Cells(100, 3))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM