首页 > 解决方案 > Excel VBA 中的宏代码未按预期运行

问题描述

我正在尝试编写一个宏,其中 EXCEL 执行以下操作:

我不断收到奇怪的值并重置我的功能

这是我现在使用的代码,但我不断收到错误:

Private Sub CommandButton1_Click()
Range("A1:A5000").NumberFormat = "dd-mm-yyyy"
Range("B1:B5000").NumberFormat = "dd-mm-yyyy"
End Sub

Private Sub CommandButton2_Click()

Dim n As Variant
Dim Range("A1:A5000") As Date
Dim Range("B1:B5000") As Date

n = DateDiff("d", Range("A1:A5000"), Range("B1:B5000"))
n = Range("C1:C5000")

End Sub

更新 :

VBA 中的错误 = 类型不匹配。

对此进行更多解释:

  1. 用户将日期复制到前 3 列(A、B、C)
  2. 我的宏(脚本)必须将这些值更改为标准格式(dd-mm-yyyy)
  3. 另一个按钮或脚本必须计算:A 和 BB 和 C A 和 C 之间的天数

  4. 3 计算的天数必须放在另一列(H 或其他)中,以便报告。

如果我不是很清楚,我很抱歉,这是我第一次使用 Stackoverflow。

问候,

标签: excelvba

解决方案


如果没有更多信息并假设您的目标......这可能会帮助您:

Private Sub CommandButton2_Click()

    Dim n As Long 'it will give you a number
    Dim LastRow As Long
    Dim C As Range

    Application.ScreenUpdating = False

    With ThisWorkbook.Sheets("SheetName") 'change this to the actual sheet name
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'last row on column A
        For Each C In .Range("A1:A" & LastRow)
            C.Offset(0, 2) = DateDiff("d", C, C.Offset(0, 1))
        Next C
    End With

    Application.ScreenUpdating = True

End Sub

推荐阅读