首页 > 解决方案 > 使用列号而不是列字母引用范围

问题描述

我觉得这应该很简单,因为我在网上找到了一百万关于如何做到这一点的参考资料。我尝试了几种不同的组合都无济于事。

我只是想在一个范围内使用 LastCol 变量引用一个列,但不断收到下面的错误。错误发生在标有 -> 的行上。我尝试了几种不同的变体,包括使用带有冒号、逗号的第一个范围参数的字母名称,移动引号,加上“。” 在 Cells 引用等之前。每次我在网上查找如何执行此操作时,似乎我都做得对。

错误信息

这是我的代码:

Public Sub cmb_orgname_Change()

Dim wb As Workbook
Dim sht As Worksheet
Dim orgname As String
Dim org_position As Double
Dim LastCol, LastRow As Integer
Dim prod_range As Range
Dim cell As Range
Set sht = Sheet1

'get the value of the selected org name from the dropdown
orgname = sht.OLEObjects("cmb_orgname").Object.Value

'find the last column for the number of org names, currently this is not being utilized
LastCol = Sheet3.Range("F2").End(xlToRight).Column

If orgname <> "" Then
    Call Clear_ComboBox
    -> org_position = WorksheetFunction.Match(orgname, Sheet3.Range(Cells(2, 6), Cells(2, LastCol)), 0) + 6
    LastRow = Sheet3.Cells(Sheet3.Rows.Count, org_position).End(xlUp).Row
    Set prod_range = Sheet3.Range(Sheet3.Cells(3, org_position), Sheet3.Cells(LastRow, org_position))
    
    
    For Each cell In prod_range
        With sht.OLEObjects("cmb_prodname").Object
            Dim test As String
            test = CStr(cell.Value)
            .AddItem CStr(cell.Value)
        End With
    Next cell
    
End If

End Sub

标签: vba

解决方案


经过不同搜索的多次不同迭代后,我发现了一个名为 ADDRESS() 的函数,它位于一个范围之后。使用 ADDRESS 功能,我能够完成这项工作!基本上,我所要做的就是将我的行更改为以下内容:

org_position = WorksheetFunction.Match(orgname, Sheet3.Range("F2:" & Sheet3.Cells(2, LastCol).Address()), 0) + 6

现在它运行顺利。这是我找到地址功能和信息的页面:https ://software-solutions-online.com/use-vba-range-address-method/


推荐阅读