vba - 使用 Worksheets 似乎不会更改不同工作表上的单元格值
问题描述
我有写在模块中的宏。我还有用户表单来收集用户输入并在同一个工作簿的两个不同工作表上填充某些单元格。
在模块中的一个子中,我已经声明:
Dim wsAssemblyBOM As Worksheet
Set wsAssemblyBOM = Worksheets("Assembly BOM")
Dim wsDocuments As Worksheet
Set wsDocuments = Worksheets("Documents")
HeaderInfoUserForm.Show
这将打开我的用户表单,一切似乎都按计划进行,直到我们进入 OK 按钮功能:
Private Sub OK_Button_Click()
With wsAssemblyBOM
Cells(2, 3) = Author.Value
Cells(2, 5) = Title.Value
Cells(2, 7) = SubCode.Value
Cells(2, 6) = DateText.Value
Version = BOMVersion.Value
End With
With wsDocuments
Cells(2, 3) = Author.Value
Cells(2, 5) = Title.Value
Cells(2, 7) = SubCode.Value
Cells(2, 6) = DateText.Value
End With
End Sub
这只会填充活动表中的单元格。我在这里有点困惑,因为网络中的所有示例都表明这应该有效。我还尝试在“单元格”前面添加点,但它只会给出错误。
我在这里做错了什么?
我也很困惑何时以点开头。例如:
With wsDocuments
.Cells(2, 3) = Author.Value
.Cells(2, 5) = Title.Value
.Cells(2, 7) = SubCode.Value
.Cells(2, 6) = DateText.Value
End With
这将给出错误“需要对象”。Cells 是工作表的一个对象,但它是错误的,因为我试图为 .cells 赋值,而这实际上不是单元格内容的位置?没有点它是指单元格的实际内容?只是在这里猜测..
很多时候 dot 在类似的地方使用。逻辑对我来说不是很清楚。工作代码示例:
With FormatRange.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlMedium
End With
解决方案
你写了,
With wsAssemblyBOM
Cells(2, 3) = Author.Value
Cells(2, 5) = Title.Value
Cells(2, 7) = SubCode.Value
Cells(2, 6) = DateText.Value
Version = BOMVersion.Value
End With
本来应该是
With wsAssemblyBOM
.Cells(2, 3) = Author.Value
.Cells(2, 5) = Title.Value
.Cells(2, 7) = SubCode.Value
.Cells(2, 6) = DateText.Value
Version = BOMVersion.Value
End With
请注意.
将 wsAssemblyBOM 父引用传递到每个 .Cells 的前缀。假设 wsAssemblyBOM 和 wsDocuments 已被声明并设置为工作表,并且它们可用于 OK_Button_Click 私有子,那么您应该没有问题。
你的最后一个例子,
With FormatRange.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlMedium
End With
......就像说一样,
FormatRange.Borders(xlEdgeTop).LineStyle = xlContinuous
FormatRange.Borders(xlEdgeTop).ColorIndex = xlAutomatic
FormatRange.Borders(xlEdgeTop).TintAndShade = 0
FormatRange.Borders(xlEdgeTop).Weight = xlMedium
详细方法也较慢,因为 FormatRange.Borders(xlEdgeTop) 必须解析四次。
将Option Explicit放在每个代码表的顶部。
推荐阅读
- mysql - 为什么我在选择yes 再次播放后无法更新我的html 模型?
- javascript - 如何使用部分超出视口的 div 制作水平滚动条
- c++ - 如何使用自适应正交例程对向量的内容进行积分
- haskell - 访问 Haskell 中的 map 等函数中的列表位置
- java - .exceptionally() 会捕获嵌套期货中抛出的异常吗?或者放在哪里是正确的 .exceptionally()
- javascript - onkeyup 弃用事件说明
- macos - 将动态库链接到 Netbeans 平台项目
- python - 一起使用多个选项或根本不使用
- neural-network - CNTK 发送有关“sequence.gather”运算符的错误
- model-view-controller - ASP.NET MVC 网站路线图不起作用