【问题标题】:Getting value from cell on another sheet从另一张纸上的单元格中获取价值
【发布时间】:2020-10-16 01:51:33
【问题描述】:

我试图从同一个工作簿中的另一个工作表中获取一个值,但我似乎无法弄清楚。

我有三张床单;它们被命名为 X、Y 和 Z。我目前的代码查看工作表 X 上的几个不同值,以确定要从工作表 Y 或 Z 上提取哪个单元格。

我觉得我的代码写得很好,但是我想要的值只是 0.00 而不是我想要的 1625.00。

Sub test()

Dim value1 As String
Dim value2 As String
Dim value3 As String
Dim value4 As Integer

value1 = ActiveSheet.Cells(8, 4).Value '(the letter Y is written in this cell)
value2 = ActiveSheet.Cells(10, 4).Value '(the word yes is written in this cell)
value3 = ActiveSheet.Cells(12, 4).Value '(the word yes is written in this cell)

if value1 = "" Then
Exit Sub
End If

If value2 = "yes" And value3 = "yes" Then
value4 = Worksheets(value1).Range("H4") 
End If

Cells(9, 9) = value4

End Sub

工作表 Y 上的单元格 H4 包含我想要拉过来的数字。 我正在尝试使用 value1 字符串作为工作表的名称,因为我可能需要从工作表 Y 或 Z 中提取

【问题讨论】:

  • Cells(9, 9).Value = Worksheets(value1).Range("H4").Value?
  • 很可能value2value3 实际上并非都是“是”。
  • 检查单词前后的空格。如果有,要么删除它们,要么用 trim() 包装分配的变量
  • 使用调试器并逐步执行您的代码(使用 F8)。检查变量的内容,这应该会告诉您代码失败的原因。

标签: excel vba


【解决方案1】:

各种问题

  • 这里有一些东西可以玩。
  • 如果您对工作簿和工作表进行了限定,那么当您知道工作表是工作表 X 时,将更容易跟踪正在发生的事情,即不需要ActiveSheet(您应该像避免瘟疫一样避免它)。
  • 比较字符串时要小心,例如“A”“a”或“是”“是”。
  • 有时最好不要将值写入变量。

守则

Option Explicit

Sub test()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim Val1 As String
    Dim Val2 As String
    Dim Val3 As String
    Dim Val4 As Long
    
    Set wb = ThisWorkbook ' The workbook containing this code.
    Set ws = wb.Worksheets("X") ' X or x will equally be accepted.
    
    Val1 = ws.Cells(8, 4).Value  ' (the letter Y is written in cell 'D8')
    Val2 = ws.Cells(10, 4).Value ' (the word yes is written in cell 'D10')
    Val3 = ws.Cells(12, 4).Value ' (the word yes is written in cell 'D12')
    'Val1 = ws.Range("D8").Value  ' (the letter Y is written in cell 'D8')
    'Val2 = ws.Range("D10").Value ' (the word yes is written in cell 'D10')
    'Val3 = ws.Range("D12").Value ' (the word yes is written in cell 'D12')
    
    If Val1 = "" Then
        Exit Sub
    End If
    
    ' StrComp with vbTextCompare will allow Yes, yes, yEs, yeS...
    If StrComp(Val2, "yes", vbTextCompare) = 0 And _
       StrComp(Val3, "yes", vbTextCompare) = 0 Then
        Val4 = wb.Worksheets(Val1).Range("H4").Value
        ' You could have just used:
        'ws.Cells(9, 9).Value = wb.Worksheets(Val1).Range("H4").Value
        ' i.e. because when you declare as Long it means there will be trouble
        ' if the value is not a number.
    End If
    
    ws.Cells(9, 9).Value = Val4 ' Cell 'I9'

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 2020-02-02
    相关资源
    最近更新 更多