【问题标题】:VBA - Adding a name inside the IFVBA - 在 IF 中添加名称
【发布时间】:2021-11-01 13:32:03
【问题描述】:

我对以下代码有一些问题:

Sub Sendorders()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = Workbooks("Hugo Automate V15.xlsm")
Dim ws As Worksheet: Set ws = wb.Worksheets("Bid-Ask")

Dim i As Long

ws.Activate

ws.Cells(2, 20) = ws.Cells(2, 20) & " Equity"

For i = 8 To 242
 If ws.Cells(2, 20).Value = ws.Cells(i, 1).Value Then

 If Cells(2, 23) = "BUY" Then
    Cells(i, 20) = Cells(2, 22)
    Cells(i, 21) = Cells(2, 21)
 Else
    Cells(i, 22) = Cells(2, 22)
    Cells(i, 23) = Cells(2, 21)
 End If
 End If
Next

Application.ScreenUpdating = True

End Sub

我想像这样编译 ligne 7 和 ligne 10:

If ws.Cells(2,20) & "Equity".Value = ws.Cells(i,1).Value Then

但是这不起作用...

【问题讨论】:

  • If ws.Cells(2,20).Value & "Equity" = ws.Cells(i,1).Value Then 添加的文本不是范围的一部分,因此您不能在字符串之后使用 value 属性。请注意,范围的标准属性是值,因此ws.Cells(2, 20) 被解释为ws.Cells(2, 20).value。所以第 7 行在技术上已经是 ws.Cells(2, 20).value = ws.Cells(2, 20).value & " Equity" 但是这两个字符串(一个空格)有区别,只是为了让你知道。

标签: vba if-statement


【解决方案1】:

.value 是 Range 对象的属性。它也是查看范围对象时使用的默认属性。

因此,第 7 行中的 ws.Cells(2,20)if 中的 ws.Cells(2, 20).Value 是同一件事。
因此第 7 行也是这样的:ws.Cells(2, 20).value = ws.Cells(2, 20).value & " Equity"

问题是尝试使用.value属性,但没有连接到范围对象,而是连接到字符串:ws.Cells(2,20) & "Equity".Value,这样不行。

您也可以使用“With”而不是 Activate 来确保定位到正确的工作表,除非您特别想切换到该工作表。

With ws
   For i = 8 To 242
      If .Cells(2, 20).Value & " Equity" = .Cells(i, 1).Value Then
         If .Cells(2, 23) = "BUY" Then
            .Cells(i, 20) = .Cells(2, 22)
            .Cells(i, 21) = .Cells(2, 21)
         Else
            .Cells(i, 22) = .Cells(2, 22)
            .Cells(i, 23) = .Cells(2, 21)
         End If
      End If
   Next i
End with

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2017-06-17
    • 2014-03-23
    • 1970-01-01
    相关资源
    最近更新 更多