尝试将 excel 命名范围的字符串(带空格的文本)转换为字符串数组

Trying to convert an excel named range of strings (text with spaces) into a string array

正在尝试将 excel 命名范围的字符串(带空格的文本)转换为字符串数组以用于访问数据库查询。基本上,从 excel 中提取名称列表,使用这些名称查询数据库,然后将与这些名称相关的 return 数据返回到 excel。我在这里找到了一些相关的答案:

Excel VBA: Range to String Array in 1 step

但是当我 运行 从变量数组转换为字符串数组的循环时,"sArray"(字符串数组)没有填充。这是我的代码:

Dim theRange As Variant
Dim sArray() As String
Dim i As Long

Application.ScreenUpdating = False
Application.Calculation = -xlCalculationManual
Application.DisplayAlerts = False

activeworksheet = ("Sheet2")

theRange = range("SecurityID").Value
size = UBound(theRange)

For i = 1 To 5
    ReDim sArray(1 To 5)
    sArray(i) = CStr(theRange(i, 1))
Next i

有一些小错误。这将适用于 ActiveSheet:

Sub marine()
    Dim theRange As Variant
    Dim sArray() As String
    Dim i As Long
    Range("A1:A5").Name = "SecurityID"
    Application.ScreenUpdating = False
    Application.Calculation = -xlCalculationManual

    'Application.DisplayAlerts = False
    'activeworksheet = ("Sheet2")

    theRange = Range("SecurityID").Value
    Size = UBound(theRange, 1)
    ReDim sArray(1 To Size)
    For i = 1 To Size
        sArray(i) = CStr(theRange(i, 1))
        MsgBox sArray(i)
    Next i
End Sub
Dim vSecurityID As Variant
Dim lngCounter As Long

vSecurityID = Range("SecurityID").Value

For lngCounter = LBound(vSecurityID) To UBound(vSecurityID)
    Debug.Print vSecurityID(lngCounter, 1)
Next lngCounter

你们很亲近。只是一些简单的事情:

Sub test()
    Dim theRange As Variant
    Dim sArray() As String
    Dim i As Long

    Application.ScreenUpdating = False
    Application.Calculation = -xlCalculationManual
    Application.DisplayAlerts = False

    theRange = Sheets("Sheet2").Range("SecurityID").Value

    ReDim sArray(1 To 5)
    For i = 1 To 5
        sArray(i) = CStr(theRange(1, i))
    Next i

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.DisplayAlerts = True
End Sub
  • 用范围指定sheet名称(ActiveWorksheet是一个保留词)
  • 您只需要在循环之前将目标数组 ReDim 一次
  • 不需要设置 size = UBound(theRange)
  • 不要忘记在最后重新启用屏幕更新、计算和警报