引用VBA For循环内的范围

时间:2020-10-27 14:51:37

标签: excel vba

谢谢您的帮助!

我正在创建一个写入文本文件的宏。我在引用for循环内的范围时遇到麻烦。我有两个示例,其中我调用的范围返回一个“”。对于下面的第一个图像,用户可以在其中使用以下两种方式输入数据:将数据输入到工作表中,并使用将其定向到用户表单的按钮,该表单会限制用户输入的内容。在此第一张图片中,用户是由userform指示的,数据被输出到另一张纸上,我使用vlookup来显示信息。我这样做是为了在另一张纸上运行操作,只是为了帮助我跟踪所有内容(新手VBA用户)。第二页是数据存储和运行计算的地方。

1st image, User input and display 2nd image, data storage and calculation sheet

newDimName仅输出“ _Cav”和循环中存储在cavNum中的值。目的是根据用户输入的内容在列A中的字符串连接更多信息。我怀疑我没有正确引用a列的范围。无论用户输入了多少“尺寸”(lastUserDim中的值),Loop都设置为2。下面的代码包含在工作表引用中(不在代码段中),因此它引用了正确的工作表。例如循环之前是“ With Sheet2”,循环结束时是“ End With”。

   Dim a As Integer, cavNum As Integer
Select Case numCav
    Case Is = 4
    For a = 2 To lastUserDim
            For cavNum = 1 To 4
                newDimName = Cells(a, 1) & "_Cav" & cavNum
            Next cavNum
    Next a
    totalColumns = 4 * lastUserDim
    Case Is = 8
    For a = 2 To lastUserDim
            For cavNum = 1 To 8
                newDimName = Cells(a, 1) & "_Cav" & cavNum
            Next cavNum
    Next a
    totalColumns = 8 * lastUserDim
    Case Is = 16
    For a = 2 To lastUserDim
            For cavNum = 1 To 16
                newDimName = Cells(a, 1) & "_Cav" & cavNum
            Next cavNum
    Next a
    totalColumns = 16 * lastUserDim
    Case Is = 32
    For a = 2 To lastUserDim
            For cavNum = 1 To 32
                newDimName = Cells(a, 1) & "_Cav" & cavNum
            Next cavNum
    Next a
    totalColumns = 32 * lastUserDim
    Case Else
    MsgBox "Please select what # of cavities this tool has."
End Select

对于下面的代码,我希望读取定义的范围,对于选择情况,希望确定单元格是否包含“是”或“否”。该循环旨在针对大量用户输入的数据运行此操作。再次,我怀疑我没有像以前使用A列那样正确地调用c列中的数据。我尝试使用第一个代码段中的单元格,只是range,range(“”)。value和range(“”)。文字。

Dim LSLBound As String, LSLBoundRef As String
Dim c As Integer
For c = 2 To lastUserDim
    LSLBoundRef = Range("C2:C" & c).Text 'ref to cell value to use for select case
Select Case LSLBoundRef
    Case Is = "No"
        LSLBound = "LBound 1;"
    Case Is = "Yes"
        'Do Nothing
        End Select
Next c

1 个答案:

答案 0 :(得分:0)

如果第二个代码段包装在“ With Sheet2”中,则需要在Range前面加上句点,即**。** Range(“ C2”)...,以便使用正确的表

Dim LSLBound As String, LSLBoundRef As String
Dim c As Integer
With Sheets("Sheet2")
For c = 2 To lastUserDim
    LSLBoundRef = .Range("C2:C" & c).Text 'ref to cell value to use for select case
    Select Case LSLBoundRef
        Case Is = "No"
            LSLBound = "LBound 1;"
        Case Is = "Yes"
            'Do Nothing
        End Select
 Next c
 End With

弄清楚实际引用的范围的一种好方法是使用Debug.Print Range.Address将范围地址打印到立即窗口中。