首页 \ 问答 \ Excel宏:根据条件将行值从一个工作表复制到另一个工作表中的特定位置(Excel Macro: Copying row values from one worksheet to a specific place in another worksheet, based on criteria)

Excel宏:根据条件将行值从一个工作表复制到另一个工作表中的特定位置(Excel Macro: Copying row values from one worksheet to a specific place in another worksheet, based on criteria)

我现在只在Excel中使用宏大约4个月,并且基本上通过查找现有代码并弄清楚它是如何工作来自学。 我现在有点卡住了。

我在Excel工作簿中有一个报告。 我需要根据D列中显示的数据将数据复制到多个工作表(在同一工作簿中)。也就是说,我需要复制D列符合某些条件的整行。 原始工作表包含公式,但我只希望在复制数据时显示值。

我已经能够复制数据,但我有两个问题:1)公式正在复制,而不仅仅是值2)数据出现在单元格A2的新工作表中,但我需要它从单元格A5开始

我将其设置为模板,因为主报告需要每月运行和拆分,因此我复制的范围不会是恒定的。 这是我目前使用的代码示例:

    Sub RefreshSheets()

    Sheets("ORIGIN").Select
    Dim lr As Long, lr2 As Long, r As Long
    lr = Sheets("ORIGIN").Cells(Rows.Count, "A").End(xlUp).Row
    lr2 = Sheets("DESTINATION").Cells(Rows.Count, "A").End(xlUp).Row

    For r = lr To 2 Step -1
        If Range("D" & r).Value = "movedata" Then
            Rows(r).Copy Destination:=Sheets("DESTINATION").Range("A" & lr2 + 1)
            lr2 = Sheets("DESTINATION").Cells(Rows.Count, "A").End(xlUp).Row
        End If


    Next r

    End Sub

我尝试在“.Range(”A“&lr2 + 1)”之后添加“.PasteSpecial Paste:= xlPasteValues”,但是我得到了编译错误(预期:语句结束)。 我确信我已经错过了一些显而易见的东西(这是我使用的代码我还没有完全理解的东西),但到目前为止我没有尝试过任何工作。

任何建议将不胜感激。


I have only been working with macros in Excel for about 4 months now and have essentially been teaching myself by finding existing code and figuring out how it works. I am now a bit stuck.

I have a report in an Excel workbook. I need to copy the data across a number of worksheets (within the same workbook), based on the data that appears in column D. That is to say, I need to copy the entire row where Column D matches certain criteria. The original worksheet contains formulas, but I only want the values to appear when the data is copied.

I have been able to copy the data across, but I have two problems: 1) the formulas are copying across, not just the values 2) the data appears in the new worksheet at cell A2, but I need it to start at cell A5

I am setting this up as a template, as the main report needs to be run and split every month, so the range from which I am copying will not be constant. This is a sample of the code I am currently using:

    Sub RefreshSheets()

    Sheets("ORIGIN").Select
    Dim lr As Long, lr2 As Long, r As Long
    lr = Sheets("ORIGIN").Cells(Rows.Count, "A").End(xlUp).Row
    lr2 = Sheets("DESTINATION").Cells(Rows.Count, "A").End(xlUp).Row

    For r = lr To 2 Step -1
        If Range("D" & r).Value = "movedata" Then
            Rows(r).Copy Destination:=Sheets("DESTINATION").Range("A" & lr2 + 1)
            lr2 = Sheets("DESTINATION").Cells(Rows.Count, "A").End(xlUp).Row
        End If


    Next r

    End Sub

I have tried adding ".PasteSpecial Paste:=xlPasteValues" after ".Range("A" & lr2 + 1)", but I get a compile error (Expected: end of statement). I am sure I have missed something obvious (this is what I get for using code I don't fully understand yet), but nothing I have tried so far has worked.

Any advice would be greatly appreciated.


原文:https://stackoverflow.com/questions/45339522
更新时间:2023-09-06 08:09

最满意答案

所有线程都必须等到分配master_tid 。 您应该使用同步机制,而不是手动sleep_for ,它容易出错并最终导致程序中的错误。 在您的情况下,您希望所有线程都在等待条件,您可以使用条件变量。 但是,我只是将不同的函数传递给master和slave,或者传递一个参数。

#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex m;
std::condition_variable cv;
thread::id master_tid {};
bool ready = false;

/// declarations
void doSomething() {
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk, []{return ready;});

    // master_tid is now assigned
   if (this_thread::get_id() == master_tid)
      cout << "master thread ..."
           << endl;
   else
      cout << "NOT master thread ..."
           << endl;
}


int main()  
{
   thread master {doSomething};

   thread slave {doSomething};

    {
        std::lock_guard<std::mutex> lk(m);
        ready = true;
        master_tid = master.get_id();
    }
    cv.notify_all();

   /// ...

   /// join with threads
   master.join();
   slave.join();

   cout << "done" << endl;
}

All threads have to wait until the master_tid is assigned. Instead of manual sleep_for, which is error prone and will eventually lead to bugs in your program, you should use a synchronization mechanism. In your case, where you want all threads wait for a condition, you can use a condition variable. However, I would just pass different functions to master and slave, or pass a parameter.

#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex m;
std::condition_variable cv;
thread::id master_tid {};
bool ready = false;

/// declarations
void doSomething() {
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk, []{return ready;});

    // master_tid is now assigned
   if (this_thread::get_id() == master_tid)
      cout << "master thread ..."
           << endl;
   else
      cout << "NOT master thread ..."
           << endl;
}


int main()  
{
   thread master {doSomething};

   thread slave {doSomething};

    {
        std::lock_guard<std::mutex> lk(m);
        ready = true;
        master_tid = master.get_id();
    }
    cv.notify_all();

   /// ...

   /// join with threads
   master.join();
   slave.join();

   cout << "done" << endl;
}

相关问答

更多
  • 您的原始断言不正确。 考虑: public static void TestThreadAbort() { var t = new Thread(() => Thread.Sleep(50000)); t.Start(); t.Abort(); Thread.Sleep(50); // Prints "Aborted" Console.WriteLine(t.ThreadState); } Your original assertion is not cor ...
  • 这是否意味着Thread.sleep()将当前线程置于睡眠状态? 是。 只有当前的线程可以做到这一点。 如果t1想让t睡觉怎么办? 那不应该是正确的? 对。 你可以设置一个volatile boolean标志,它会导致另一个线程调用Thread.sleep(...)但是另一个线程不会导致线程休眠。 volatile boolean shouldSleep = false; ... // check this flag that might be set by another thread to see ...
  • 总CPU时间或总用户时间不会告诉您有关线程年龄的任何信息。 它只能说最低线程的年龄就是这个值。 您可以考虑使用线程转储分析器,如Mchr3k - Java线程转储分析器或Samurai Total CPU time or Total User time does not give you any info on the age of the thread. It can only say that the the thread age at the minimum is this value. You ca ...
  • 您将根据定义引入竞争条件 - 当另一个线程观察到观察到的线程正在执行MethodX它可能已经转移到MethodY - 因为它将继续运行。 或者,您可以在观察时观察MethodX ,但它大部分时间都MethodY 。 您可以使用调试器和分析器完成您想要做的事情 - 这些将是您最好的选择,也是最可靠的选择。 You'd be introducing a race condition by definition--by the time another thread observed that the obser ...
  • 使用当前逻辑,您必须以更粗略的粒度进行同步,否则您可能会删除错误的元素。 for (int i = currentTemp; i < list.size() - 1; i++) { synchronized (list) { if (i + 1 > list.size() && isEqual(list.get(currentTemp), list.get(i+1))) { list.remove(i + 1); i--; } } } 您可以看到, isEq ...
  • 您可以使用队列和每个连接的多个线程来解决此问题。 基本概要: 每个客户端连接产生两个线程 - 一个用于监视客户端输入,另一个用于监视队列。 放在队列中的项目将被发送到客户端。 每个客户端连接都有自己的输出队列。 您还需要一个全局字典来将客户端名称映射到其输出队列。 要向特定客户端发送消息,请查找客户端的输出队列并将消息添加到该客户端。 您还需要一种方法来关闭客户端的输出线程。 一种常见的方法是在队列上使用sentinel值(如None )来通知输出线程退出其处理循环。 当客户端的输入线程检测到EOF时,它可 ...
  • CLR不一定知道在进程内运行的所有线程。 它对使用CreateThread()的本机代码启动的线程一无所知。 承载CLR的COM服务器或本机程序就是常见的例子。 例如,有许多COM服务器由.NET类,System.DirectoryServices和System.Management包装。 当这样的线程调用托管代码,事件或回调是通常的情况时,它被迫处理它们。 因为它还需要在该线程上执行堆栈遍历,以便在收集垃圾或查找CAS属性时查找托管对象。 此时,这个未知的本机线程成为“已识别”的线程。 看到“2”这个值没 ...
  • 所有线程都必须等到分配master_tid 。 您应该使用同步机制,而不是手动sleep_for ,它容易出错并最终导致程序中的错误。 在您的情况下,您希望所有线程都在等待条件,您可以使用条件变量。 但是,我只是将不同的函数传递给master和slave,或者传递一个参数。 #include #include #include std::mutex m; std::condition_variable cv; thread::id ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)