excel - 在 VBA For 循环中引用范围
问题描述
提前感谢您的帮助!
我正在创建一个写入文本文件的宏。我无法引用 for 循环内的范围。我有两个例子,我调用的范围返回一个“”。对于下面的第一张图片,这是用户使用在工作表中输入数据和使用将他们定向到用户表单的按钮的组合来输入数据的地方,该用户表单将输入他们输入的内容。在第一个图像中,用户由用户表单引导,数据被输出到另一个工作表,我使用 vlookup 显示信息。我这样做是为了在另一张纸上运行操作,只是为了帮助我跟踪所有内容(新手 vba 用户)。第二张表是存储数据和运行计算的地方。
第 1 图像,用户输入和显示 第 2 图像,数据存储和计算表
newDimName 仅输出“_Cav”和循环存储在 cavNum 中的值。目的是将 A 列内的字符串与更多信息连接起来,具体取决于用户输入的内容。我怀疑我没有正确引用 a 列的范围。Loop 设置为 2 到用户输入的任何数量的“维度”(lastUserDim 中的值)。下面的代码包含工作表引用(不在代码段中),因此它引用了正确的工作表。前任。“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
解决方案
如果第二个代码片段包含在“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 将范围地址打印到即时窗口。
推荐阅读
- javascript - simplecart js 多视图功能
- bash - 在 docker 容器中编辑 war 文件中的文件
- javascript - Javascript函数等待直到另一个函数返回true或false并做相应的事情
- sql - 从具有一对多关系的两个表中获取数据的最佳方法是什么?
- java - TabLayout 中的标题不显示
- polymorphism - decltype 和 typeid 返回不同的类型
- javascript - 从数据库中输出获取到的json数据
- c# - 您如何使用 Google Play Social API 报告时间?
- javascript - 使用 NodeJS 类和猫鼬时如何避免回调?
- android - viewpager 选择了两个标签(疯了)