iT邦幫忙

1

請教如何設置一個全工作簿的變數,在其他工作表可以取其值?

vba
    Set Arr = CreateObject("Scripting.Dictionary")
                BgnRow = 2
                EndRow = .Cells(Rows.Count, "A").End(xlUp).Row
        
                 For i = BgnRow To EndRow
                    If .Cells(i, "D").Value = "V" Then
                        Arr(i) = .Cells(i, "A").Value
                    End If
                 Next i

要如何設置這樣的變數,在其他工作表可以直接引用他的值,比如:Arr.count,或他的Key或Items的值?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
1
japhenchen
iT邦超人 1 級 ‧ 2021-07-09 12:36:21
=工作表1!$A$1 + 工作表2!$B$1

VBA比照辦理

sum = Worksheets("工作表1").cells(1,1) + Worksheets("工作表2").cells(2,1)

打完收工

再補一個,跨工作簿(XLS檔)

Workbooks("c:\excel\20210709.xls").Worksheets("工作表1").cells(1,1)

啊如果是跨電腦.......(有分享)

Workbooks("\\張三的電腦\sharedir\excel\20210709.xls").Worksheets("工作表1").cells(1,1)
lin520 iT邦新手 4 級 ‧ 2021-07-10 09:42:00 檢舉

謝謝!感恩!

1
海綿寶寶
iT邦大神 1 級 ‧ 2021-07-09 12:55:10
blanksoul12 iT邦研究生 5 級 ‧ 2021-07-09 13:14:12 檢舉

sorry delete

blanksoul12 iT邦研究生 5 級 ‧ 2021-07-09 13:15:37 檢舉

sorry sorry

lin520 iT邦新手 4 級 ‧ 2021-07-10 10:01:42 檢舉

請教若使用Public或Global宣告,以Arr為例,
Public Arr as Variant
Public k as Variant
public t as Variant

             For i = BgnRow To EndRow
                If .Cells(i, "D").Value = "V" Then
                    Arr(i) = .Cells(i, "A").Value
                End If
             Next i
        End With
        k=Arr.Keys
        t=Arr.Items

可否直接宣告一個Public Arr as Variant,其他k 或t值,於sub程式再利用k=Arr.Keys 或t=Arr.Items取得?我的嘗試會錯誤,請教該如何設置?

1
blanksoul12
iT邦研究生 5 級 ‧ 2021-07-09 13:12:46

其中一種做法

Dim temp_arr As Double
Sub test()
    Set arr = CreateObject("Scripting.Dictionary")
    BgnRow = 2
    EndRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row

     For i = BgnRow To EndRow
        If ActiveSheet.Cells(i, "D").Value = "V" Then
            arr(i) = ActiveSheet.Cells(i, "A").Value
        End If
     Next i
     temp_arr = arr.Count
End Sub
Sub other() '先行這個
    test
    MsgBox temp_arr
End Sub

另一種做法

Function temp_arr()
    Set arr = CreateObject("Scripting.Dictionary")
    BgnRow = 2
    EndRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row

     For i = BgnRow To EndRow
        If ActiveSheet.Cells(i, "D").Value = "V" Then
            arr(i) = ActiveSheet.Cells(i, "A").Value
        End If
     Next i
     temp_arr = arr.Count
End Function
Sub other()
    MsgBox temp_arr
End Sub
lin520 iT邦新手 4 級 ‧ 2021-07-10 10:04:10 檢舉

若使用Function不失為好解決辦法,但是要如何於Sub呼叫?

blanksoul12 iT邦研究生 5 級 ‧ 2021-07-12 17:54:00 檢舉

你直接在 other 那個 sub 按 F5 可以了

我要發表回答

立即登入回答