Версия массива
Не знаю много о коллекциях, но я думаю, что массивы - это путь.
Option Explicit
Public Belts As Variant 'Public Belts As Collection
Public Sub mCaricaBelts()
On Error GoTo RigaErrore
Dim wb As Workbook, wbn As String
Dim sh As Worksheet
Dim rng As Range
Dim c As Range, v As Variant
Dim lrw As Long
With Application
.ScreenUpdating = False
.Calculation = xlManual
.StatusBar = _
"Sto caricato la tabella Fasce"
End With
wbn = "Listino.xlsx"
' If Not Belts Is Nothing Then
' Set Belts = Nothing
' End If
' Set Belts = New Collection
If AlreadyOpen(wbn) Then
Set wb = Workbooks(wbn)
Else
Set wb = Workbooks.Open("\\itcpifs01\license$\Listino.xlsx")
End If
Set rng = wb.Worksheets("dbRatesSTD").Range("C1")
Set rng = Range(rng, rng.End(xlToRight))
'Be careful, this is a horizontal array.
Belts = rng
' For Each c In rng
' Belts.Add c
' Next
' if I put the loop here, I can show results
For Each v In Belts
Debug.Print v
Next
Application.DisplayAlerts = False
wb.Close
Application.DisplayAlerts = True
' if I put the loop here, I can't show results, Error 424 Object required
For Each v In Belts
Debug.Print v
Next
RigaChiusura:
Set c = Nothing
Set rng = Nothing
Set sh = Nothing
With Application
.ScreenUpdating = True
.Calculation = xlAutomatic
.StatusBar = ""
End With
Exit Sub
RigaErrore:
MsgBox Err.Number & vbNewLine & Err.Description
Resume RigaChiusura
End Sub
У меня более старый Excel, поэтому я могу только представить, что AlreadyOpen(wbn)
означает, но вот старый способ для полной инструкции If для вашего кода:
'Check if Excel file is opened:
On Error Resume Next
Set wb = Workbooks(wbn) 'Workbook is opened.
If Err then 'Workbook is closed.
Set wb = Workbooks.Open("\\itcpifs01\license$\Listino.xlsx")
Err.Clear
End If
On Error GoTo RigaErrore 'Reactivate your 'first line error'.
В вашем коде нет констант.Я хотел бы добавить это в начало кода и внести соответствующие изменения:
Const cStrTabella as String = "Sto caricato la tabella Fasce"
Const cStrWbn as String = "Listino.xlsx"
Const cStrWbp as String = "\\itcpifs01\license$\Listino.xlsx"
Const cStrWs as String = "dbRatesSTD"
Const cStrAddress as String = "C1"
Теперь гораздо проще изменить материал, а кому-то - изменить его для теста, и вы можете гораздо быстрее получить ответ дляпроблема.