运行时错误13我的代码中键入不匹配?

时间:2019-03-05 12:20:08

标签: excel vba

我在一栏中有不同格式的日期。我正在尝试转换为格式11.01.2019。这些日期来自电子邮件正文,因此采用字符串格式。 这是我的代码,不适用于其中的一部分,但不适用于所有代码。我正在尝试为所有日期格式添加条件要求。

enter image description here

Sub ConvertToDate()

  Dim r As Range
  Dim setdate As Range

  Set setdate = Range(Cells(3, 3), Cells(3, 3).End(xlDown))

  With setdate
    .NumberFormat = "dd.mm.yyyy" 
    .Value = .Value
  End With

  For Each r In setdate
      r.Value = CDate(r.Value)
  Next r

End Sub

错误显示在行中:

r.Value = CDate(r.Value) 

1 个答案:

答案 0 :(得分:1)

在Excel中查看带有日期的值。如果它们自动左对齐,则Excel不会考虑日期,而是考虑字符串。在下图中,A列和B列是字符串,C列是日期。

enter image description here

1-Mar-19应用于字符串时,会出现类型不匹配错误,因为VBA不知道如何将字符串转换为日期。

为确保将日期格式化为日期,并且Excel知道如何处理日期,您必须找到一种将-解析为日期的方法。有几种方法可以做到,具体取决于您的感觉。可能最简单的方法是将/替换为Sub TestMe() Dim r As Range For Each r In ThisWorkbook.Worksheets(1).Range("A1:B9") r = Replace(r, "-", "/") r.NumberFormat = "dd.mm.yyyy" Next r End Sub ,然后让VBA和Excel完成其余工作:

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "example.com",
    UserName = "user",
    Password = "password",
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    List<string> prevFiles = null;

    while (true)
    {
        // Collect file list
        List<string> files =
            session.EnumerateRemoteFiles(
                "/remote/path", "*.*", EnumerationOptions.AllDirectories)
            .Select(fileInfo => fileInfo.FullName)
            .ToList();
        if (prevFiles == null)
        {
            // In the first round, just print number of files found
            Console.WriteLine("Found {0} files", files.Count);
        }
        else
        {
            // Then look for differences against the previous list
            IEnumerable<string> added = files.Except(prevFiles);
            if (added.Any())
            {
                Console.WriteLine("Added files:");
                foreach (string path in added)
                {
                    Console.WriteLine(path);
                }
            }

            IEnumerable<string> removed = prevFiles.Except(files);
            if (removed.Any())
            {
                Console.WriteLine("Removed files:");
                foreach (string path in removed)
                {
                    Console.WriteLine(path);
                }
            }
        }

        prevFiles = files;

        Console.WriteLine("Sleeping 10s...");
        Thread.Sleep(10000);
    }
}