excel - Excel VBA 中的宏代码未按预期运行
问题描述
我正在尝试编写一个宏,其中 EXCEL 执行以下操作:
- 将 A1 、 B1 、 C1 等中的数据更改为特定的日期格式 (dd-mm-yyyy)
- 使用 DATEDIFF 函数计算 A1 和 B1 中的值之间以及 A1 和 C1 中的值之间的天数
- 将该 DateDIFF 函数的结果放在另一个单元格中
我不断收到奇怪的值并重置我的功能
这是我现在使用的代码,但我不断收到错误:
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 中的错误 = 类型不匹配。
对此进行更多解释:
- 用户将日期复制到前 3 列(A、B、C)
- 我的宏(脚本)必须将这些值更改为标准格式(dd-mm-yyyy)
另一个按钮或脚本必须计算:A 和 BB 和 C A 和 C 之间的天数
3 计算的天数必须放在另一列(H 或其他)中,以便报告。
如果我不是很清楚,我很抱歉,这是我第一次使用 Stackoverflow。
问候,
解决方案
如果没有更多信息并假设您的目标......这可能会帮助您:
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
推荐阅读
- c# - 当页面回发时,Updatepanel 使网格消失
- python - “pyodbc.Cursor”对象没有属性“fast_executemany”
- react-admin - 无法读取属性“hasOwnProperty”
- spring-boot - Spring Boot 应用程序中的 HazelCast 抛出您可能有太长的 Hazelcast 配置的错误
- javascript - ajax 通过 Php 从 MSSQL 服务器获取数据
- android - 在 ARCore 中始终旋转的垂直平面上添加的对象
- php - Laravel - 如何更新两个值
- c# - 我可以列出 Visual Studio 解决方案中的所有 *不可用* 项目吗?
- php - PDO:如果查询未找到结果,则返回 0
- android - MVC 与 MVP 与 MVVM 用例