Expressions with the word table

  • to table – (British English) предлагать, выносить на обсуждение; (American English) откладывать в долгий ящик, класть под сукно
  • turn the tables – поменяться ролями с кем-либо для того, чтобы получить преимущество перед ними
  • (put one’s) cards on the table – раскрыть карты; рассказать все начистоту, как есть
  • deal under the table – держать свои планы в тайне; действовать тайно, из-под полы; действовать подпольно, незаконно
  • under the table – тайно, закулисно, секретно; из-под полы; в качестве взятки, незаконно
  • bring [something] to the table – вносить (свою) лепту; быть полезным, добиться чего-либо, сделать свой вклад в общее дело; проявить себя, показать результативность (в командной работе)

Американское произношение:

Hello and welcome to Words and Their Stories from VOA Learning English!

Здравствуйте и добро пожаловать на «Истории слов», программу из материалов VOA Learning English.

On this program, we explore the stories behind common expressions in American English.

В этой программе мы раскрываем истории, стоящие за часто употребляемыми выражениями американского английского.

Today, we talk about an object found in every home. We eat off them. We can also work at them. We play games on them and, at other times, we simply gather around them.

Сегодня мы поговорим о том, что есть в каждом доме. Мы на них едим. За ними мы также можем работать. Мы играем на них в игры и, иногда, мы просто собираемся вокруг них.

They are tables!

Это столы!

A table is often at the center of many activities. So it is not surprising that the word “table” is used in several common expressions.

Стол часто находится в центре многих занятий. Так что нет ничего удивительного в том, что многие распространенные выражения включают в себя слово «стол».

Let’s start with a very simple one: to table something.

Давайте начнем с самого простого: to table something.

George Bernard Shaw was a famous playwright. He reportedly said that «England and America are separated by the same language.»

Джордж Бернард Шоу был знаменитым драматургом. Ему приписывают слова о том, что «Англия и Америка разделены общим языком».

However, he may not have said that. It was the Irish writer Oscar Wilde who wrote years earlier in his 1887 story The Canterville Ghost, «… we have really everything in common with America nowadays, except, of course, language.»

Однако, он, возможно, этого и не говорил. Не кто иной, как ирландский писатель Оскар Уайльд написал несколькими годами ранее, в 1887 году, в своем рассказе «Кентервильское привидение»: «…теперь у нас с Америкой практически все общее – кроме, конечно же, языка».

Regardless of who said it first, there is truth in this funny statement. Similar expressions can sometimes mean different things in the U.K and the U.S.

Независимо от того, кто был первым, в этом забавном высказывании есть доля правды. Похожие выражения нередко означают совершенно разные вещи в Великобритании и США.

For example, the term to table means one thing in Britain, while it means the exact opposite in the United States.

Например, выражение to table в Великобритании означает одно, а в Соединенных Штатах – совершенно противоположное.

When Britain’s parliament wishes to consider an issue for discussion, members vote «to table it.» On the other hand, when the United States Senate or House of Representatives votes «to table» a proposal, lawmakers decide to set aside the plan or even kill it altogether.

Когда члены британского парламента хотят предложить вопрос для рассмотрения, они голосуют за что, чтобы вынести его на обсуждение (table it). И наоборот, если Сенат или Палата представителей США голосуют за то, чтобы снять проект с обсуждения (table it), то законодатели решили отложить задуманный план или вовсе от него отказаться.

These differences led to misunderstandings between the two countries shortly after the United States entered World War II.

Такие различия приводили ко множеству недоразумений между двумя странами вскоре после того, как Соединенные Штаты вступили во Вторую мировую войну.

As the Americans and British began to develop joint military plans, the term «to table» usually required a clearer explanation. There were British proposals that the Americans were strongly opposed to. They did not even want to discuss them. Respectfully, they said, «Let’s table them.»

Когда американцы и британцы начали разработку совместных военных планов, выражение «to table» обычно требовало уточнения. Американцы были категорически против некоторых идей, предложенных британцами. Они даже не хотели их обсуждать. Они вежливо отвечали: «Let’s table them — Давайте отложим их на потом».

The British were happy to hear that. They thought the Americans were ready to give the proposals serious considerations. Boy, were they wrong!

Британцы были рады такому ответу. Они думали, что американцы были открыты к серьезному рассмотрению их предложений. Ох, как они ошибались!

For a time, the misunderstandings could be troublesome. But in time, the two sides grew to understand what each meant by the expression «to table.» And communications between them improved.

Какое-то время эти недопонимания могли быть источником напряжения. Но со временем обе стороны научились различать, что каждая из них имела в виду, говоря «to table». И связь между ними наладилась.

So did their military situation. In time, the Allies turned the tables on Nazi Germany. After being on the defensive for a long time, allied forces moved forward to take the offensive on all battle fronts.

Как и военная обстановка. К этому времени антигитлеровская коалиция поменялась ролями (turned the tables) с нацистской Германией. После длительной обороны союзные войска стали выдвигаться и переходить в наступление по всем фронтам.

The Allies turned the tables on German forces and defeated them.

Союзники поменялись ролями с немецкими войсками и нанесли им поражение.

The expression «to turn the tables» means to give opponents the same treatment they have been giving you. This saying comes from a popular 16th century card game.

Выражение «to turn the tables» означает поражать противника его же собственными методами. Эта фраза появилась благодаря популярной карточной игре шестнадцатого века.

In the game, a player might have found themselves in a worse position than his opponent. And so, turning the board, or table, around put the other person in the same position.

Во время игры можно было оказаться в худшем положении, чем противник. И, в прямом смысле развернув доску или стол, поставить противника в ваше положение.

Now, let us hear this expression used in an everyday conversation.

А теперь давайте послушаем, как это выражение используется в повседневной речи.

A: Hey did you watch your boss’s television interview about education reform?

А ты видел интервью твоей начальницы о реформе образования по телевизору?

B: Not yet. I hate watching her speak to reporters. Most of them are unfair and unprepared.

Еще нет. Я терпеть не могу слушать ее разговоры с репортерами. Почти все они пристрастны и плохо подготовлены.

A: Well, your boss was ready for them. She turned the tables on all of them. She brought all her facts and knowledge about the issue to the table. She supplied hard evidence that proved their accusations wrong.

Вообще-то, она была готова к разговору с ними. Она повернула ситуацию в свою сторону, поменявшись ролями со всеми ними. Она выложила все свои знания и факты по вопросу. Она привела веские доказательства в опровержение их обвинений.

B: In that case, I’ll watch that interview right away! Nothing is better than seeing the tables turn against unfair reporters.

Если так, то я сейчас же посмотрю интервью! Нет ничего лучше, чем видеть, как кто-то ставит на место этих предвзятых репортеров.

So the expression «turn the tables» comes from a game and so does the expression cards on the table.

Итак, выражение «turn the tables» берет свое начало из игры, как и выражение cards on the table (раскрыть карты; рассказать все начистоту, как есть).

If we put our cards on the table we lay everything out in plain view. Nothing is hidden. However, people who want to keep their plans secret, deal under the table. This expression is used to describe dishonest activities, such as cheating.

Раскрывая все свои карты (put our cards on the table), мы выкладываем всем, что у нас есть. Никаких секретов. Однако, те, кто намеревается держать свои планы в тайне, действует из-под полы (deal under the table). Это выражение используется при описании непорядочных занятий, таких, как мошенничество.

An employer who pays a worker under the table is paying them illegally without taking out taxes.

Работодатель, который платит своим сотрудникам зарплату из-под полы (under the table), делает это незаконно, чтобы избежать налогов.

But if you bring something to a party, you don’t put it under the table. You put it on the table. Often when people are invited to parties, they bring something to eat or drink to share. Whether it is a bottle of wine or a chocolate cake, these gifts go on a table for everyone to enjoy.

Но если вы принесли угощение на какое-то празднество, вы не поставите его под стол. Вы поставите его на стол. Часто, будучи приглашенными на торжество, люди приносят с собой какую-нибудь еду или выпивку для всех остальных. Бутылка ли это вина или шоколадный торт, эти подарки находят себе место на общем столе.

In American English, however, what you bring to the table is not limited to food or something to drink.

В американском английском, однако, то, что вы приносите на стол (bring to the table) не ограничивается едой и напитками.

What you bring to the table can be interesting stories, personal knowledge of a subject or a witty sense of humor. These things all make the event better. So, people who bring something to the table are those who bring something of value to a party, a meeting or event.

То, что вы предлагаете к столу, может быть интересными историями, глубокими познаниями в какой-либо области, или блестящее чувство юмора. Все эти вещи сделают вечер лучше. То есть, люди, которым есть, что предложить (bring something to the table) – это те, кто приносит пользу на вечеринке, встрече или на любом собрании.

On the other hand, if someone does not bring anything of value to a gathering, for whatever reason, we can say that person brings nothing to the table.

И наоборот, если кто-то не привносит в компанию ничего стоящего, по какой бы то ни было причине, мы можем сказать, что такому человеку нечего предложить (brings nothing to the table).

You might ask, what does VOA Learning English bring to the table? We create stories and programs every day that hopefully help you improve your English.

Возможно, у вас возникнет вопрос – а что полезного в программах VOA Learning English? Мы каждый день представляем рассказы и программы, которые, как мы надеемся, помогут вам улучшить ваши знания английского языка.

Thanks for listening. I’m Anna Matteo.

Спасибо, что слушали нас. Меня зовут Анна Маттео.

In this video, an English lesson for foreign language speakers teaches viewers expressions using the work «table.» There are three different expressions taught through watching, listening and defining.
-Pay someone under the table.
— Lay your cards on the table.
-Bring something to the table.
The viewer watches a conversation and tries to interpret the meaning of the expressions based on the conversation. A multiple choice question is provided to guess at the meaning, and a review session after the individual phrases are discussed. The entire video is subtitled for additional understanding to ESL viewers. This is a good way to learn phrases that may not make sense in a simple translation.

Want to master Microsoft Excel and take your work-from-home job prospects to the next level? Jump-start your career with our Premium A-to-Z Microsoft Excel Training Bundle from the new Gadget Hacks Shop and get lifetime access to more than 40 hours of Basic to Advanced instruction on functions, formula, tools, and more.

Buy Now (97% off) >

Other worthwhile deals to check out:

  • 97% off The Ultimate 2021 White Hat Hacker Certification Bundle
  • 98% off The 2021 Accounting Mastery Bootcamp Bundle
  • 99% off The 2021 All-in-One Data Scientist Mega Bundle
  • 59% off XSplit VCam: Lifetime Subscription (Windows)
  • 98% off The 2021 Premium Learn To Code Certification Bundle
  • 62% off MindMaster Mind Mapping Software: Perpetual License
  • 41% off NetSpot Home Wi-Fi Analyzer: Lifetime Upgrades

In a MS Word (2016) subroutine (macro), I am trying to confirm if a table containing the current user selection on a subsequent macro call is the same table as the one selected on a previous call and preserved in static variables.

I confirm that the selection is within a table using .Information and have saved the previous table as a Variant object Set Tbl1 = Selection.Tables(1). However, when I try to test if the second table is the same object using Tbl1 Is Tbl2, the result is False even when the tables are known to be the same and no other changes have occurred to the document.

Moreover, even (in a document containing several tables) the test ActiveDocument.Tables(1) Is ActiveDocument.Tables(1) results in False, when I would expect these to be exactly the same Object. Compare Excel ActiveSheet.ListObjects(1) Is ActiveSheet.ListObjects(1) which is True.

Can anyone explain this (or reveal the error in my test)?

I could solve my identification problem by, eg, comparing some table content or feature, but this is unreliable (due to possible replication in another table), or by uniquely setting an often unused table property, eg, .Descr or .Title, or by wrapping the table in a Bookmark (which is at least uniquely identifiable by its .Name, though Bookmarks, too, fail the Is test above), but I would rather not have to modify the table or the document simply in order to do the test. I could also compare the table locations, eg, by Tbl1.Range.Start, but this also could be unreliable if the document has been modified between selections/calls. Any other suggestions? Does Word not have any kind of unique table identifier/property?

Added background:-

I frequently have long Word tables (maybe over several pages) in which I have merged (some) cells horizontally and/or vertically. If I later need to change the width of a ‘notional’ column, this can be very tedious, especially if several shorter tables have been joined and the notional columns don’t even align. NB I appreciate that Word doesn’t preserve any understanding of the uniform, rectangular column structure that would have existed before any merging — a ‘merged’ cell is just another cell, and a ‘merged’ table simply has varying numbers of odd-sized cells (‘columns’) per row; and it’s even messier with vertical merging.

Even though Word has a nice facility to click & drag a left/right cell boundary, and all cell ‘columns’ with the same position will move together, this is awkward to use successfully on long tables, especial if they have similar but not identical cell boundaries. So I wanted to write a macro that would let me pre-set desired boundaries for ‘notional’ columns (eg, using the widths of a reference row having the maximum number of cells) and apply them to the whole table, making allowance for ‘merged’ cells that appeared to span more than one of these reference row columns. I anticipated that I might not find a fully successful algorithm for doing this and that I might keep having to relinquish control to the user to manually adjust ‘awkward’ rows and then restart the automatic process. Hence the need to verify that, when the macro is re-called, the same table is being worked on (even though some aspects of it have changed).

There are several ways round this identification problem that are probably good enough in practice (eg, based on range start/end points, etc) but I was intrigued that my initial supposition that I would be able to compare Table objects directly (as I thought I could in Excel) didn’t seem to work in Word. I am surprised that a Word table doesn’t seem to maintain an ‘identity’ that survives document editing, either inside or outside the table.

Further Info:-

In Excel, where cell D6 is within a table and is selected:
ActiveSheet.ListObjects(1) Is ActiveSheet.ListObjects(1) -> true;
Range("D6").ListObject Is Range("D6").ListObject -> false;
Selection.ListObject Is Selection.ListObject -> false.

So, even here, some ‘derived’ objects (eg, table from cell or selection) do not seem to be exactly equivalent even though they purport to represent the same entity on the worksheet. It would still be nice to have some technical explanation for these phenomena, if anyone can oblige, but it seems clear that I cannot just compare objects using Is in the way I was hoping.

Reading Time: 8 minutes

Common Table Expressions (CTE’s) are a very useful tool available to us when querying databases in Microsoft SQL Server. CTE’s can help you gather the information you want quickly without needing to write much code, or persist an object in the database.

Common Table Expressions are just one type of table expression we have available to us in SQL Server. For an introduction to all the different kinds of table expressions, take a look at the full beginner-friendly tutorial:

SQL Server Table Expressions: The Ultimate Guide for Beginners

In this tutorial, we will answer the following questions about CTE’s:

  1. What is a Common Table Expression?
  2. What is the syntax for creating a Common Table Expression?
  3. How can Common Table Expressions help us?
  4. What are the limitations of a Common Table Expression?
  5. Tips, tricks and links

Make sure you also download your FREE GUIDE:

FREE 1-page Simple SQL Cheat Sheet on SQL Server Table Expressions!

This guide contains all the key points you need to understand about all the different table expressions you can create within Microsoft SQL Server, including CTE’s, condensed into a simple 1 page guide. Make sure you download it today!

Let’s dive in.

1. What is a Common Table Expression?

A Common Table Expression (better known as a CTE) is a temporary table expression that is defined directly above an outer query. The CTE contains an inner query, and is given an alias. That alias is referenced in the FROM clause of the outer query. 

A CTE is not persisted in the database as an object. They are similar to derived tables in that way. As soon as the outer query completes, the CTE falls out of scope and cannot be used again.

This is different from a View or an Inline Table Valued function where the table expression is created as a database object, and can be used repeatedly.

2. What is the syntax of a Common Table Expression?

It’s a little strange:

;WITH <CTE alias name>
AS
(
<inner query>
)
SELECT <column list> FROM <CTE alias name>

Let’s break this down, starting from the top.

No, the semicolon in front of the word ‘WITH‘ is not a typo.

The word ‘WITH‘ is actually a keyword in SQL Server. In the definition of the CTE, if we tried to use the word WITH by itself, SQL Server would get confused and give us an error message. Therefore, we need to put a semicolon in front of it, which officially terminates any statements that exist in your query window before the CTE.

This is just one of those things you will need to remember about CTE’s: When you create a CTE, always precede the word ‘WITH‘ with a semicolon.

(The only way you could get away with not putting a semicolon in front of the word WITH is when the CTE is the first query in your query window. But just do yourself a favor and forget about that exception)

Moving on.

The Name of your CTE can be anything you want it to be. You’ll want to be a good programmer and name it something meaningful, though. Don’t just make the name a single letter, like ‘C‘. That’s bad practice.

The inner query of your CTE is defined within parentheses. This is the query whose result set will serve as the actual table expression, represented by the name of your CTE.

Finally, we have the outer query. This must be directly below the ending parentheses of your inner query. This outer query will reference the name of the CTE in the FROM clause (just like how a normal table is referenced).

But the best way to understand this is to actually try it out! Let’s look at some examples in the next section.

3. How can Common Table Expressions help us?

Here is our first simple example of a a CTE:

simple common table expression example

The inner query of our CTE simply pulls the Customer ID and Email address for Customers that have an email address. We give that result set a name, CustomersWithEmail.

Then, in the outer query, we query that table expression name just like we would any other table: In the FROM clause.

This is one of the reasons I prefer to use CTE’s over derived tables. I think the syntax of the outer query reads a bit easier since it is the same as it would be for any other table.

But that example doesn’t really show us the full benefit of using a CTE. Take a look at this CTE:

common table expression example

The inner query hasn’t changed, but our outer query has.

We used the results of our CTE in a JOIN with the Customers table to get the First Name and Last Name of our Customers with an Email address.

See how clean that outer query is?

If we wanted to get the same results through using a derived table instead, we would need to do this:

using derived table instead of CTE

Not as clean, in my opinion.

But cleanliness isn’t the only thing we need to worry about. Sometimes a CTE just makes things easier.

Take this example:

order month using common table expression

Let’s talk about what this code does. In the inner query, we query the Orders table that has an OrderDate column. We use the DATENAME system function to get the actual name of the month for each order. For example, an order made on 9/21/2020 will have a month name of ‘September‘.

We also filter our results in the inner query to show orders placed in 2020 only.

So when that inner query completes, we’ll see the month name of all our orders placed in 2020. We can actually highlight that inner query and run it by itself to show you the results:

 just inner query of common table expression

Cool. The next thing to look at is the the work done in our outer query. The outer query simply counts the number of orders placed in each month for 2020 and returns the results. Here are those results again:

order month using common table expression

The outer query is clean again, which is good, but think about what we would need to do if we didn’t use a CTE.

In our outer query, we use the ‘OrderMonth‘ column twice: Once in the SELECT list, and another time in the GROUP BY clause.

But remember, it took some effort in the inner query to figure out the OrderMonth value.

So If we didn’t use a CTE, we would have needed to repeat that effort to get the same results:

not using cte repeating code

There is a golden rule you need to remember when coding: Don’t repeat yourself!

4. What are the limitations of a Common Table Expression?

We need to discuss some of the rules about the inner query of a CTE. These aren’t really limitations. They are simply rules you need to follow:

  1. In your inner SELECT statement, your columns must all have names. If one of your columns is the result of a calculation or an aggregation, you need to make sure you give that column an alias.
  2. Also when it comes to columns, your column names must be unique. You can’t have two or more columns in your inner SELECT statement with the same name.
  3. You can’t have an ORDER BY clause in your inner SELECT statement. The only exception to this rule is if there was also TOP or OFFSET-FETCH used in your SELECT list.

The only actual limitation is that the life of your CTE ends when the outer query falls out of scope.

There is no persisting object created in the database. Sometimes that’s exactly what you want, but sometimes it isn’t.

For example, this doesn’t work:

common table expression end of life

It doesn’t matter that the second SELECT statement was ran in the same batch. The CTE ended with the completion of the outer query, which was SELECT * FROM CustomersWithEmail. We cannot use the CTE again after that!

5. Tips, tricks and links

Here is a list of some helpful tips and tricks you should know when working with CTE’s:

Tip # 1: Your column aliases can be external

Let’s look at this example of a CTE again:

Common table expression before external alias

Notice our alias ‘OrderMonth‘. This is an Internal alias, meaning it is directly next to the derived column in the SELECT list.

But here is how you would set it up if you wanted the alias to be external:

common table expression external alias

You put the names of your columns in parentheses next to the alias of the CTE.

Notice we need to outline all the columns, and not just the one that is the result of our DATENAME function.

By the way, if you put aliases both externally and internally (because you like to party), the external aliases will take precedence.

Tip # 2: You can define multiple CTE’s at once

You would separate them by a comma. Here is an example:

multiple common table expressions

First, we have a CTE with the alias ProductInfo. After the closing parentheses of that CTE, we have a comma, then another CTE named OrderInfo.

After the closing parentheses for that second CTE, we have our outer query.

There are two things to be aware of when you have multiple CTE’s:

  • A CTE can refer to any CTE that came before it. For instance, our OrderInfo CTE refers to the first ProductInfo CTE. I underlined that reference in red.
  • The outer query can refer to any CTE. Again , underlined in red, we see how our outer query referred to both the OrderInfo CTE and the ProductInfo CTE.

Kinda neat, right?

Links

There is a great book called T-SQL Fundamentals written by Itzik Ben-Gan that goes over several core concepts you should know about SQL Server, Common Table Expressions. The book actually has an entire chapter dedicated to the discussion of all the different table expressions. You won’t regret owning this book, trust me. Definitely get it today!

Next Steps:

Leave a comment if you found this tutorial helpful!

If you found this tutorial helpful, make sure you download your FREE GUIDE:

FREE 1-page Simple SQL Cheat Sheet on SQL Server Table Expressions!

The guide contains all the key points you need to understand about all the different table expressions you can create within Microsoft SQL Server, including CTE’s, condensed into a simple 1 page guide. Make sure you download it today!

Don’t forget to read up on Derived Tables, too. They are another great querying tool!

Also see my tutorials on Views and Inline Table Valued Functions, which are also table expressions. These objects are actually persisted in the database, unlike CTE’s:

What is  a View in SQL Server? A Guide for Beginners

Inline Table Valued Functions: The Ultimate Guide for Beginners 

Thank you very much for reading!

Make sure you subscribe to my newsletter to receive special offers and notifications anytime a new tutorial is released!

If you have any questions, please don’t hesitate to leave a comment, or better yet, send me an email!

Создание таблиц в документе Word из кода VBA Excel. Метод Tables.Add, его синтаксис и параметры. Объекты Table, Column, Row, Cell. Границы таблиц и стили.

Работа с Word из кода VBA Excel
Часть 4. Создание таблиц в документе Word
[Часть 1] [Часть 2] [Часть 3] [Часть 4] [Часть 5] [Часть 6]

Таблицы в VBA Word принадлежат коллекции Tables, которая предусмотрена для объектов Document, Selection и Range. Новая таблица создается с помощью метода Tables.Add.

Синтаксис метода Tables.Add

Expression.Add (Range, Rows, Columns, DefaultTableBehavior, AutoFitBehavior)

Expression – выражение, возвращающее коллекцию Tables.

Параметры метода Tables.Add

  • Range – диапазон, в котором будет создана таблица (обязательный параметр).
  • Rows – количество строк в создаваемой таблице (обязательный параметр).
  • Columns – количество столбцов в создаваемой таблице (обязательный параметр).
  • DefaultTableBehavior – включает и отключает автоподбор ширины ячеек в соответствии с их содержимым (необязательный параметр).
  • AutoFitBehavior – определяет правила автоподбора размера таблицы в документе Word (необязательный параметр).

Создание таблицы в документе

Создание таблицы из 3 строк и 4 столбцов в документе myDocument без содержимого и присвоение ссылки на нее переменной myTable:

With myDocument

Set myTable = .Tables.Add(.Range(Start:=0, End:=0), 3, 4)

End With

Создание таблицы из 5 строк и 4 столбцов в документе Word с содержимым:

With myDocument

myInt = .Range.Characters.Count 1

Set myTable = .Tables.Add(.Range(Start:=myInt, End:=myInt), 5, 4)

End With

Для указания точки вставки таблицы присваиваем числовой переменной количество символов в документе минус один. Вычитаем единицу, чтобы исключить из подсчета последний знак завершения абзаца (¶), так как точка вставки не может располагаться за ним.

Последний знак завершения абзаца всегда присутствует в документе Word, в том числе и в новом без содержимого, поэтому такой код подойдет и для пустого документа.

При создании, каждой новой таблице в документе присваивается индекс, по которому к ней можно обращаться:

myDocument.Tables(индекс)

Нумерация индексов начинается с единицы.

Отображение границ таблицы

Новая таблица в документе Word из кода VBA Excel создается без границ. Отобразить их можно несколькими способами:

Вариант 1
Присвоение таблице стиля, отображающего все границы:

myTable.Style = «Сетка таблицы»

Вариант 2
Отображение внешних и внутренних границ в таблице:

With myTable

.Borders.OutsideLineStyle = wdLineStyleSingle

.Borders.InsideLineStyle = wdLineStyleSingle

End With

Вариант 3
Отображение всех границ в таблице по отдельности:

With myTable

.Borders(wdBorderHorizontal) = True

.Borders(wdBorderVertical) = True

.Borders(wdBorderTop) = True

.Borders(wdBorderLeft) = True

.Borders(wdBorderRight) = True

.Borders(wdBorderBottom) = True

End With

Присвоение таблицам стилей

Вариант 1

myTable.Style = «Таблица простая 5»

Чтобы узнать название нужного стиля, в списке стилей конструктора таблиц наведите на него указатель мыши. Название отобразится в подсказке. Кроме того, можно записать макрос с присвоением таблице стиля и взять название из него.

Вариант 2

myTable.AutoFormat wdTableFormatClassic1

Выбирайте нужную константу с помощью листа подсказок свойств и методов – Auto List Members.

Обращение к ячейкам таблицы

Обращение к ячейкам второй таблицы myTable2 в документе myDocument по индексам строк и столбцов:

myTable2.Cell(nRow, nColumn)

myDocument.Tables(2).Cell(nRow, nColumn)

  • nRow – номер строки;
  • nColumn – номер столбца.

Обращение к ячейкам таблицы myTable в документе Word с помощью свойства Cell объектов Row и Column и запись в них текста:

myTable.Rows(2).Cells(2).Range = _

«Содержимое ячейки во 2 строке 2 столбца»

myTable.Columns(3).Cells(1).Range = _

«Содержимое ячейки в 1 строке 3 столбца»

В таблице myTable должно быть как минимум 2 строки и 3 столбца.

Примеры создания таблиц Word

Пример 1
Создание таблицы в новом документе Word со сплошными наружными границами и пунктирными внутри:

Sub Primer1()

Dim myWord As New Word.Application, _

myDocument As Word.Document, myTable As Word.Table

  Set myDocument = myWord.Documents.Add

  myWord.Visible = True

With myDocument

  Set myTable = .Tables.Add(.Range(0, 0), 5, 4)

End With

With myTable

  .Borders.OutsideLineStyle = wdLineStyleSingle

  .Borders.InsideLineStyle = wdLineStyleDot

End With

End Sub

В выражении myDocument.Range(Start:=0, End:=0) ключевые слова Start и End можно не указывать – myDocument.Range(0, 0).

Пример 2
Создание таблицы под ранее вставленным заголовком, заполнение ячеек таблицы и применение автосуммы:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

Sub Primer2()

On Error GoTo Instr

Dim myWord As New Word.Application, _

myDocument As Word.Document, _

myTable As Word.Table, myInt As Integer

  Set myDocument = myWord.Documents.Add

  myWord.Visible = True

With myDocument

‘Вставляем заголовок таблицы

  .Range.InsertAfter «Продажи фруктов в 2019 году» & vbCr

  myInt = .Range.Characters.Count 1

‘Присваиваем заголовку стиль

  .Range(0, myInt).Style = «Заголовок 1»

‘Создаем таблицу

  Set myTable = .Tables.Add(.Range(myInt, myInt), 4, 4)

End With

With myTable

‘Отображаем сетку таблицы

  .Borders.OutsideLineStyle = wdLineStyleSingle

  .Borders.InsideLineStyle = wdLineStyleSingle

‘Форматируем первую и четвертую строки

  .Rows(1).Range.Bold = True

  .Rows(4).Range.Bold = True

‘Заполняем первый столбец

  .Columns(1).Cells(1).Range = «Наименование»

  .Columns(1).Cells(2).Range = «1 квартал»

  .Columns(1).Cells(3).Range = «2 квартал»

  .Columns(1).Cells(4).Range = «Итого»

‘Заполняем второй столбец

  .Columns(2).Cells(1).Range = «Бананы»

  .Columns(2).Cells(2).Range = «550»

  .Columns(2).Cells(3).Range = «490»

  .Columns(2).Cells(4).AutoSum

‘Заполняем третий столбец

  .Columns(3).Cells(1).Range = «Лимоны»

  .Columns(3).Cells(2).Range = «280»

  .Columns(3).Cells(3).Range = «310»

  .Columns(3).Cells(4).AutoSum

‘Заполняем четвертый столбец

  .Columns(4).Cells(1).Range = «Яблоки»

  .Columns(4).Cells(2).Range = «630»

  .Columns(4).Cells(3).Range = «620»

  .Columns(4).Cells(4).AutoSum

End With

‘Освобождаем переменные

Set myDocument = Nothing

Set myWord = Nothing

‘Завершаем процедуру

Exit Sub

‘Обработка ошибок

Instr:

If Err.Description <> «» Then

  MsgBox «Произошла ошибка: « & Err.Description

End If

If Not myWord Is Nothing Then

  myWord.Quit

  Set myDocument = Nothing

  Set myWord = Nothing

End If

End Sub

Метод AutoSum суммирует значения в ячейках одного столбца над ячейкой с суммой. При использовании его для сложения значений ячеек в одной строке, результат может быть непредсказуемым.

Чтобы просуммировать значения в строке слева от ячейки с суммой, используйте метод Formula объекта Cell:

myTable.Cell(2, 4).Formula («=SUM(LEFT)»)

Другие значения метода Formula, применяемые для суммирования значений ячеек:

  • «=SUM(ABOVE)» – сумма значений над ячейкой (аналог метода AutoSum);
  • «=SUM(BELOW)» – сумма значений под ячейкой;
  • «=SUM(RIGHT)» – сумма значений справа от ячейки.


Понравилась статья? Поделить с друзьями:
  • Expressions with the word story
  • Expressions with the word sleep
  • Expressions with the word set
  • Expressions with the word search
  • Expressions with the word say